@cmmd-center/forge 0.13.75 → 0.13.76

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.
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/__vite-browser-external-2W3EstLn.js","assets/rolldown-runtime-hePW80VL.js","assets/transport-CgH8pQK3.js","assets/workspaceReadinessAtom-D6bgTvKb.js","assets/atomRegistry-C1yW8tyM.js","assets/Stream-mUTFnSY9.js","assets/angular-html-B8mrqUL5.js","assets/html-XwrE-1r6.js","assets/javascript-obGGvMPs.js","assets/css-CNuuLpMC.js","assets/angular-ts-Bzix210W.js","assets/scss-YesllqfO.js","assets/apl-Dhin1L29.js","assets/xml-BlnrEAEy.js","assets/java-DdHNQ9hk.js","assets/json-DAgxKhMr.js","assets/astro-B-4NNgOP.js","assets/typescript-BydbNFcO.js","assets/postcss-BXeXVLqQ.js","assets/tsx-CUOciP0b.js","assets/blade-Wr94ul2N.js","assets/html-derivative-i4STDFnl.js","assets/sql-ClgswhA6.js","assets/bsl-BkkzgIyY.js","assets/sdbl-bTVj8UrX.js","assets/c-iCihek07.js","assets/cairo-DLTphjLi.js","assets/python-gzcpVVnB.js","assets/cobol-Cw2-KvLW.js","assets/coffee-CiiSLhB6.js","assets/cpp-DjoE5qBx.js","assets/regexp-DR20uMnK.js","assets/glsl-D5MA2a_X.js","assets/crystal-wCJpIkgB.js","assets/shellscript-Da78Ox-3.js","assets/edge-DCY0a-ow.js","assets/elixir-DP304Xio.js","assets/elm-o4NJxfws.js","assets/erb-BcNYoZVd.js","assets/ruby-2bd251b9.js","assets/haml-CwEpbK1d.js","assets/graphql-Ctjuxyvl.js","assets/jsx-gTgmArGx.js","assets/lua-FONpmTUP.js","assets/yaml-Du_6cdrH.js","assets/erlang-Cphh6RMH.js","assets/markdown-BYOwaDjH.js","assets/fortran-fixed-form-DEKoE2YW.js","assets/fortran-free-form-CYNrtFtB.js","assets/fsharp-D13ZGOAj.js","assets/gdresource-C0sCabJj.js","assets/gdshader-CBce3t8t.js","assets/gdscript-Cp2uCuqX.js","assets/git-commit-BSykSTBG.js","assets/diff-woXpYk--.js","assets/git-rebase-BDPpS8w6.js","assets/glimmer-js-BONyzAsu.js","assets/glimmer-ts-f9c0GCOe.js","assets/hack-7ztQ7Up-.js","assets/handlebars-ryMP1rBR.js","assets/http-kmH8AyfE.js","assets/hurl-DCZHXKU4.js","assets/csv-Dx-8-gkx.js","assets/hxml-B0Qn7Nwc.js","assets/haxe-OTjmBuCE.js","assets/jinja-B-tLrNsM.js","assets/jison-CBjhYtSs.js","assets/julia-CjHxn3vf.js","assets/r-D6UWEOL2.js","assets/just-CZ9bduw9.js","assets/perl-BAov3eih.js","assets/latex-D9bvcAJr.js","assets/tex-0w6-Dtgt.js","assets/liquid-G0MH4h_m.js","assets/marko-DV5GrDmo.js","assets/less-DVTAwKKz.js","assets/mdc-cg1lnqpW.js","assets/nextflow-BJtWHP5T.js","assets/nextflow-groovy-DJMQeKeT.js","assets/nginx-BTMw9COX.js","assets/nim-B6yJ_yaC.js","assets/php-Cg76ANFt.js","assets/pug-DkgDHZci.js","assets/qml-_a-QhfPD.js","assets/razor-D3EoCAik.js","assets/csharp-Ct8U2NOr.js","assets/rst-YTmaoyaq.js","assets/cmake-Bj61d0ZC.js","assets/sas-B6p8-ynO.js","assets/shaderlab-TOUzSsQk.js","assets/hlsl-Cvrh5tZx.js","assets/shellsession-CVsQGYfZ.js","assets/soy-DEd-qcad.js","assets/sparql-D_iOobhT.js","assets/turtle-ByJddavk.js","assets/stata-RoaAgbqU.js","assets/surrealql-DIn4NJsS.js","assets/svelte-Bj3Hmc9F.js","assets/templ-TjxbArHn.js","assets/go-rLFTqkRN.js","assets/ts-tags-DFwAVxhO.js","assets/twig-BbcH-NR0.js","assets/vue-BNi0qJZP.js","assets/vue-html-DkKkQnZL.js","assets/vue-vine-DFaKYU4X.js","assets/stylus-B6D30XZt.js","assets/xsl-BOPS8gLt.js"])))=>i.map(i=>d[i]);
2
- import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$t as i,Aa as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as h,Di as g,Dn as _,Dt as v,Ei as y,En as b,Er as x,Et as S,F as C,Fa as w,Fi as T,Fn as E,Fr as D,Ft as ee,Gn as te,Gt as ne,Ha as O,Hn as k,Hr as re,Ht as A,Ia as ie,Ir as ae,It as oe,J as se,Jn as ce,Jt as le,K as ue,Kn as de,Kt as fe,L as pe,La as me,Ln as he,Lr as ge,Lt as _e,M as ve,Ma as ye,Mi as be,Mr as xe,Mt as Se,N as Ce,Ni as we,Nn as eee,Nt as Te,O as tee,Oa as nee,On as ree,Ot as iee,P as aee,Pa as oee,Pi as Ee,Pn as De,Pt as Oe,Qi as ke,Qn as Ae,Qt as see,R as je,Rn as Me,Rr as Ne,Rt as cee,Si as lee,Sn as uee,T as Pe,Ta as Fe,Tn as dee,Tr as Ie,Tt as Le,U as Re,Ua as fee,Un as ze,Ur as Be,Ut as pee,V as mee,Va as Ve,Vn as He,Vr as Ue,Vt as We,W as Ge,Wa as hee,Wn as gee,Wr as _ee,Wt as vee,X as yee,Xn as bee,Y as xee,Yi as Ke,Yn as qe,Yt as See,Z as Je,Zi as Cee,Zn as wee,Zt as Tee,_ as Eee,_a as Ye,_n as Dee,_r as Oee,_t as kee,an as Aee,at as Xe,bn as jee,br as Mee,bt as Ze,ca as Qe,ci as $e,cn as Nee,ct as et,di as Pee,dn as Fee,dr as Iee,dt as tt,ea as nt,ei as Lee,en as rt,er as Ree,et as zee,fi as it,fr as Bee,ft as at,gi as ot,gn as st,gt as ct,hn as lt,hr as ut,ht as dt,in as ft,it as Vee,j as pt,ja as Hee,jn as mt,jr as Uee,jt as ht,ki as gt,kr as Wee,kt as _t,li as vt,ln as Gee,m as Kee,mn as yt,mr as bt,mt as xt,na as qee,ni as Jee,nr as St,nt as Ct,oa as Yee,on as Xee,or as wt,pi as Zee,pn as Tt,pt as Et,q as Dt,qn as Ot,qt as Qee,r as $ee,ri as ete,rn as kt,rr as tte,rt as nte,s as rte,si as ite,sn as ate,st as At,ui as ote,un as jt,ut as Mt,vn as Nt,vr as ste,vt as cte,w as Pt,wn as lte,wr as ute,wt as Ft,x as dte,xi as fte,xn as It,y as pte,yi as mte,yn as Lt,yt as hte,z as Rt,zn as gte,zt as _te}from"./Stream-mUTFnSY9.js";import{i as vte,l as zt,n as Bt,o as Vt,s as Ht}from"./atomRegistry-C1yW8tyM.js";import{En as yte,Fn as Ut,J as Wt,On as bte,Rn as xte,Tn as Gt,an as Kt,cn as Ste,dn as qt,fn as Jt,gn as Cte,hn as Yt,i as wte,ln as Tte,on as Ete,sn as Xt,un as Dte}from"./CompositeItem-B_Qce_Zi.js";import{$n as Zt,$t as Ote,A as Qt,An as kte,At as $t,Bn as Ate,Bt as jte,C as Mte,Ct as Nte,D as en,Dn as tn,Dt as nn,En as rn,Et as an,Fn as on,Ft as Pte,Gn as Fte,Gt as sn,H as cn,Hn as Ite,Ht as ln,In as un,It as dn,Jn as Lte,Jt as Rte,Kt as fn,L as zte,Ln as pn,Lt as Bte,Mn as Vte,Mt as mn,Nt as Hte,O as hn,On as gn,Pn as _n,Pt as Ute,Qt as Wte,Rn as Gte,Rt as Kte,St as vn,Tn as yn,Tt as bn,U as qte,Un as Jte,Ut as xn,V as Sn,Vn as Yte,Vt as Cn,W as Xte,Wn as Zte,Wt as wn,Xt as Tn,Y as Qte,Yt as $te,Z as ene,Zt as tne,_n as j,_t as En,a as nne,an as Dn,b as On,bn as kn,c as An,cn as jn,d as rne,dt as Mn,en as ine,et as ane,f as one,fn as Nn,g as sne,gn as Pn,gt as cne,hn as Fn,ht as In,i as lne,in as une,j as Ln,jn as Rn,jt as zn,k as dne,kn as fne,kt as Bn,l as Vn,ln as Hn,lt as Un,m as pne,mn as Wn,nn as mne,nt as Gn,o as Kn,on as qn,p as hne,pn as gne,pt as _ne,q as vne,qt as Jn,rn as yne,s as M,sn as Yn,tn as Xn,tt as Zn,u as Qn,ut as $n,v as er,vn as tr,w as bne,wn as nr,x as xne,xn as rr,yn as Sne,yt as Cne,z as wne,zt as ir}from"./src-IM0FnQax.js";import{A as ar,C as Tne,D as or,F as Ene,I as Dne,L as sr,M as cr,N as One,O as lr,S as kne,T as ur,a as dr,b as Ane,c as jne,d as Mne,j as fr,k as pr,l as Nne,n as mr,s as Pne,u as Fne,v as Ine,x as Lne,y as Rne}from"./cmmdAuthRedirect-lzr9SGGx.js";import{t as N}from"./preload-helper-Czpn1I53.js";import{n as P,t as hr}from"./transport-CgH8pQK3.js";import{n as zne,t as Bne}from"./workspaceReadinessAtom-D6bgTvKb.js";function Vne(e){return e[e.length-1]}function Hne(e,t){return typeof e==`function`?e(t):e}var gr=Object.prototype.hasOwnProperty,Une=Object.prototype.propertyIsEnumerable;function Wne(e){for(let t in e)if(gr.call(e,t))return!0;return!1}var Gne=()=>Object.create(null),Kne=(e,t)=>_r(e,t,Gne);function _r(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=xr(e)&&xr(i);if(!a&&!(yr(e)&&yr(i)))return i;let o=a?e:vr(e);if(!o)return i;let s=a?i:vr(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:gr.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=_r(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function vr(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!Une.call(e,r))return!1;t.push(r)}return t}function yr(e){if(!br(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!br(n)||!n.hasOwnProperty(`isPrototypeOf`))}function br(e){return Object.prototype.toString.call(e)===`[object Object]`}function xr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Sr(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!Sr(e[r],t[r],n))return!1;return!0}if(yr(e)&&yr(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Sr(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!Sr(e[o],t[o],n)))return!1;return i===a}return!1}var qne=/[\x00-\x1f\x7f"<>`{}]/g;function Jne(e){return e.replace(qne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Cr(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return Jne(t)}var Yne=[`http:`,`https:`,`mailto:`,`tel:`];function Xne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Zne(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=Cr(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Cr(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Qne(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function $ne(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function wr(){throw Error(`Invariant failed`)}var F=t(hee(),1),Tr=F.createContext(null);function Er(e){return F.useContext(Tr)}var Dr=F.createContext(void 0),ere=F.createContext(void 0),tre=xte();function nre(e,t){return e===t}function Or(e,t,n=nre){let r=(0,F.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,F.useCallback)(()=>e?.get(),[e]);return(0,tre.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var kr={};function Ar(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=_r(n.current,i):i}}function jr(e){let t=Er(),n=F.useContext(e.from?ere:Dr),r=e.from??n,i=t.stores.getMatchStore(r),a=Ar(e,t),o=Or(i,e=>e?a(e):kr);if(o!==kr)return o;(e.shouldThrow??!0)&&wr()}function rre(e){return jr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}var Mr=fee(),Nr=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Pr=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Fr=new class extends Pr{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},ire={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ir=new class{#e=ire;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function are(e){setTimeout(e,0)}var ore=typeof window>`u`||`Deno`in globalThis;function Lr(){}function sre(e,t){return typeof e==`function`?e(t):e}function Rr(e){return typeof e==`number`&&e>=0&&e!==1/0}function zr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Br(e,t){return typeof e==`function`?e(t):e}function Vr(e,t){return typeof e==`function`?e(t):e}function cre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Hr(o,t.options))return!1}else if(!Wr(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function lre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Ur(t.options.mutationKey)!==Ur(a))return!1}else if(!Wr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Hr(e,t){return(t?.queryKeyHashFn||Ur)(e)}function Ur(e){return JSON.stringify(e,(e,t)=>Jr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Wr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Wr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Wr(e[r],t[r]))return!1;return!0}return!1}var ure=Object.prototype.hasOwnProperty;function Gr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=qr(e)&&qr(t);if(!r&&!(Jr(e)&&Jr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ure.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Gr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Kr(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function qr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Jr(e){if(!Yr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Yr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Yr(e){return Object.prototype.toString.call(e)===`[object Object]`}function dre(e){return new Promise(t=>{Ir.setTimeout(t,e)})}function Xr(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Gr(e,t)}function fre(e){return e}function pre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function mre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Zr=Symbol();function Qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Zr?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function $r(e,t){return typeof e==`function`?e(...t):!!e}function hre(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ei=(()=>{let e=()=>ore;return{isServer(){return e()},setIsServer(t){e=t}}})();function ti(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var gre=are;function _re(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=gre,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var ni=_re(),ri=new class extends Pr{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function vre(e){return Math.min(1e3*2**e,3e4)}function ii(e){return(e??`online`)!==`online`||ri.isOnline()}var ai=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function oi(e){let t=!1,n=0,r,i=ti(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ai(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Fr.isFocused()&&(e.networkMode===`always`||ri.isOnline())&&e.canRun(),u=()=>ii(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ei.isServer()?0:3),o=e.retryDelay??vre,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),dre(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var si=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rr(this.gcTime)&&(this.#e=Ir.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ei.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Ir.clearTimeout(this.#e),this.#e=void 0)}};function yre(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{hre(e,()=>t.signal,()=>n=!0)},u=Qr(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?mre:pre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?li:ci,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ci(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ci(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function li(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bre(e,t){return t?ci(e,t)!=null:!1}function xre(e,t){return!t||!e.getPreviousPageParam?!1:li(e,t)!=null}var Sre=class extends si{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fi(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=fi(this.options);e.data!==void 0&&(this.setState(di(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Xr(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Vr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zr||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Br(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!zr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Qr(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?yre(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=oi({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ai&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ai){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...ui(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...di(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),ni.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function ui(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ii(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function di(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function fi(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var pi=class extends Pr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ti(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),mi(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return hi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return hi(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Vr(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Kr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&gi(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Vr(this.options.enabled,this.#t)!==Vr(t.enabled,this.#t)||Br(this.options.staleTime,this.#t)!==Br(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Vr(this.options.enabled,this.#t)!==Vr(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return wre(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Lr)),t}#g(){this.#b();let e=Br(this.options.staleTime,this.#t);if(ei.isServer()||this.#r.isStale||!Rr(e))return;let t=zr(this.#r.dataUpdatedAt,e)+1;this.#d=Ir.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(ei.isServer()||Vr(this.options.enabled,this.#t)===!1||!Rr(this.#p)||this.#p===0)&&(this.#f=Ir.setInterval(()=>{(this.options.refetchIntervalInBackground||Fr.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Ir.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Ir.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&mi(e,t),o=i&&gi(e,n,t,r);(a||o)&&(l={...l,...ui(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=Xr(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=Xr(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:_i(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Vr(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{let e=this.#o=x.promise=ti();i(e)},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a()}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!Kr(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){ni.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Cre(e,t){return Vr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Vr(t.retryOnMount,e)!==!1)}function mi(e,t){return Cre(e,t)||e.state.data!==void 0&&hi(e,t,t.refetchOnMount)}function hi(e,t,n){if(Vr(t.enabled,e)!==!1&&Br(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&_i(e,t)}return!1}function gi(e,t,n,r){return(e!==t||Vr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&_i(e,n)}function _i(e,t){return Vr(t.enabled,e)!==!1&&e.isStaleByTime(Br(t.staleTime,e))}function wre(e,t){return!Kr(e.getCurrentResult(),t)}var vi=F.createContext(void 0),yi=e=>{let t=F.useContext(vi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Tre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Mr.jsx)(vi.Provider,{value:e,children:t})),bi=F.createContext(!1),xi=()=>F.useContext(bi);bi.Provider;function Ere(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Dre=F.createContext(Ere()),Si=()=>F.useContext(Dre),Ci=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?$r(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},wi=e=>{F.useEffect(()=>{e.clearReset()},[e])},Ti=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||$r(n,[e.error,r])),Ei=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Ore=(e,t)=>e.isLoading&&e.isFetching&&!t,Di=(e,t)=>e?.suspense&&t.isPending,Oi=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ki(e,t,n){let r=xi(),i=Si(),a=yi(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Ei(o),Ci(o,i,s),wi(i);let l=!a.getQueryCache().get(o.queryHash),[u]=F.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(F.useSyncExternalStore(F.useCallback(e=>{let t=f?u.subscribe(ni.batchCalls(e)):Lr;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Di(o,d))throw Oi(o,u,i);if(Ti({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!ei.isServer()&&Ore(d,r)&&(l?Oi(o,u,i):s?.promise)?.catch(Lr).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Ai(e,t){return ki(e,pi,t)}function kre(e){return e}var Are={[Symbol.iterator](){return jre}},jre={next(){return{done:!0,value:void 0}}},Mre=()=>Are,Nre=x,ji=globalThis.Number,Pre=e=>{if(e===`NaN`)return T(NaN);if(e===`Infinity`)return T(1/0);if(e===`-Infinity`)return T(-1/0);if(e.trim()===``)return Ee();let t=ji(e);return ji.isNaN(t)?Ee():T(t)},Fre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Mi=`~effect/http/HttpClientRequest`,Ire={[Mi]:Mi,...ke,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Yee(this.headers),body:this.body.toJSON()}},pipe(){return Ve(this,arguments)}};function Ni(e,t,n,r,i,a){let o=Object.create(Ire);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Lre=Ni(`GET`,``,tne,Ee(),Cn,$te),Pi=e=>(t,n)=>zre(Lre,{method:e,url:t,...n??void 0}),Rre=Pi(`POST`),zre=w(2,(e,t)=>{let n=e;return t.method&&(n=Bre(n,t.method)),t.url&&(n=Ure(n,t.url)),t.headers&&(n=Fi(n,t.headers)),t.urlParams&&(n=Wre(n,t.urlParams)),t.hash&&(n=Gre(n,t.hash)),t.body&&(n=Li(n,t.body)),t.accept&&(n=Ii(n,t.accept)),t.acceptJson&&(n=Hre(n)),n}),Bre=w(2,(e,t)=>Ni(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Vre=w(3,(e,t,n)=>Ni(e.method,e.url,e.urlParams,e.hash,Jn(e.headers,t,n),e.body)),Fi=w(2,(e,t)=>Ni(e.method,e.url,e.urlParams,e.hash,Rte(e.headers,t),e.body)),Ii=w(2,(e,t)=>Vre(e,`Accept`,t)),Hre=Ii(`application/json`),Ure=w(2,(e,t)=>{if(typeof t==`string`)return Ni(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Wte(n.searchParams),i=fte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Ni(e.method,n.toString(),r,i,e.headers,e.body)}),Wre=w(2,(e,t)=>Ni(e.method,e.url,ine(e.urlParams,t),e.hash,e.headers,e.body)),Gre=w(2,(e,t)=>Ni(e.method,e.url,e.urlParams,T(t),e.headers,e.body)),Li=w(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=fn(fn(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Jn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Jn(n,`content-length`,t.contentLength.toString()))),Ni(e.method,e.url,e.urlParams,e.hash,n,t)}),Kre=e=>xn({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${we(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),Ri=`~effect/http/HttpClient`,zi=vt(`effect/HttpClient`),Bi=w(2,(e,t)=>Vi(n=>t(e.postprocess(n)),e.preprocess)),qre=Bi(Ct(Bte)),Vi=(e,t)=>{let n=Object.create(Jre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Jre={[Ri]:Ri,pipe(){return Ve(this,arguments)},...ke,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Fre.map(([e,t])=>[t,function(t,n){return this.execute(Pi(e)(t,n))}]))},Yre=e=>Vi(t=>Ct(t,t=>Nt(n=>{let i=$re.get(t),a=i??new AbortController,o=Ote(t.url,t.urlParams,y(t.hash));if(Jee(o))return r(new Xn({reason:new yne({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Wee)||n.getRef(Hi)(t)){let r=e(t,s,a.signal,n);return i?r:Tt(e=>Le(e(r),{onSuccess(e){return Wi.register(e,a),rt(new Gi(e,a))},onFailure(e){return bt(e)&&a.abort(),zee(e)}}))}return lt(n.getRef(Zre)(t),{kind:`client`},r=>{r.attribute(`http.request.method`,t.method),r.attribute(`server.address`,s.origin),s.port!==``&&r.attribute(`server.port`,+s.port),r.attribute(`url.full`,s.toString()),r.attribute(`url.path`,s.pathname),r.attribute(`url.scheme`,s.protocol.slice(0,-1));let o=s.search.slice(1);o!==``&&r.attribute(`url.query`,o);let c=n.getRef(jte),l=sn(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Ui)?Fi(t,Kre(r)):t,Tt(o=>o(e(t,s,a.signal,n)).pipe(Lt(r,{captureStackTrace:!1}),Le({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=sn(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?rt(e):(Wi.register(e,a),rt(new Gi(e,a)))},onFailure(e){return!i&&bt(e)&&a.abort(),zee(e)}})))})})),rt),Xre=w(2,(e,t)=>{let n=dee(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,o=i&&b(i),s=n?void 0:t.times;return Bi(e,ie(r===`errors-only`?me:oe({schedule:o,times:s,while:qi}),r===`response-only`?me:_e({while:n||t.while===void 0?Ki:a(Ki,t.while),schedule:i,times:s})))}),Hi=$e(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Hee}),Ui=$e(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:ye}),Zre=$e(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Qre=e=>mt(zi)(se(t=>Ze(e,e=>Bi(e,yt(e=>ot(t,e)))))),Wi=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new Map;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),$re=new WeakMap,Gi=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[dn]=dn;[ir]=ir;applyInterrupt(e){return kt(()=>(Wi.unregister(this.original),_t(e,()=>ft(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return Eee(()=>(Wi.unregister(this.original),$ee(this.original.stream,ft(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[nt](){return this.original[nt]()}pipe(){return Ve(this,arguments)}},Ki=e=>Mee(e)||eie(e),eie=e=>Dn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&qi(e.reason.response)),qi=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Ji=`~effect/FiberSet`,tie=e=>Ye(e,Ji),nie={[Ji]:Ji,[Symbol.iterator](){return this.state._tag===`Closed`?Mre():this.state.backing[Symbol.iterator]()},...Ke,toJSON(){return{_id:`FiberMap`,state:this.state}}},rie=(e,t)=>{let n=Object.create(nie);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},iie=()=>je(ft(()=>rie(new Set,qe())),e=>kt(()=>{let t=e.state;if(t._tag===`Closed`)return st;e.state={_tag:`Closed`};let n=t.backing;return C(n).pipe(ce(e.deferred))})),Yi=-1,aie=ge(D(Iee,ae(Yi))),oie=w(e=>tie(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Yi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),St(r)&&(n?.propagateInterruption===!0?!aie(r.cause):!ut(r.cause))&&Ot(e.deferred,r))}))}),sie=function(){let e;return()=>(e===void 0&&(e=f(xt)),e)}(),cie=e=>()=>Ze(Dt(),t=>{let n=We(t);return(t,r)=>{if(e.state._tag===`Closed`)return sie();let i=n(t,r);return oie(e,i),i}}),Xi=e=>de(e.deferred),Zi=`~effect/socket/Socket`,Qi=vt(`effect/socket/Socket`),lie=`~effect/socket/Socket/CloseEvent`,uie=e=>Ye(e,lie),$i=`~effect/socket/Socket/SocketError`,die=e=>Ye(e,$i),ea=class extends Hn(`effect/socket/Socket/SocketReadError`)({_tag:un(`SocketReadError`),cause:jn}){message=`An error occurred during Read`},fie=class extends Hn(`effect/socket/Socket/SocketWriteError`)({_tag:un(`SocketWriteError`),cause:jn}){message=`An error occurred during Write`},ta=class extends Hn(`effect/socket/Socket/SocketOpenError`)({_tag:un(`SocketOpenError`),kind:Nn([`Unknown`,`Timeout`]),cause:jn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},na=class extends Hn(`effect/socket/Socket/SocketCloseError`)({_tag:un(`SocketCloseError`),code:Fn,closeReason:_n(j)}){static filterClean(e){return function(t){return ia.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?ite(t.reason):Lee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},ra=rr([ea,fie,ta,na]),ia=class extends Sne($i)(`SocketError`,{_tag:un(`SocketError`),reason:ra}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[$i]=$i;static is(e){return die(e)}message=this.reason.message},pie=e=>!0,mie=class extends vt()(`~effect/socket/Socket/WebSocket`){},aa=class extends vt()(`@effect/platform/Socket/WebSocketConstructor`){},hie=(e,t)=>aa.use(n=>gie(je((typeof e==`string`?rt(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>ft(()=>e.close(1e3))),t)),gie=(e,t)=>Nt(n=>{let i,a=pt(!1),o=n.context,s=t?.closeCodeIsError??pie,c=(n,c)=>Tee(Xe(function*(o){let l=yield*iie().pipe(te(o)),u=yield*te(e,o),d=yield*Oe(cie(l)(),mie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=Ct(ht(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return ct(t)?t:st});return d(t)}let t=n(e.data);ct(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),Ot(l.deferred,r(new ia({reason:f?new ea({cause:e}):new ta({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),Ot(l.deferred,r(new ia({reason:new na({code:t,closeReason:e.reason})})))}if(u.addEventListener(`close`,h,{once:!0}),u.addEventListener(`error`,m,{once:!0}),u.addEventListener(`message`,p),u.readyState!==1){let e=qe();u.addEventListener(`open`,()=>{f=!0,Ot(e,st)},{once:!0}),yield*de(e).pipe(jt({duration:t?.openTimeout??1e4,orElse:()=>r(new ia({reason:new ta({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),ee(Xi(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ue(Xi(l),na.filterClean(e=>!s(e)),()=>st)})).pipe(yt(e=>ot(o,e)),Je(ft(()=>{a.closeUnsafe(),i=void 0}))),l=new TextEncoder,u=(e,t)=>c(t=>typeof t==`string`?e(l.encode(t)):t instanceof Uint8Array?e(t):e(new Uint8Array(t)),t),d=rt(e=>a.whenOpen(ft(()=>{let t=i;uie(e)?t.close(e.code,e.reason):t.send(e)})));return rt(Qi.of({[Zi]:Zi,run:u,runRaw:c,writer:d}))}),oa=ie(hie,mt(Qi)),sa=class extends vt()(`effect/workers/Transferable/Collector`){},_ie=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return sa.of({addAllUnsafe:t,addAll:e=>ft(()=>t(e)),readUnsafe:n,read:ft(n),clearUnsafe:r,clear:ft(r)})},vie=`~effect/workers/WorkerError`,yie=class extends Hn(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:un(`WorkerSpawnError`),message:j,cause:_n(jn)}){},bie=class extends Hn(`effect/workers/WorkerError/WorkerSendError`)({_tag:un(`WorkerSendError`),message:j,cause:_n(jn)}){},xie=class extends Hn(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:un(`WorkerReceiveError`),message:j,cause:_n(jn)}){},Sie=class extends Hn(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:un(`WorkerUnknownError`),message:j,cause:_n(jn)}){},ca=rr([yie,bie,xie,Sie]);Hn(vie)({_tag:un(`WorkerError`),reason:ca});var la=`~effect/rpc/RpcClientError`,ua=class extends Hn(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:un(`RpcClientDefect`),message:j,cause:jn}){},da=class extends Hn(la)({_tag:un(`RpcClientError`),reason:rr([ca,ra,mne,ua])}){[la]=la;get message(){return`${this.reason._tag}: ${this.reason.message}`}},fa=e=>typeof e==`bigint`?e:BigInt(e),Cie={_tag:`Ping`},pa;try{pa=new TextDecoder}catch{}var I,ma,L=0,ha=[],ga=ha,_a=0,va={},ya,ba,xa=0,Sa=0,Ca,wa,Ta=[],Ea,Da={useRecords:!1,mapsAsObjects:!0},Oa=class{},ka=new Oa;ka.name=`MessagePack 0xC1`;var Aa=!1,ja=2,Ma,Na,Pa;try{Function(``)}catch{ja=1/0}var Fa=class e{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=0&&(e.structures=[],e.maxSharedStructures||=0)),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType=`number`)),Object.assign(this,e)}unpack(t,n){if(I)return io(()=>(ao(),this?this.unpack(t,n):e.prototype.unpack.call(Da,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(ma=n.end||t.length,L=n.start||0):(L=0,ma=n>-1?n:t.length),_a=0,Sa=0,ba=null,ga=ha,Ca=null,I=t;try{Ea=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){throw I=null,t instanceof Uint8Array?e:Error(`Source must be a Uint8Array or Buffer but was a `+(t&&typeof t==`object`?t.constructor.name:typeof t))}if(this instanceof e){if(va=this,this.structures)return ya=this.structures,Ia(n);(!ya||ya.length>0)&&(ya=[])}else va=Da,(!ya||ya.length>0)&&(ya=[]);return Ia(n)}unpackMultiple(e,t){let n,r=0;try{Aa=!0;let i=e.length,a=this?this.unpack(e,i):so.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(Ia(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(Ia());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Aa=!1,ao()}}_mergeStructures(e,t){Na&&(e=Na.call(this,e)),e||=[],Object.isFrozen(e)&&(e=e.map(e=>e.slice(0)));for(let t=0,n=e.length;t<n;t++){let n=e[t];n&&(n.isShared=!0,t>=32&&(n.highByte=t-32>>5))}e.sharedLength=e.length;for(let n in t||[])if(n>=0){let r=e[n],i=t[n];i&&(r&&((e.restoreStructures||(e.restoreStructures=[]))[n]=r),e[n]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function Ia(e){try{if(!va.trusted&&!Aa){let e=ya.sharedLength||0;e<ya.length&&(ya.length=e)}let t;if(va.randomAccessStructure&&I[L]<64&&I[L]>=32&&Ma?(t=Ma(I,L,ma,va),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=ma):t=Ra(),Ca&&=(L=Ca.postBundlePosition,null),Aa&&(ya.restoreStructures=null),L==ma)ya&&ya.restoreStructures&&La(),ya=null,I=null,wa&&=null;else if(L>ma)throw Error(`Unexpected end of MessagePack data`);else if(!Aa){let e;try{e=JSON.stringify(t,(e,t)=>typeof t==`bigint`?`${t}n`:t).slice(0,100)}catch(t){e=`(JSON view not available `+t+`)`}throw Error(`Data read, but end of buffer not reached `+e)}return t}catch(e){throw ya&&ya.restoreStructures&&La(),ao(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>ma)&&(e.incomplete=!0),e}}function La(){for(let e in ya.restoreStructures)ya[e]=ya.restoreStructures[e];ya.restoreStructures=null}function Ra(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=ya[e&63]||va.getStructures&&Va()[e&63];return t?(t.read||=za(t,e&63),t.read()):e}}else if(e<144){if(e-=128,va.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=$a();e===`__proto__`&&(e=`__proto_`),t[e]=Ra()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Ra(),Ra());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=Ra();return va.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Sa>=L)return ba.slice(L-xa,(L+=t)-xa);if(Sa==0&&ma<140){let e=t<16?Ja(t):qa(t);if(e!=null)return e}return Ha(t)}{let t;switch(e){case 192:return null;case 193:return Ca?(t=Ra(),t>0?Ca[1].slice(Ca.position1,Ca.position1+=t):Ca[0].slice(Ca.position0,Ca.position0-=t)):ka;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return Xa(t);case 197:return t=Ea.getUint16(L),L+=2,Xa(t);case 198:return t=Ea.getUint32(L),L+=4,Xa(t);case 199:return Za(I[L++]);case 200:return t=Ea.getUint16(L),L+=2,Za(t);case 201:return t=Ea.getUint32(L),L+=4,Za(t);case 202:if(t=Ea.getFloat32(L),va.useFloat32>2){let e=oo[(I[L]&127)<<1|I[L+1]>>7];return L+=4,(e*t+(t>0?.5:-.5)>>0)/e}return L+=4,t;case 203:return t=Ea.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=Ea.getUint16(L),L+=2,t;case 206:return t=Ea.getUint32(L),L+=4,t;case 207:return va.int64AsType===`number`?(t=Ea.getUint32(L)*4294967296,t+=Ea.getUint32(L+4)):va.int64AsType===`string`?t=Ea.getBigUint64(L).toString():va.int64AsType===`auto`?(t=Ea.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Ea.getBigUint64(L),L+=8,t;case 208:return Ea.getInt8(L++);case 209:return t=Ea.getInt16(L),L+=2,t;case 210:return t=Ea.getInt32(L),L+=4,t;case 211:return va.int64AsType===`number`?(t=Ea.getInt32(L)*4294967296,t+=Ea.getUint32(L+4)):va.int64AsType===`string`?t=Ea.getBigInt64(L).toString():va.int64AsType===`auto`?(t=Ea.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Ea.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return to(I[L++]&63);{let e=Ta[t];if(e)return e.read?(L++,e.read(Ra())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,to(I[L++]&63,I[L++])):Za(2);case 214:return Za(4);case 215:return Za(8);case 216:return Za(16);case 217:return t=I[L++],Sa>=L?ba.slice(L-xa,(L+=t)-xa):Tie(t);case 218:return t=Ea.getUint16(L),L+=2,Sa>=L?ba.slice(L-xa,(L+=t)-xa):Eie(t);case 219:return t=Ea.getUint32(L),L+=4,Sa>=L?ba.slice(L-xa,(L+=t)-xa):Die(t);case 220:return t=Ea.getUint16(L),L+=2,Wa(t);case 221:return t=Ea.getUint32(L),L+=4,Wa(t);case 222:return t=Ea.getUint16(L),L+=2,Ga(t);case 223:return t=Ea.getUint32(L),L+=4,Ga(t);default:if(e>=224)return e-256;if(e===void 0){let e=Error(`Unexpected end of MessagePack data`);throw e.incomplete=!0,e}throw Error(`Unknown MessagePack token `+e)}}}var wie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function za(e,t){function n(){if(n.count++>ja){let n=e.read=Function(`r`,`return function(){return `+(va.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:wie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(Ra);return e.highByte===0&&(e.read=Ba(t,e.read)),n()}let r={};for(let t=0,n=e.length;t<n;t++){let n=e[t];n===`__proto__`&&(n=`__proto_`),r[n]=Ra()}return va.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Ba(t,n):n}var Ba=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=ya[r]||Va()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=za(i,e),i.read()};function Va(){let e=io(()=>(I=null,va.getStructures()));return ya=va._mergeStructures(e,ya)}var Ha=Ua,Tie=Ua,Eie=Ua,Die=Ua;function Ua(e){let t;if(e<16&&(t=Ja(e)))return t;if(e>64&&pa)return pa.decode(I.subarray(L,L+=e));let n=L+e,r=[];for(t=``;L<n;){let e=I[L++];if(!(e&128))r.push(e);else if((e&224)==192){let t=I[L++]&63,n=(e&31)<<6|t;n<128?r.push(65533):r.push(n)}else if((e&240)==224){let t=I[L++]&63,n=I[L++]&63,i=(e&31)<<12|t<<6|n;i<2048||i>=55296&&i<=57343?r.push(65533):r.push(i)}else if((e&248)==240){let t=I[L++]&63,n=I[L++]&63,i=I[L++]&63,a=(e&7)<<18|t<<12|n<<6|i;a<65536||a>1114111?r.push(65533):a>65535?(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023,r.push(a)):r.push(a)}else r.push(65533);r.length>=4096&&(t+=Ka.apply(String,r),r.length=0)}return r.length>0&&(t+=Ka.apply(String,r)),t}function Wa(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Ra();return va.freezeData?Object.freeze(t):t}function Ga(e){if(va.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=$a();e===`__proto__`&&(e=`__proto_`),t[e]=Ra()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Ra(),Ra());return t}}var Ka=String.fromCharCode;function qa(e){let t=L,n=Array(e);for(let r=0;r<e;r++){let e=I[L++];if((e&128)>0){L=t;return}n[r]=e}return Ka.apply(String,n)}function Ja(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return Ka(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return Ka(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return Ka(t,n,r)}{let t=I[L++],n=I[L++],r=I[L++],i=I[L++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){L-=4;return}if(e<6){if(e===4)return Ka(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return Ka(t,n,r,i,e)}}if(e<8){let a=I[L++],o=I[L++];if((a&128)>0||(o&128)>0){L-=6;return}if(e<7)return Ka(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return Ka(t,n,r,i,a,o,s)}{let a=I[L++],o=I[L++],s=I[L++],c=I[L++];if((a&128)>0||(o&128)>0||(s&128)>0||(c&128)>0){L-=8;return}if(e<10){if(e===8)return Ka(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return Ka(t,n,r,i,a,o,s,c,e)}}if(e<12){let l=I[L++],u=I[L++];if((l&128)>0||(u&128)>0){L-=10;return}if(e<11)return Ka(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return Ka(t,n,r,i,a,o,s,c,l,u,d)}{let l=I[L++],u=I[L++],d=I[L++],f=I[L++];if((l&128)>0||(u&128)>0||(d&128)>0||(f&128)>0){L-=12;return}if(e<14){if(e===12)return Ka(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return Ka(t,n,r,i,a,o,s,c,l,u,d,f,e)}}{let p=I[L++],m=I[L++];if((p&128)>0||(m&128)>0){L-=14;return}if(e<15)return Ka(t,n,r,i,a,o,s,c,l,u,d,f,p,m);let h=I[L++];if((h&128)>0){L-=15;return}return Ka(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Ya(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=Ea.getUint16(L),L+=2;break;case 219:t=Ea.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Ua(t)}function Xa(e){return va.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function Za(e){let t=I[L++];if(Ta[t]){let n;return Ta[t](I.subarray(L,n=L+=e),e=>{L=e;try{return Ra()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var Qa=Array(4096);function $a(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Sa>=L)return ba.slice(L-xa,(L+=e)-xa);if(!(Sa==0&&ma<180))return Ha(e)}else return L--,eo(Ra());let t=(e<<5^(e>1?Ea.getUint16(L):e>0?I[L]:0))&4095,n=Qa[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=Ea.getUint32(r),a!=n[o++]){r=1879048192;break}r+=4}for(i+=3;r<i;)if(a=I[r++],a!=n[o++]){r=1879048192;break}if(r===i)return L=r,n.string;i-=3,r=L}for(n=[],Qa[t]=n,n.bytes=e;r<i;)a=Ea.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Ja(e):qa(e);return s==null?n.string=Ha(e):n.string=s}function eo(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(e==null)return e+``;if(va.allowArraysInMapKeys&&Array.isArray(e)&&e.flat().every(e=>[`string`,`number`,`boolean`,`bigint`].includes(typeof e)))return e.flat().toString();throw Error(`Invalid property type for record: ${typeof e}`)}var to=(e,t)=>{let n=Ra().map(eo),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=ya[e];return i&&(i.isShared||Aa)&&((ya.restoreStructures||(ya.restoreStructures=[]))[e]=i),ya[e]=n,n.read=za(n,r),n.read()};Ta[0]=()=>{},Ta[0].noBuffer=!0,Ta[66]=e=>{let t=e.byteLength%8||8,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r<t;r++)n<<=BigInt(8),n+=BigInt(e[r]);if(e.byteLength!==t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=(e,t)=>{let n=t-e;if(n<=40){let n=r.getBigUint64(e);for(let i=e+8;i<t;i+=8)n<<=64n,n|=r.getBigUint64(i);return n}let a=e+(n>>4<<3),o=i(e,a),s=i(a,t);return o<<BigInt((t-a)*8)|s};n=n<<BigInt((r.byteLength-t)*8)|i(t,r.byteLength)}return n};var no={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Ta[101]=()=>{let e=Ra();if(!no[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return no[e[0]](e[1],{cause:e[2]})},Ta[105]=e=>{if(va.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Ea.getUint32(L-4);wa||=new Map;let n=I[L],r;r=n>=144&&n<160||n==220||n==221?[]:n>=128&&n<144||n==222||n==223?new Map:(n>=199&&n<=201||n>=212&&n<=216)&&I[L+1]===115?new Set:{};let i={target:r};wa.set(t,i);let a=Ra();if(i.used)Object.assign(r,a);else return i.target=a;if(r instanceof Map)for(let[e,t]of a.entries())r.set(e,t);if(r instanceof Set)for(let e of Array.from(a))r.add(e);return r},Ta[112]=e=>{if(va.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Ea.getUint32(L-4),n=wa.get(t);return n.used=!0,n.target},Ta[115]=()=>new Set(Ra());var ro=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Oie=typeof globalThis==`object`?globalThis:window;Ta[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=ro[t];if(!r){if(t===16)return n;if(t===17)return new DataView(n);throw Error(`Could not find typed array for code `+t)}return new Oie[r](n)},Ta[120]=()=>{let e=Ra();return new RegExp(e[0],e[1])};var kie=[];Ta[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,Ca=kie,Ca=[Ya(),Ya()],Ca.position0=0,Ca.position1=0,Ca.postBundlePosition=L,L=n,Ra()},Ta[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date(`invalid`);function io(e){Pa&&Pa();let t=ma,n=L,r=_a,i=xa,a=Sa,o=ba,s=ga,c=wa,l=Ca,u=new Uint8Array(I.slice(0,ma)),d=ya,f=ya.slice(0,ya.length),p=va,m=Aa,h=e();return ma=t,L=n,_a=r,xa=i,Sa=a,ba=o,ga=s,wa=c,Ca=l,I=u,Aa=m,ya=d,ya.splice(0,ya.length,...f),va=p,Ea=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function ao(){I=null,wa=null,ya=null}var oo=Array(147);for(let e=0;e<256;e++)oo[e]=+(`1e`+Math.floor(45.15-e*.30103));var so=new Fa({useRecords:!1});so.unpack,so.unpackMultiple,so.unpack;var Aie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var co;try{co=new TextEncoder}catch{}var lo,uo,fo=typeof Buffer<`u`,po=fo?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,mo=fo?Buffer:Uint8Array,ho=fo?4294967296:2144337920,R,go,_o,z=0,vo,yo=null,jie,Mie=21760,Nie=/[\u0080-\uFFFF]/,bo=Symbol(`record-id`),Pie=class extends Fa{constructor(e){super(e),this.offset=0;let t,n,r,i,a=mo.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:co&&co.encodeInto?function(e,t){return co.encodeInto(e,R.subarray(t)).written}:!1,o=this;e||={};let s=e&&e.sequential,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(l??=c?32:0,l>8160)throw Error(`Maximum maxSharedStructure is 8160`);e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let u=e.maxOwnStructures;u??=c?32:64,!this.structures&&e.useRecords!=0&&(this.structures=[]);let d=l>32||u+l>64,f=l+64,p=l+u+64;if(p>8256)throw Error(`Maximum maxSharedStructure + maxOwnStructure is 8192`);let m=[],h=0,g=0;this.pack=this.encode=function(e,a){if(R||(R=new po(8192),_o=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),vo=R.length-10,vo-z<2048?(R=new po(R.length),_o=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),vo=R.length-10,z=0):z=z+7&2147483640,t=z,a&2048&&(z+=a&255),i=o.structuredClone?new Map:null,o.bundleStrings&&typeof e!=`string`?(yo=[],yo.size=1/0):yo=null,r=o.structures,r){r.uninitialized&&(r=o._mergeStructures(o.getStructures()));let e=r.sharedLength||0;if(e>l)throw Error(`Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to `+r.sharedLength);if(!r.transitions){r.transitions=Object.create(null);for(let t=0;t<e;t++){let e=r[t];if(!e)continue;let n,i=r.transitions;for(let t=0,r=e.length;t<r;t++){let r=e[t];n=i[r],n||=i[r]=Object.create(null),i=n}i[bo]=t+64}this.lastNamedStructuresLength=e}s||(r.nextId=e+64)}n&&=!1;let c;try{o.randomAccessStructure&&e&&typeof e==`object`?e.constructor===Object?D(e):e.constructor!==Map&&!Array.isArray(e)&&!uo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=yo;if(yo&&wo(t,y,0),i&&i.idsToInsert){let e=i.idsToInsert.sort((e,t)=>e.offset>t.offset?1:-1),r=e.length,a=-1;for(;n&&r>0;){let i=e[--r].offset+t;i<n.stringsPosition+t&&a===-1&&(a=0),i>n.position+t?a>=0&&(a+=6):(a>=0&&(_o.setUint32(n.position+t,_o.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&_o.setUint32(n.position+t,_o.getUint32(n.position+t)+a),z+=e.length*6,z>vo&&w(z),o.offset=z;let s=Fie(R.subarray(t,z),e);return i=null,s}return o.offset=z,a&512?(R.start=t,R.end=z,R):R.subarray(t,z)}catch(e){throw c=e,e}finally{if(r&&(_(),n&&o.saveStructures)){let n=r.sharedLength||0,i=R.subarray(t,z),s=Iie(r,o);if(!c)return o.saveStructures(s,s.isCompatible)===!1?o.pack(e,a):(o.lastNamedStructuresLength=n,R.length>1073741824&&(R=null),i)}R.length>1073741824&&(R=null),a&1024&&(z=t)}};let _=()=>{g<10&&g++;let e=r.sharedLength||0;if(r.length>e&&!s&&(r.length=e),h>1e4)r.transitions=null,g=0,h=0,m.length>0&&(m=[]);else if(m.length>0&&!s){for(let e=0,t=m.length;e<t;e++)m[e][bo]=0;m=[]}},v=e=>{var t=e.length;t<16?R[z++]=144|t:t<65536?(R[z++]=220,R[z++]=t>>8,R[z++]=t&255):(R[z++]=221,_o.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>vo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(yo&&n>=4&&n<4096){if((yo.size+=n)>Mie){let e,n=(yo[0]?yo[0].length*3+yo[1].length:0)+10;z+n>vo&&(R=w(z+n));let r;yo.position?(r=yo,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,wo(t,y,0),_o.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),yo=[``,``],yo.previous=r,yo.size=0,yo.position=e}let r=Nie.test(e);yo[+!r]+=e,R[z++]=193,y(r?-n:n);return}let i;i=n<32?1:n<256?2:n<65536?3:5;let o=n*3;if(z+o>vo&&(R=w(z+o)),n<64||!a){let t,a,o,s=z+i;for(t=0;t<n;t++)a=e.charCodeAt(t),a<128?R[s++]=a:a<2048?(R[s++]=a>>6|192,R[s++]=a&63|128):(a&64512)==55296&&((o=e.charCodeAt(t+1))&64512)==56320?(a=65536+((a&1023)<<10)+(o&1023),t++,R[s++]=a>>18|240,R[s++]=a>>12&63|128,R[s++]=a>>6&63|128,R[s++]=a&63|128):(R[s++]=a>>12|224,R[s++]=a>>6&63|128,R[s++]=a&63|128);r=s-z-i}else r=a(e,z+i);r<32?R[z++]=160|r:r<256?(i<2&&R.copyWithin(z+2,z+1,z+1+r),R[z++]=217,R[z++]=r):r<65536?(i<3&&R.copyWithin(z+3,z+2,z+2+r),R[z++]=218,R[z++]=r>>8,R[z++]=r&255):(i<5&&R.copyWithin(z+5,z+3,z+3+r),R[z++]=219,_o.setUint32(z,r),z+=4),z+=r}else if(n===`number`)if(e>>>0===e)e<32||e<128&&this.useRecords===!1||e<64&&!this.randomAccessStructure?R[z++]=e:e<256?(R[z++]=204,R[z++]=e):e<65536?(R[z++]=205,R[z++]=e>>8,R[z++]=e&255):(R[z++]=206,_o.setUint32(z,e),z+=4);else if(e>>0===e)e>=-32?R[z++]=256+e:e>=-128?(R[z++]=208,R[z++]=e+256):e>=-32768?(R[z++]=209,_o.setInt16(z,e),z+=2):(R[z++]=210,_o.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,_o.setFloat32(z,e);let n;if(t<4||(n=e*oo[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,_o.setFloat64(z,e),z+=8}else if(n===`object`||n===`function`)if(!e)R[z++]=192;else{if(i){let n=i.get(e);if(n){n.id||=(i.idsToInsert||(i.idsToInsert=[])).push(n),R[z++]=214,R[z++]=112,_o.setUint32(z,n.id),z+=4;return}i.set(e,{offset:z-t})}let a=e.constructor;if(a===Object)C(e);else if(a===Array)v(e);else if(a===Map)if(this.mapAsEmptyObject)R[z++]=128;else{r=e.size,r<16?R[z++]=128|r:r<65536?(R[z++]=222,R[z++]=r>>8,R[z++]=r&255):(R[z++]=223,_o.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=lo.length;t<n;t++){let n=uo[t];if(e instanceof n){let n=lo[t];if(n.write){n.type&&(R[z++]=212,R[z++]=n.type,R[z++]=0);let t=n.write.call(this,e);t===e?Array.isArray(e)?v(e):C(e):y(t);return}let r=R,i=_o,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>vo&&w(z),{target:R,targetView:_o,position:z-e}),y)}finally{r&&(R=r,_o=i,z=a,vo=R.length-10)}o&&(o.length+z>vo&&w(o.length+z),z=Co(o,R,z,n.type));return}}if(Array.isArray(e))v(e);else{if(e.toJSON){let t=e.toJSON();if(t!==e)return y(t)}if(n===`function`)return y(this.writeFunction&&this.writeFunction(e));C(e)}}}else if(n===`boolean`)R[z++]=e?195:194;else if(n===`bigint`){if(e<0x8000000000000000&&e>=-0x8000000000000000)R[z++]=211,_o.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,_o.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,_o.setFloat64(z,Number(e));else if(this.largeBigIntToString)return y(e.toString());else if(this.useBigIntExtension||this.moreTypes){let t=BigInt(e<0?-1:0),n;if(e>>BigInt(65536)===t){let r=BigInt(0x10000000000000000)-BigInt(1),i=[];for(;i.push(e&r),e>>BigInt(63)!==t;)e>>=BigInt(64);n=new Uint8Array(new BigUint64Array(i).buffer),n.reverse()}else{let t=e<0,r=(t?~e:e).toString(16);if(r.length%2?r=`0`+r:parseInt(r.charAt(0),16)>=8&&(r=`00`+r),fo)n=Buffer.from(r,`hex`);else{n=new Uint8Array(r.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(r.slice(e*2,e*2+2),16)}if(t)for(let e=0;e<n.length;e++)n[e]=~n[e]}n.length+z>vo&&w(n.length+z),z=Co(n,R,z,66);return}else throw RangeError(e+` was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string`);z+=8}else if(n===`undefined`)this.encodeUndefinedAsNil?R[z++]=192:(R[z++]=212,R[z++]=0,R[z++]=0);else throw Error(`Unknown type: `+n)},b=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?e=>{let t;if(this.skipValues){t=[];for(let n in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(n))&&!this.skipValues.includes(e[n])&&t.push(n)}else t=Object.keys(e);let n=t.length;n<16?R[z++]=128|n:n<65536?(R[z++]=222,R[z++]=n>>8,R[z++]=n&255):(R[z++]=223,_o.setUint32(z,n),z+=4);let r;if(this.coercibleKeyAsNumber)for(let i=0;i<n;i++){r=t[i];let n=Number(r);y(isNaN(n)?r:n),y(e[r])}else for(let i=0;i<n;i++)y(r=t[i]),y(e[r])}:e=>{R[z++]=222;let n=z-t;z+=2;let r=0;for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(y(t),y(e[t]),r++);if(r>65535)throw Error(`Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object`);R[n+++t]=r>>8,R[n+t]=r&255},x=this.useRecords===!1?b:e.progressiveRecords&&!d?e=>{let n,i=r.transitions||(r.transitions=Object.create(null)),a=z++-t,o;for(let s in e)if(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(s)){if(n=i[s],n)i=n;else{let c=Object.keys(e),l=i;i=r.transitions;let u=0;for(let e=0,t=c.length;e<t;e++){let t=c[e];n=i[t],n||(n=i[t]=Object.create(null),u++),i=n}a+t+1==z?(z--,T(i,c,u)):E(i,c,a,u),o=!0,i=l[s]}y(e[s])}if(!o){let n=i[bo];n?R[a+t]=n:E(i,Object.keys(e),a,0)}}:e=>{let t,n=r.transitions||(r.transitions=Object.create(null)),i=0;for(let r in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(r))&&(t=n[r],t||(t=n[r]=Object.create(null),i++),n=t);let a=n[bo];a?a>=96&&d?(R[z++]=((a-=96)&31)+96,R[z++]=a>>5):R[z++]=a:T(n,n.__keys__||Object.keys(e),i);for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&y(e[t])},S=typeof this.useRecords==`function`&&this.useRecords,C=S?e=>{S(e)?x(e):b(e)}:x,w=e=>{let n;if(e>16777216){if(e-t>ho)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(ho,Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096)*4096)}else n=(Math.max(e-t<<2,R.length-1)>>12)+1<<12;let r=new po(n);return _o=r.dataView||=new DataView(r.buffer,0,n),e=Math.min(e,R.length),R.copy?R.copy(r,0,t,e):r.set(R.slice(t,e)),z-=t,t=0,vo=r.length-10,R=r},T=(e,t,i)=>{let a=r.nextId;a||=64,a<f&&this.shouldShareStructure&&!this.shouldShareStructure(t)?(a=r.nextOwnId,a<p||(a=f),r.nextOwnId=a+1):(a>=p&&(a=f),r.nextId=a+1);let o=t.highByte=a>=96&&d?a-96>>5:-1;e[bo]=a,e.__keys__=t,r[a-64]=t,a<f?(t.isShared=!0,r.sharedLength=a-63,n=!0,o>=0?(R[z++]=(a&31)+96,R[z++]=o):R[z++]=a):(o>=0?(R[z++]=213,R[z++]=114,R[z++]=(a&31)+96,R[z++]=o):(R[z++]=212,R[z++]=114,R[z++]=a),i&&(h+=g*i),m.length>=u&&(m.shift()[bo]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=vo,c=t;R=go,z=0,t=0,R||(go=R=new po(8192)),vo=R.length-10,T(e,n,i),go=R;let l=z;if(R=a,z=o,vo=s,t=c,l>1){let e=z+l-1;e>vo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(go.slice(0,l),n),z=e}else R[r+t]=go[0]},D=e=>{let i=jie(e,R,t,z,r,w,(e,t,r)=>{if(r)return n=!0;z=t;let i=R;return y(e),_(),i===R?z:{position:z,targetView:_o,target:R}},this);if(i===0)return C(e);z=i}}useBuffer(e){R=e,R.dataView||(R.dataView=new DataView(R.buffer,R.byteOffset,R.byteLength)),_o=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};uo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Oa],lo=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:e,targetView:n,position:i}=t(6);e[i++]=214,e[i++]=255,n.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:n,targetView:i,position:a}=t(10);n[a++]=215,n[a++]=255,i.setUint32(a,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(a+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:e,targetView:r,position:i}=t(3);e[i++]=212,e[i++]=255,e[i++]=255}else{let{target:n,targetView:i,position:a}=t(15);n[a++]=199,n[a++]=12,n[a++]=255,i.setUint32(a,e.getMilliseconds()*1e6),i.setBigInt64(a+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:a}=t(this.moreTypes?3:0);this.moreTypes&&(i[a++]=212,i[a++]=115,i[a++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?xo(e,16,t):So(fo?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==mo&&this.moreTypes?xo(e,ro.indexOf(n.name),t):So(e,t)}},{pack(e,t){this.moreTypes?xo(e,17,t):So(fo?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function xo(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:a,position:o}=n(4+i);a[o++]=199,a[o++]=i+1}else if(i+1<65536){var{target:a,position:o}=n(5+i);a[o++]=200,a[o++]=i+1>>8,a[o++]=i+1&255}else{var{target:a,position:o,targetView:s}=n(7+i);a[o++]=201,s.setUint32(o,i+1),o+=4}a[o++]=116,a[o++]=t,e.buffer||(e=new Uint8Array(e)),a.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function So(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:a}=t(n+5);r[i++]=198,a.setUint32(i,n),i+=4}r.set(e,i)}function Co(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function Fie(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let t=n.offset,a=n.id;e.copyWithin(t+r,t,i),r-=6;let o=t+r;e[o++]=214,e[o++]=105,e[o++]=a>>24,e[o++]=a>>16&255,e[o++]=a>>8&255,e[o++]=a&255,i=t}return e}function wo(e,t,n){if(yo.length>0){_o.setUint32(yo.position+e,z+n-yo.position-e),yo.stringsPosition=z-e;let r=yo;yo=null,t(r[0]),t(r[1])}}function Iie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var To=new Pie({useRecords:!1});To.pack,To.pack;var{NEVER:Lie,ALWAYS:Rie,DECIMAL_ROUND:zie,DECIMAL_FIT:Bie}=Aie,Eo=class extends vt()(`effect/rpc/RpcSerialization`){},Vie=Eo.of({contentType:`application/json`,includesFraming:!1,makeUnsafe:()=>{let e=new TextDecoder;return{decode:t=>{let n=JSON.parse(typeof t==`string`?t:e.decode(t));return Array.isArray(n)?n:[n]},encode:e=>JSON.stringify(e)}}}),Do=he(Eo)(Vie),Hie=e=>kt(()=>{let t=new Set,n=new Map,r=new Map,i=(e,t)=>se(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),st});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return at(function*(){t.add(e),r.set(e,i);let a=n.get(e);if(a){n.delete(e);for(let[e,t]of a)yield*Te(kt(()=>i(e)),t)}return yield*iee(S,()=>(t.delete(e),r.delete(e),st))})}}))}),Uie=BigInt(0),Wie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Uie++),o=yield*Dt(),s=it(o,Me),c=new Map,l=!1;yield*gte(s,Nt(e=>(l=!0,d(Ree(e.id)))));let d=Xe(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?Pt(n.queue):Pe(n.queue,e.cause):n.resume(e)}),f=e=>{let r=Pte(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?ln(s.headers):Cn,l=s?.context??Pee();if(!r){let r=t=>m(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):lt(`${n}.${e._tag}`,{attributes:t.spanAttributes},r)}let u=h(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:dte(Ze(u,rte))}},m=(e,n,r,i,o,s,u)=>Nt(d=>{if(l)return xt;let f=a(),p=n(e=>t.onFromClient({message:e,context:s,discard:u}),{_tag:`Request`,id:f,tag:e._tag,payload:i,...r?{traceId:r.traceId,spanId:r.spanId,sampled:r.sampled}:{},headers:wn(d.getRef(Jie),o)});if(u)return p;let m;return _t(Re(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?Lt(r,{captureStackTrace:!1}):me,We(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),Rt(aee(m),_(f,Array.from(e),s))))}),h=Xe(function*(e,r,o,s,d,f){if(l)return yield*xt;let m=i?void 0:yield*hte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),h=Ce(),g=a(),v=Zee(h.context,Me);yield*u(v,e=>c.has(g)?(c.delete(g),_(g,St(e)?Array.from(Oee(e.cause)):[],f)):st);let y=yield*p(d);return c.set(g,{_tag:`Queue`,rpc:e,queue:y,scope:v,context:f}),yield*r(e=>t.onFromClient({message:e,context:f,discard:!1}),{_tag:`Request`,id:g,tag:e._tag,payload:o,...m?{traceId:m.traceId,spanId:m.spanId,sampled:m.sampled}:{},headers:wn(h.getRef(Jie),s)}).pipe(m?Lt(m,{captureStackTrace:!1}):me,Ge(e=>Pe(y,e)),dt,Mt(v,{startImmediately:!0})),y}),g=e=>{let t=[];for(let n of e.middlewares.values()){let e=o.mapUnsafe.get(`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},_=(e,n,r)=>Re(i=>{let a=Ce();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Nee(1e3),We(a.context)).addObserver(()=>{i(st)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?st:tee(i.queue,e.values).pipe(r?Ct(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):me,Ge(e=>Pe(i.queue,e)))}case`Exit`:{let t=e.requestId,n=c.get(t);return n?(c.delete(t),n._tag===`Effect`?(n.resume(e.exit),st):e.exit._tag===`Success`?Pt(n.queue):Pe(n.queue,e.exit.cause)):st}case`Defect`:return d(bee(e.defect));case`ClientEnd`:return st}},y;if(t.flatten){let t=new Map;y=function(n,r,i){let a=t.get(n);return a||(a=f(e.requests.get(n)),t.set(n,a)),a(r,i)}}else y={},e.requests.forEach(e=>{y[e._tag]=f(e)});return{client:y,write:v}}),Gie=0,Oo=Xe(function*(e,t){let n=Gie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*ko,s=new Map,{client:l,write:u}=yield*Wie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?_ie():void 0,l=Ce(),u={rpc:r,context:a?ote(l.context,sa,a):l.context,schemas:qie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Te(u.context),c,Ct(e=>i(n,{...t,id:String(t.id),payload:e,headers:Object.entries(t.headers)},a&&a.readUnsafe())))}case`Ack`:return s.get(t.requestId)?i(n,{_tag:`Ack`,requestId:String(t.requestId)}):st;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):st;case`Eof`:return st}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=fa(e.requestId),n=s.get(t);return!n||g(n.schemas.decodeChunk)?st:n.schemas.decodeChunk.value(e.values).pipe(Te(n.context),c,Ct(t=>u({_tag:`Chunk`,clientId:0,requestId:fa(e.requestId),values:t})),v(t=>u({_tag:`Exit`,clientId:0,requestId:fa(e.requestId),exit:Ae(t)})))}case`Exit`:{let t=fa(e.requestId),n=s.get(t);return n?(s.delete(t),n.schemas.decodeExit(e.exit).pipe(Te(n.context),c,Le({onSuccess:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:Ae(e)})}))):st}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Qie(e.defect)});case`ClientProtocolError`:{let t=wee(e.error);return At(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return st}}).pipe(Ge(cte),dt,tt),l}),Kie=new WeakMap,qie=e=>{let t=Kie.get(e);if(t!==void 0)return t;let n=Ute(e.successSchema);return t={decodeChunk:be(n,e=>rn(pn(gne(e.success)))),encodePayload:fne(pn(e.payloadSchema)),decodeExit:rn(pn(Hte(e)))},Kie.set(e,t),t},Jie=$e(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Cn}),ko=class extends vt()(`effect/rpc/RpcClient/Protocol`){static make=Hie},Ao=e=>ko.make(Xe(function*(t,n){let i=yield*Qi,a=yield*Eo,o=yield*see(Zie),s=new Map,u=yield*i.writer,d=a.makeUnsafe(),f=yield*Xie(u(d.encode(Cie))),p,m=kt(()=>(p=void 0,gt(o)?o.value.onConnect:st)),h=e=>At(n,n=>t(n,e));return yield*kt(()=>(d=a.makeUnsafe(),f.reset(),i.runRaw(e=>{try{let n=d.decode(e);if(n.length===0)return;let r=0;return Dee({while:()=>r<n.length,body:()=>{let e=n[r++];if(e._tag===`Pong`)return f.onPong(),st;if(`requestId`in e){let n=s.get(e.requestId);if(n!==void 0)return e._tag===`Exit`&&s.delete(e.requestId),t(n,e)}return h(e)},step:oee})}catch(e){return h({_tag:`ClientProtocolError`,error:new da({reason:new ua({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(ee(Ct(f.timeout,()=>r(new ia({reason:new ta({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(Ct(()=>r(new ia({reason:new na({code:1e3})}))),gt(o)?Je(o.value.onDisconnect):me,Xee(t=>{let n=Bee(t),r=ete(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?st:(p=new da({reason:r?n.success.reason:new ua({message:`Unknown socket error`,cause:Ie(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),_e(e?.retryPolicy??Yie),l({module:`RpcClient`,method:`makeProtocolSocket`}),tt),{send(e,t){if(p)return r(p);t._tag===`Request`&&s.set(t.id,e);let n=d.encode(t);return n===void 0?st:c(u(n))},supportsAck:!0,supportsTransferables:!1}})),Yie=h(500,1.5).pipe(uee(ree(5e3))),Xie=Xe(function*(e){let t=!0,n=0,r=pt();return yield*kt(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(xee(`5 seconds`),Et,et,dt,tt),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Zie=class extends vt()(`effect/rpc/RpcClient/ConnectionHooks`){},Qie=nr(jn);function jo(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function $ie(e){return e?.target.wsBaseUrl??null}function eae(e){return e?.target.httpBaseUrl??null}function tae(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function nae(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function rae(e){let t=nae(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function iae(e){let t=e.topology===`cmmd-cloud-runtime`;return{cmmd:!0,ownerBootstrapPromotion:e.topology!==`cloud-shell`&&!t,bearerBootstrap:!0,desktopBootstrap:e.topology===`desktop-local`,providerCredentialBroker:e.topology===`cmmd-control-plane`}}function aae(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function oae(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Mo(e){let t=e.capabilities,n=t.runtime??rae(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??iae(n),tools:t.tools??aae(n),projects:t.projects??oae(t,n)}}function sae(e){return e?Mo(e).projects.cloudProjects:!1}function cae(e){return e?Mo(e).runtime.workspaceProxy??!1:!1}function No(e,t){return{environmentId:e,projectId:t}}function Po(e,t){return{environmentId:e,threadId:t}}var Fo=`scoped:v1:`;function Io(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Fo)?`${Fo}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Lo(e){return Io(e)}function Ro(e){return Io(e)}function lae(e){let t=e.slice(10),n=t.indexOf(`:`);if(n<=0||n>=t.length-1||t.indexOf(`:`,n+1)!==-1)return null;try{let e=decodeURIComponent(t.slice(0,n)),r=decodeURIComponent(t.slice(n+1));return e.length>0&&r.length>0?{environmentId:e,localId:r}:null}catch{return null}}function zo(e){if(e.startsWith(Fo))return lae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Bo(e){let t=zo(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Vo(e){let t=zo(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var uae=1e3,dae=64e3;Oo(An);function fae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(uae*2**e),dae)}var Ho=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Uo(e){return Array.isArray(e)?e.map(Uo):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Uo(t)])):e}function pae(e){let t=JSON.stringify(Uo(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var mae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function hae(e){return e._tag===`Ping`?mae:null}function gae(e){if(e.policy===null||e.policy.method!==e.method)throw new Ho(`method_not_remotable`,`Relay method has no exact dispatch policy: ${e.method}`,!1);if(e.policy.requiredScope!==null&&!e.grantedScopes.includes(e.policy.requiredScope))throw new Ho(`scope_denied`,`Relay method ${e.method} requires scope ${e.policy.requiredScope}`,!1);return{requiredScope:e.policy.requiredScope,deliveryClass:e.policy.deliveryClass,journalPersistence:e.policy.journalPersistence}}function _ae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new Ho(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new Ho(`method_not_remotable`,`Relay dispatch policy targets an unregistered method: ${r.method}`,!1);if((r.deliveryClass===`idempotent-command`||r.deliveryClass===`create-command`)==(r.journalPersistence===`none`))throw new Ho(`method_not_remotable`,`Relay dispatch policy has incompatible journal persistence: ${r.method}`,!1);n.set(r.method,r)}for(let t of e.registeredMethods)if(!n.has(t))throw new Ho(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var vae=[{method:M.projectsSearchContents,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.projectsSearchEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.projectsListEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.serverDiscoverSourceControl,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.serverReportClientActivity,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.projectsWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.projectCheckoutDeletionPreview,requiredScope:`workspace.write`,deliveryClass:`read`},{method:M.projectCheckoutDeletionExecute,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.reviewGetDiffPreview,requiredScope:`diff.read`,deliveryClass:`read`},{method:M.projectsReadFile,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.cloudListRuntimes,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.filesystemBrowse,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.workspaceReadFile,requiredScope:`workspace.read`,deliveryClass:`bulk-transfer`},{method:M.workspaceBeginWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.workspaceWriteFileChunk,requiredScope:`workspace.write`,deliveryClass:`bulk-transfer`},{method:M.workspaceCommitWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.workspaceCancelWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.shellOpenInEditor,requiredScope:`shell.open`,deliveryClass:`idempotent-command`},{method:M.gitPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:M.gitRunStackedAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitListBranches,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsListRefs,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.vcsRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsCreateRef,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.vcsSwitchRef,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.gitRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitCreateBranch,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.gitCheckout,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitResolvePullRequest,requiredScope:`git.read`,deliveryClass:`read`},{method:M.gitPreparePullRequestThread,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.terminalOpen,requiredScope:`terminal.write`,deliveryClass:`create-command`},{method:M.terminalAttach,requiredScope:`terminal.write`,deliveryClass:`terminal-output`},{method:M.terminalWrite,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalResize,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalSignal,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalClear,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalRestart,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalClose,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.browserOpenSession,requiredScope:`browser.control`,deliveryClass:`create-command`},{method:M.browserListSessions,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.browserCloseSession,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserGetSession,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.browserCommand,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserClearBrowsingData,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserAttachDisplay,requiredScope:`browser.read`,deliveryClass:`subscription`},{method:M.computerInput,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserAddDisplayIceCandidate,requiredScope:`browser.read`,deliveryClass:`browser-control`},{method:M.devTunnelRegister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:M.devTunnelUnregister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:M.devTunnelList,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.threadDevRuntimeGet,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.threadDevRuntimeAllocatePort,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:M.threadDevRuntimeRelease,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:M.workspaceEnvironmentPreflight,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.workspaceEnsureScratch,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.serverGetConfig,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.serverRefreshProviders,requiredScope:`provider.read`,deliveryClass:`read`},{method:M.serverStartProviderAuth,requiredScope:`provider.manage`,deliveryClass:`create-command`},{method:M.serverRepairProviderAuthRuntime,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverDisconnectProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverGetProviderAuthSession,requiredScope:`provider.read`,deliveryClass:`read`},{method:M.serverCancelProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSubmitProviderAuthCode,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSyncPersonalCodexToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSyncPersonalClaudeToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverUpsertKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverRemoveKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverGetSettings,requiredScope:`settings.read`,deliveryClass:`read`},{method:M.serverUpdateSettings,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverUpdateEnvironmentDisplayName,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverGetTraceDiagnostics,requiredScope:`settings.read`,deliveryClass:`read`},{method:M.serverHeartbeat,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.usageGetSummary,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.pullRequestsList,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsListStats,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsDetail,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsActivity,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsThreadComments,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsDiffFileContents,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsRunAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsUpdate,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsComment,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsUpdateComment,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsSubmitReview,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsReplyToThread,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsSetThreadResolution,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsSetReaction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsInvalidate,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsReviewerCandidates,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsRequestReviewers,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.subscribeGitStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:M.subscribeVcsStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:M.subscribeTerminalEvents,requiredScope:`terminal.read`,deliveryClass:`terminal-output`},{method:M.subscribeTerminalMetadata,requiredScope:`terminal.read`,deliveryClass:`read`},{method:M.subscribeBrowserEvents,requiredScope:`browser.read`,deliveryClass:`browser-frame`},{method:M.subscribeServerConfig,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:M.subscribeServerLifecycle,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:M.subscribeAuthAccess,requiredScope:`provider.read`,deliveryClass:`subscription`},{method:M.subscribeWorkspaceReadiness,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:Gn.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:Gn.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:Gn.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:Gn.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:Gn.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:Gn.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.getArchivedShellSnapshot,requiredScope:`thread.read`,deliveryClass:`read`},{method:Gn.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.getThreadDetailPage,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.assetsCreateUrl,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.attachmentsCreateUploadUrl,requiredScope:`turn.dispatch`,deliveryClass:`create-command`},{method:M.attachmentsDelete,requiredScope:`turn.dispatch`,deliveryClass:`idempotent-command`},{method:Gn.searchThreads,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.providerUploadFeedback,requiredScope:`thread.read`,deliveryClass:`create-command`},{method:M.sourceControlLookupRepository,requiredScope:`git.read`,deliveryClass:`read`},{method:M.sourceControlCloneRepository,requiredScope:`project.write`,deliveryClass:`idempotent-command`}],yae=new Set([M.gitPull,M.gitRunStackedAction,M.gitCreateWorktree,M.gitRemoveWorktree,M.gitCreateBranch,M.gitCheckout,M.gitInit,M.gitPreparePullRequestThread,M.threadDevRuntimeAllocatePort,M.threadDevRuntimeRelease,M.serverUpsertKeybinding,M.serverRemoveKeybinding,M.serverUpdateEnvironmentDisplayName,Gn.dispatchCommand]),bae=vae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?yae.has(e.method)?`frame`:`metadata-only`:`none`}}),xae=_ae({registeredMethods:[...An.requests.keys()],policies:bae}),Wo={"project.create":{requiredScope:`project.write`,deliveryClass:`create-command`},"project.meta.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.script.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.delete":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"thread.create":{requiredScope:`thread.create`,deliveryClass:`create-command`},"thread.delete":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.archive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.settle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unsettle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unarchive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.meta.update":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.runtime-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.interaction-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.turn.start":{requiredScope:`turn.dispatch`,deliveryClass:`create-command`},"thread.turn.interrupt":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.user-input.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.checkpoint.revert":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.session.stop":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.plan-approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`}},Sae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function Cae(e){if(e.method!==Gn.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!Sae.has(t.type))return null;let n=t.type===`thread.plan-approval.respond`?t.promptId:t.requestId;if(typeof t.commandId!=`string`||t.commandId.length===0||typeof n!=`string`||n.length===0)throw new Ho(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Go(e){let t=xae.get(e.method)??null,n=gae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==Gn.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new Ho(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in Wo))throw new Ho(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=Wo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new Ho(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Ko=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},qo=class extends Ko{},Jo=class extends Ko{},Yo=class extends Ko{},wae=class extends Ko{},Tae=class extends Ko{},Eae=class extends Ko{},Dae=class extends Ko{},Oae=class extends Ko{},kae=class extends Ko{},Aae=class extends Ko{},Xo=class extends Ko{},Zo=jae(globalThis,{});function jae(e,t){return new Proxy(e,{get(n,r,i){return r in t?t[r]:e[r]},set(n,r,i){return r in t&&delete t[r],e[r]=i,!0},deleteProperty(n,r){let i=!1;return r in t&&(delete t[r],i=!0),r in e&&(delete e[r],i=!0),i},ownKeys(n){let r=Reflect.ownKeys(e),i=Reflect.ownKeys(t),a=new Set(i);return[...r.filter(e=>!a.has(e)),...i]},defineProperty(n,r,i){return r in t&&delete t[r],Reflect.defineProperty(e,r,i),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}async function Mae(){if(Zo!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e.subtle}catch(e){throw new Xo(e)}}var Qo=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await Mae())}},$o={Base:0,Psk:1,Auth:2,AuthPsk:3},Nae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},es={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},ts={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},ns=new Uint8Array,rs=0n,is=1n,as=2n,Pae=new Uint8Array([75,69,77,0,0]),os=new Uint8Array([72,80,75,69,45,118,49]);function ss(e){return new Uint8Array(cs(e))}function cs(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var Fae=class extends Qo{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:es.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:ns}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}init(e){this._suiteId=e}buildLabeledIkm(e,t){this._checkInit();let n=new Uint8Array(7+this._suiteId.byteLength+e.byteLength+t.byteLength);return n.set(os,0),n.set(this._suiteId,7),n.set(e,7+this._suiteId.byteLength),n.set(t,7+this._suiteId.byteLength+e.byteLength),n}buildLabeledInfo(e,t,n){this._checkInit();let r=new Uint8Array(9+this._suiteId.byteLength+e.byteLength+t.byteLength);return r.set(new Uint8Array([0,n]),0),r.set(os,2),r.set(this._suiteId,9),r.set(e,9+this._suiteId.byteLength),r.set(t,9+this._suiteId.byteLength+e.byteLength),r}async extract(e,t){await this._setup();let n=e.byteLength===0?new ArrayBuffer(this.hashSize):cs(e);if(n.byteLength!==this.hashSize)throw new qo(`The salt length must be the same as the hashSize`);let r=cs(t),i=await this._api.importKey(`raw`,n,this.algHash,!1,[`sign`]);return await this._api.sign(`HMAC`,i,r)}async expand(e,t,n){await this._setup();let r=cs(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=ns,c=ss(t),l=new Uint8Array(1);if(n>255*this.hashSize)throw Error(`Entropy limit reached`);let u=new Uint8Array(this.hashSize+c.length+1);for(let e=1,t=0;t<o.length;e++)l[0]=e,u.set(s,0),u.set(c,s.length),u.set(l,s.length+c.length),s=new Uint8Array(await this._api.sign(`HMAC`,i,u.slice(0,s.length+c.length+1))),o.length-t>=s.length?(o.set(s,t),t+=s.length):(o.set(s.slice(0,o.length-t),t),t+=o.length-t);return a}async extractAndExpand(e,t,n,r){await this._setup();let i=cs(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:cs(e),info:cs(n)},a,r*8)}async labeledExtract(e,t,n){return await this.extract(e,this.buildLabeledIkm(t,n))}async labeledExpand(e,t,n,r){return await this.expand(e,this.buildLabeledInfo(t,n,r),r)}_checkInit(){if(this._suiteId===ns)throw Error(`Not initialized. Call init()`)}},Iae=class extends Fae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:es.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}},ls=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function us(e,t){if(t<=0)throw Error(`i2Osp: too small size`);if(e>=256**t)throw Error(`i2Osp: too large integer`);let n=new Uint8Array(t);for(let r=0;r<t&&e;r++)n[t-(r+1)]=e%256,e=Math.floor(e/256);return n}function ds(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function fs(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function Lae(){if(Zo!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e}catch{throw Error(`failed to load Crypto`)}}function Rae(e,t){if(e.byteLength!==t.byteLength)throw Error(`xor: different length inputs`);let n=new Uint8Array(e.byteLength);for(let r=0;r<e.byteLength;r++)n[r]=e[r]^t[r];return n}var zae=new Uint8Array([101,97,101,95,112,114,107]),Bae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Vae(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(e,0),r.set(t,e.length),r.set(n,e.length+t.length),r}var Hae=class{constructor(e,t,n){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e,this._prim=t,this._kdf=n;let r=new Uint8Array(Pae);r.set(us(this.id,2),3),this._kdf.init(r)}async serializePublicKey(e){return await this._prim.serializePublicKey(e)}async deserializePublicKey(e){return await this._prim.deserializePublicKey(cs(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(cs(e))}async importKey(e,t,n=!0){return await this._prim.importKey(e,t,n)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(e){let t=cs(e);if(t.byteLength>8192)throw new qo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():ls(e.ekm)?e.ekm:await this.deriveKeyPair(e.ekm);let n=await this._prim.serializePublicKey(t.publicKey),r=await this._prim.serializePublicKey(e.recipientPublicKey);try{let i;if(e.senderKey===void 0)i=new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey));else{let n=ls(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=ds(new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey)),new Uint8Array(await this._prim.dh(n,e.recipientPublicKey)))}let a;if(e.senderKey===void 0)a=ds(new Uint8Array(n),new Uint8Array(r));else{let t=ls(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Vae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new wae(e)}}async decap(e){let t=cs(e.enc),n=await this._prim.deserializePublicKey(t),r=ls(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=ls(e.recipientKey)?e.recipientKey.publicKey:await this._prim.derivePublicKey(e.recipientKey),a=await this._prim.serializePublicKey(i);try{let i;i=e.senderPublicKey===void 0?new Uint8Array(await this._prim.dh(r,n)):ds(new Uint8Array(await this._prim.dh(r,n)),new Uint8Array(await this._prim.dh(r,e.senderPublicKey)));let o;if(e.senderPublicKey===void 0)o=ds(new Uint8Array(t),new Uint8Array(a));else{let n=await this._prim.serializePublicKey(e.senderPublicKey);o=new Uint8Array(t.byteLength+a.byteLength+n.byteLength),o.set(new Uint8Array(t),0),o.set(new Uint8Array(a),t.byteLength),o.set(new Uint8Array(n),t.byteLength+a.byteLength)}return await this._generateSharedSecret(i,o)}catch(e){throw new Tae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(zae,e),r=this._kdf.buildLabeledInfo(Bae,t,this.secretSize);return await this._kdf.extractAndExpand(ns,n,r,this.secretSize)}},ps=[`deriveBits`],Uae=new Uint8Array([100,107,112,95,112,114,107]),Wae=new Uint8Array([115,107]),ms=class{constructor(e,t,n,r=[]){Object.defineProperty(this,"key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extractable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"algorithm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.key=t,this.type=n,this.algorithm={name:e},this.usages=r,n===`public`&&(this.usages=[])}},Gae=class{constructor(e,t,n,r){Object.defineProperty(this,"_algName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_curve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._algName=e,this._nPk=t,this._nSk=t,this._curve=n,this._hkdf=r}serializePublicKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Jo(e))}}async deserializePublicKey(e){try{return await this._importRawKey(cs(e),!0)}catch(e){throw new Yo(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Jo(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(cs(e),!1)}catch(e){throw new Yo(e)}}async importKey(e,t,n){try{if(e===`raw`)return await this._importRawKey(t,n);if(t instanceof ArrayBuffer)throw Error(`Invalid jwk key format`);return await this._importJWK(t,n)}catch(e){throw new Yo(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new ms(this._algName,e,`private`,ps);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new Xo(e)}}async deriveKeyPair(e){try{let t=cs(e),n=await this._hkdf.labeledExtract(ns.buffer,Uae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Wae,ns,this._nSk),i=new ms(this._algName,new Uint8Array(r),`private`,ps);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Aae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new ms(this._algName,t,`public`))}catch(e){return Promise.reject(new Yo(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new Jo(e))}}_importRawKey(e,t){return new Promise((n,r)=>{t&&e.byteLength!==this._nPk&&r(Error(`Invalid length of the key`)),!t&&e.byteLength!==this._nSk&&r(Error(`Invalid length of the key`)),n(new ms(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:ps))})}_importJWK(e,t){return new Promise((n,r)=>{e.kty!==`OKP`&&r(Error(`Invalid kty: ${e.kty}`)),e.crv!==this._algName&&r(Error(`Invalid crv: ${e.crv}`)),t?(e.d!==void 0&&r(Error("Invalid key: `d` should not be set")),typeof e.x!=`string`&&r(Error("Invalid key: `x` not found")),n(new ms(this._algName,fs(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new ms(this._algName,fs(e.d),`private`,ps)))})}};function Kae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function hs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function gs(e,t,n=``){let r=Kae(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function _s(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function vs(e,t){gs(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function qae(e){if(typeof e==`bigint`){if(!ks(e))throw Error(`positive bigint expected, got `+e)}else hs(e);return e}function ys(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function bs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Jae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ss(e,t){return e<<32-t|e>>>t}var Cs=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Yae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Xae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Zae(e){if(gs(e),Cs)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Yae[e[n]];return t}var ws={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ts(e){if(e>=ws._0&&e<=ws._9)return e-ws._0;if(e>=ws.A&&e<=ws.F)return e-(ws.A-10);if(e>=ws.a&&e<=ws.f)return e-(ws.a-10)}function Qae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Cs)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=Ts(e.charCodeAt(i)),a=Ts(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function $ae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=rs;for(let n=0;n<e.length;n++){let r=Ts(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|Xae[r]}return t}function Es(e){hs(e,`numberToBigint`);let t=e,n=rs,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function Ds(e){return $ae(Zae(Os(gs(e)).reverse()))}function eoe(e,t){hs(t),e=qae(e);let n=Qae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function toe(e,t){return eoe(e,t).reverse()}function Os(e){return Uint8Array.from(e)}function ks(e){return typeof e==`bigint`&&0n<=e}function noe(e,t,n){return ks(e)&&ks(t)&&ks(n)&&t<=e&&e<n}function As(e,t,n,r){if(!noe(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function roe(e,t={},n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}let i=(e,t)=>Object.entries(e).forEach(([e,n])=>r(e,n,t));i(t,!1),i(n,!0)}async function ioe(e=32){let t=await Lae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function aoe(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function ooe(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);hs(e.outputLen),hs(e.blockLen)}function soe(e,t={}){let n=(t,n)=>e(n).update(t).digest(),r=e(void 0),i=Object.assign(n,{outputLen:r.outputLen,blockLen:r.blockLen,create:t=>e(t),...t});return Object.freeze(i)}var js=class{constructor(e,t){if(Object.defineProperty(this,"oHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),ooe(e),gs(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),bs(r)}update(e){return _s(this),this.iHash.update(e),this}digestInto(e){_s(this),gs(e,this.outputLen,`output`),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ms=(e,t,n)=>new js(e,t).update(n).digest();Ms.create=(e,t)=>new js(e,t);function coe(e,t,n){return e&t^~e&n}function loe(e,t,n){return e&t^e&n^t&n}var uoe=class{constructor(e,t,n,r){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"padOffset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isLE",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"view",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=xs(this.buffer)}update(e){_s(this),gs(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=xs(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){_s(this),vs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,bs(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;n.setBigUint64(r-8,Es(this.length*8),i),this.process(n,0);let o=xs(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen must be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ns=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),doe=Uint32Array.from([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]),Ps=new Uint32Array(64),foe=class extends uoe{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Ps[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ps[e-15],n=Ps[e-2],r=Ss(t,7)^Ss(t,18)^t>>>3,i=Ss(n,17)^Ss(n,19)^n>>>10;Ps[e]=i+Ps[e-7]+r+Ps[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=Ss(o,6)^Ss(o,11)^Ss(o,25),u=l+t+coe(o,s,c)+doe[e]+Ps[e]|0,d=(Ss(n,2)^Ss(n,13)^Ss(n,22))+loe(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){bs(Ps)}destroy(){this.set(0,0,0,0,0,0,0,0),bs(this.buffer)}},poe=class extends foe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Ns[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Ns[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Ns[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Ns[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Ns[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Ns[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Ns[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Ns[7]|0})}},Fs=soe(()=>new poe,aoe(1));function Is(e,t){let n=e%t;return n>=0n?n:t+n}function Ls(e,t,n){let r=e;for(;t-->rs;)r*=r,r%=n;return r}function moe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function hoe(e){return roe(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function goe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=hoe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||ioe,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?as**254n:as**447n,p=f+(o?8n*as**251n-is:4n*as**445n-is)+is,m=e=>Is(e,t),h=g(u);function g(e){return toe(m(e),l)}function _(e){let t=Os(gs(e,l,`uCoordinate`));return o&&(t[31]&=127),m(Ds(t))}function v(e){return Ds(r(Os(gs(e,l,`scalar`))))}function y(e,t){let n=w(_(t),v(e));if(n===0n)throw Error(`invalid private or public key received`);return g(n)}function b(e){return y(e,h)}let x=b,S=y;function C(e,t,n){let r=m(e*(t-n));return t=m(t-r),n=m(n+r),{x_2:t,x_3:n}}function w(e,n){As(`u`,e,rs,t),As(`scalar`,n,f,p);let r=n,a=e,o=is,s=rs,l=e,u=is,h=rs;for(let e=c-1n;e>=rs;e--){let t=r>>e&is;h^=t,{x_2:o,x_3:l}=C(h,o,l),{x_2:s,x_3:u}=C(h,s,u),h=t;let n=o+s,i=m(n*n),c=o-s,f=m(c*c),p=i-f,g=l+u,_=l-u,v=m(_*n),y=m(g*c),b=v+y,x=v-y;l=m(b*b),u=m(a*m(x*x)),o=m(i*f),s=m(p*(i+m(d*p)))}({x_2:o,x_3:l}=C(h,o,l)),{x_2:s,x_3:u}=C(h,s,u);let g=i(s);return m(o*g)}let T={secretKey:l,publicKey:l,seed:l},E=async e=>(e===void 0&&(e=await s(l)),gs(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:moe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Rs(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var _oe=(e,t)=>{function n(n,...r){if(gs(n,void 0,`key`),!Jae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];gs(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&gs(r[1],void 0,`AAD`);let a=t(n,...r),o=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);gs(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,gs(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(gs(e),i&&e.length<i)throw Error(`"ciphertext" expected length bigger than tagLength=`+i);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(n,e),n};function voe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function yoe(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function zs(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error(`"output" expected Uint8Array of length `+e+`, got: `+t.length);if(n&&!xoe(t))throw Error(`invalid output, must be aligned`);return t}function boe(e,t,n){Rs(n);let r=new Uint8Array(16),i=xs(r);return i.setBigUint64(0,Es(t),n),i.setBigUint64(8,Es(e),n),r}function xoe(e){return e.byteOffset%4==0}var Bs=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),Soe=Bs(`expand 16-byte k`),Coe=Bs(`expand 32-byte k`),woe=ys(Soe),Toe=ys(Coe);function Vs(e,t){return e<<t|e>>>32-t}function Hs(e){return e.byteOffset%4==0}var Us=64,Eoe=16,Ws=2**32-1,Gs=Uint32Array.of();function Doe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Us),u=ys(l),d=Hs(i)&&Hs(a),f=d?ys(i):Gs,p=d?ys(a):Gs;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Ws)throw Error(`arx: counter overflow`);let h=Math.min(Us,c-m);if(d&&h===Us){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Eoe;t++)n=e+t,p[n]=f[n]^u[t];m+=Us;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function Ooe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=voe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return hs(i),hs(o),Rs(a),Rs(n),(t,s,c,l,u=0)=>{gs(t,void 0,`key`),gs(s,void 0,`nonce`),gs(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),gs(l,void 0,`output`),hs(u),u<0||u>=Ws)throw Error(`arx: counter overflow`);if(l.length<d)throw Error(`arx: output (${l.length}) is shorter than data (${d})`);let f=[],p=t.length,m,h;if(p===32)f.push(m=Os(t)),h=Toe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=woe,f.push(m);else throw gs(t,32,`arx key`),Error(`invalid key size`);Hs(s)||f.push(s=Os(s));let g=ys(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,ys(s.subarray(0,16)),g),s=s.subarray(16)}let _=16-i;if(_!==s.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let v=ys(s);return Doe(e,h,g,v,c,l,u,o),bs(...f),l}}function Ks(e,t){return e[t++]&255|(e[t++]&255)<<8}var koe=class{constructor(e){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:new Uint8Array(16)}),Object.defineProperty(this,"r",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"h",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"pad",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(8)}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e=Os(gs(e,32,`key`));let t=Ks(e,0),n=Ks(e,2),r=Ks(e,4),i=Ks(e,6),a=Ks(e,8),o=Ks(e,10),s=Ks(e,12),c=Ks(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Ks(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=Ks(e,t+0),_=Ks(e,t+2),v=Ks(e,t+4),y=Ks(e,t+6),b=Ks(e,t+8),x=Ks(e,t+10),S=Ks(e,t+12),C=Ks(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),ee=i[4]+((y>>>4|b<<12)&8191),te=i[5]+(b>>>1&8191),ne=i[6]+((b>>>14|x<<2)&8191),O=i[7]+((x>>>11|S<<5)&8191),k=i[8]+((S>>>8|C<<8)&8191),re=i[9]+(C>>>5|r),A=0,ie=A+w*o+5*h*T+5*m*E+5*p*D+5*f*ee;A=ie>>>13,ie&=8191,ie+=5*d*te+5*u*ne+5*l*O+5*c*k+5*s*re,A+=ie>>>13,ie&=8191;let ae=A+w*s+T*o+5*h*E+5*m*D+5*p*ee;A=ae>>>13,ae&=8191,ae+=5*f*te+5*d*ne+5*u*O+5*l*k+5*c*re,A+=ae>>>13,ae&=8191;let oe=A+w*c+T*s+E*o+5*h*D+5*m*ee;A=oe>>>13,oe&=8191,oe+=5*p*te+5*f*ne+5*d*O+5*u*k+5*l*re,A+=oe>>>13,oe&=8191;let se=A+w*l+T*c+E*s+D*o+5*h*ee;A=se>>>13,se&=8191,se+=5*m*te+5*p*ne+5*f*O+5*d*k+5*u*re,A+=se>>>13,se&=8191;let ce=A+w*u+T*l+E*c+D*s+ee*o;A=ce>>>13,ce&=8191,ce+=5*h*te+5*m*ne+5*p*O+5*f*k+5*d*re,A+=ce>>>13,ce&=8191;let le=A+w*d+T*u+E*l+D*c+ee*s;A=le>>>13,le&=8191,le+=te*o+5*h*ne+5*m*O+5*p*k+5*f*re,A+=le>>>13,le&=8191;let ue=A+w*f+T*d+E*u+D*l+ee*c;A=ue>>>13,ue&=8191,ue+=te*s+ne*o+5*h*O+5*m*k+5*p*re,A+=ue>>>13,ue&=8191;let de=A+w*p+T*f+E*d+D*u+ee*l;A=de>>>13,de&=8191,de+=te*c+ne*s+O*o+5*h*k+5*m*re,A+=de>>>13,de&=8191;let fe=A+w*m+T*p+E*f+D*d+ee*u;A=fe>>>13,fe&=8191,fe+=te*l+ne*c+O*s+k*o+5*h*re,A+=fe>>>13,fe&=8191;let pe=A+w*h+T*m+E*p+D*f+ee*d;A=pe>>>13,pe&=8191,pe+=te*u+ne*l+O*c+k*s+re*o,A+=pe>>>13,pe&=8191,A=(A<<2)+A|0,A=A+ie|0,ie=A&8191,A>>>=13,ae+=A,i[0]=ie,i[1]=ae,i[2]=oe,i[3]=se,i[4]=ce,i[5]=le,i[6]=ue,i[7]=de,i[8]=fe,i[9]=pe}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;bs(n)}update(e){_s(this),gs(e),e=Os(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){bs(this.h,this.r,this.buffer,this.pad)}digestInto(e){_s(this),vs(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function Aoe(e){let t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}var joe=Aoe(e=>new koe(e));function Moe(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,ee=f,te=p,ne=m,O=h,k=g,re=_,A=v,ie=y,ae=b,oe=x;for(let e=0;e<a;e+=2)S=S+E|0,A=Vs(A^S,16),ne=ne+A|0,E=Vs(E^ne,12),S=S+E|0,A=Vs(A^S,8),ne=ne+A|0,E=Vs(E^ne,7),C=C+D|0,ie=Vs(ie^C,16),O=O+ie|0,D=Vs(D^O,12),C=C+D|0,ie=Vs(ie^C,8),O=O+ie|0,D=Vs(D^O,7),w=w+ee|0,ae=Vs(ae^w,16),k=k+ae|0,ee=Vs(ee^k,12),w=w+ee|0,ae=Vs(ae^w,8),k=k+ae|0,ee=Vs(ee^k,7),T=T+te|0,oe=Vs(oe^T,16),re=re+oe|0,te=Vs(te^re,12),T=T+te|0,oe=Vs(oe^T,8),re=re+oe|0,te=Vs(te^re,7),S=S+D|0,oe=Vs(oe^S,16),k=k+oe|0,D=Vs(D^k,12),S=S+D|0,oe=Vs(oe^S,8),k=k+oe|0,D=Vs(D^k,7),C=C+ee|0,A=Vs(A^C,16),re=re+A|0,ee=Vs(ee^re,12),C=C+ee|0,A=Vs(A^C,8),re=re+A|0,ee=Vs(ee^re,7),w=w+te|0,ie=Vs(ie^w,16),ne=ne+ie|0,te=Vs(te^ne,12),w=w+te|0,ie=Vs(ie^w,8),ne=ne+ie|0,te=Vs(te^ne,7),T=T+E|0,ae=Vs(ae^T,16),O=O+ae|0,E=Vs(E^O,12),T=T+E|0,ae=Vs(ae^T,8),O=O+ae|0,E=Vs(E^O,7);let se=0;r[se++]=o+S|0,r[se++]=s+C|0,r[se++]=c+w|0,r[se++]=l+T|0,r[se++]=u+E|0,r[se++]=d+D|0,r[se++]=f+ee|0,r[se++]=p+te|0,r[se++]=m+ne|0,r[se++]=h+O|0,r[se++]=g+k|0,r[se++]=_+re|0,r[se++]=v+A|0,r[se++]=y+ie|0,r[se++]=b+ae|0,r[se++]=x+oe|0}var Noe=Ooe(Moe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Poe=new Uint8Array(16),qs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Poe.subarray(n))},Foe=new Uint8Array(32);function Js(e,t,n,r,i){i!==void 0&&gs(i,void 0,`AAD`);let a=e(t,n,Foe),o=boe(r.length,i?i.length:0,!0),s=joe.create(a);i&&qs(s,i),qs(s,r),s.update(o);let c=s.digest();return bs(a,o),c}var Ys=_oe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=zs(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Js(e,t,n,s,r);return a.set(c,o),bs(c),a},decrypt(i,a){a=zs(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Js(e,t,n,o,r);if(!yoe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),bs(c),a}}))(Noe)),Ioe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(cs(e))}async seal(e,t,n){return await this._seal(cs(e),cs(t),cs(n))}async open(e,t,n){return await this._open(cs(e),cs(t),cs(n))}_seal(e,t,n){return new Promise(r=>{r(Ys(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(Ys(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},Loe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:ts.Chacha20Poly1305}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(e){return new Ioe(e)}};function Xs(){return new Promise((e,t)=>{t(new Xo(`Not supported`))})}var Roe=new Uint8Array([115,101,99]),Zs=class{constructor(e,t,n){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=e,this._kdf=t,this.exporterSecret=n}async seal(e,t){return await Xs()}async open(e,t){return await Xs()}async export(e,t){let n=cs(e);if(n.byteLength>8192)throw new qo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Roe,new Uint8Array(n),t)}catch(e){throw new Eae(e)}}},zoe=class extends Zs{},Boe=class extends Zs{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=r}},Qs=class extends Zs{constructor(e,t,n){if(super(e,t,n.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.key===void 0||n.baseNonce===void 0||n.seq===void 0)throw Error(`Required parameters are missing`);this._aead=n.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;let r=this._aead.createEncryptionContext(n.key);this._ctx={key:r,baseNonce:n.baseNonce,seq:n.seq}}computeNonce(e){let t=us(e.seq,e.baseNonce.byteLength);return Rae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new kae(`Message limit reached`);e.seq+=1}},Voe=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Hoe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},$s,ec=class{constructor(){$s.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Voe(this,$s,`f`);return Hoe(this,$s,t,`f`),await n,e}};$s=new WeakMap;var tc=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Uoe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},nc,Woe=class extends Qs{constructor(){super(...arguments),nc.set(this,void 0)}async open(e,t=ns.buffer){Uoe(this,nc,tc(this,nc,`f`)??new ec,`f`);let n=await tc(this,nc,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),cs(e),cs(t))}catch(e){throw new Oae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};nc=new WeakMap;var rc=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Goe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},ic,Koe=class extends Qs{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ic.set(this,void 0),this.enc=r}async seal(e,t=ns.buffer){Goe(this,ic,rc(this,ic,`f`)??new ec,`f`);let n=await rc(this,ic,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),cs(e),cs(t))}catch(e){throw new Dae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};ic=new WeakMap;var qoe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Joe=new Uint8Array([101,120,112]),Yoe=new Uint8Array([105,110,102,111,95,104,97,115,104]),Xoe=new Uint8Array([107,101,121]),Zoe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Qoe=new Uint8Array([115,101,99,114,101,116]),$oe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),ese=class extends Qo{constructor(e){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof e.kem==`number`)throw new qo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new qo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new qo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array($oe),this._suiteId.set(us(this._kem.id,2),4),this._suiteId.set(us(this._kdf.id,2),6),this._suiteId.set(us(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.encap(e),n;return n=e.psk===void 0?e.senderKey===void 0?$o.Base:$o.Auth:e.senderKey===void 0?$o.Psk:$o.AuthPsk,await this._keyScheduleS(n,t.sharedSecret,t.enc,e)}async createRecipientContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.decap(e),n;return n=e.psk===void 0?e.senderPublicKey===void 0?$o.Base:$o.Auth:e.senderPublicKey===void 0?$o.Psk:$o.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=ns.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=ns.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?ns:ss(n.psk.id),i=await this._kdf.labeledExtract(ns,Zoe,r),a=n.info===void 0?ns:ss(n.info),o=await this._kdf.labeledExtract(ns,Yoe,a),s=new Uint8Array(1+i.byteLength+o.byteLength);s.set(new Uint8Array([e]),0),s.set(new Uint8Array(i),1),s.set(new Uint8Array(o),1+i.byteLength);let c=n.psk===void 0?ns:ss(n.psk.key),l=this._kdf.buildLabeledIkm(Qoe,c),u=this._kdf.buildLabeledInfo(Joe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===ts.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(Xoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(qoe,s,this._aead.nonceSize),h=await this._kdf.extractAndExpand(t,l,m,this._aead.nonceSize);return{aead:this._aead,exporterSecret:d,key:p,baseNonce:new Uint8Array(h),seq:0}}async _keyScheduleS(e,t,n,r){let i=await this._keySchedule(e,t,r);return i.key===void 0?new Boe(this._api,this._kdf,i.exporterSecret,n):new Koe(this._api,this._kdf,i,n)}async _keyScheduleR(e,t,n){let r=await this._keySchedule(e,t,n);return r.key===void 0?new zoe(this._api,this._kdf,r.exporterSecret):new Woe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new qo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new qo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new qo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new qo(`Too long psk.id`)}}},tse=class extends ese{},nse=1n,ac=2n,rse=3n,ise=5n,oc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function ase(e){let t=10n,n=80n,r=oc,i=e*e%r*e%r,a=Ls(Ls(i,ac,r)*i%r,nse,r)*e%r,o=Ls(a,ise,r)*a%r,s=Ls(o,t,r)*o%r,c=Ls(s,20n,r)*s%r,l=Ls(c,40n,r)*c%r;return{pow_p_5_8:Ls(Ls(Ls(Ls(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,ac,r)*e%r,b2:i}}function ose(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var sse=(()=>{let e=oc;return goe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=ase(t);return Is(Ls(n,rse,e)*r,e)},adjustScalarBytes:ose})})(),cse=class extends Gae{constructor(e){super(`X25519`,32,sse,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new Jo(e))}}},sc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,lse=2**31,use=65536,dse=16,cc=32,lc=(1n<<255n)-19n,uc=new TextEncoder,dc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function fc(e){let t=0n;for(let n=0;n<e.length;n+=2)t|=BigInt(Number.parseInt(e.slice(n,n+2),16))<<BigInt(n/2*8);return t}var fse=new Set([0n,1n,fc(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),fc(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),lc-1n]),pse=new Uint8Array,pc=class extends Iae{async extract(e,t){return cs(Ms(Fs,e.byteLength===0?new Uint8Array(this.hashSize):ss(e),ss(t)))}async expand(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>255*this.hashSize)throw Error(`HKDF output length exceeds the RFC 5869 limit.`);let r=ss(e),i=ss(t),a=new Uint8Array(n),o=pse;for(let e=1,t=0;t<a.byteLength;e+=1){let n=_c([o,i,Uint8Array.of(e)]);o=new Uint8Array(Ms(Fs,r,n));let s=a.byteLength-t;a.set(o.subarray(0,Math.min(o.byteLength,s)),t),t+=Math.min(o.byteLength,s)}return cs(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},mc=new tse({kem:new class extends Hae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Nae.DhkemX25519HkdfSha256,new cse(e),e)}}(new pc),kdf:new pc,aead:new Loe}),hc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function gc(e){return new Uint8Array(e.slice(0))}function mse(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function _c(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}function vc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new hc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function yc(e){if(!Number.isSafeInteger(e)||e<0)throw new hc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function hse(e){return _c([vc(e.byteLength),e])}function bc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function gse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function xc(e){let t=``;for(let n=0;n<e.byteLength;n+=3){let r=e[n]??0,i=e[n+1]??0,a=e[n+2]??0,o=r<<16|i<<8|a;t+=dc[o>>>18&63],t+=dc[o>>>12&63],n+1<e.byteLength&&(t+=dc[o>>>6&63]),n+2<e.byteLength&&(t+=dc[o&63])}return t}function Sc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new hc(`channel_authentication_failed`,`Encrypted relay frame is not canonical base64url.`);let t=new Uint8Array(Math.floor(e.length*6/8)),n=0,r=0,i=0;for(let a of e){let e=dc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(xc(t)!==e)throw new hc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function _se(e){let t=new Uint8Array(e);t[31]=(t[31]??0)&127;let n=0n;for(let e=0;e<t.byteLength;e+=1)n|=BigInt(t[e]??0)<<BigInt(e*8);return fse.has(n%lc)}var vse={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new hc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return gc(await globalThis.crypto.subtle.digest(`SHA-256`,mse(e)))}},Cc={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new hc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function wc(e,t){let n=uc.encode(e).byteLength;if(n===0||n>256)throw new hc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function yse(e){let t=uc.encode(e).byteLength;if(t===0||t>65536)throw new hc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${use} UTF-8 bytes.`)}async function Tc(e,t=vse){yse(e.exactCompactTicket),wc(e.channelId,`Channel ID`),wc(e.runtimeId,`Runtime ID`),yc(e.connectionEpoch);let n=await t.sha256(uc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new hc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function bse(e){return xc(e.ticketDigest)}async function xse(e=Cc){let t=new Uint8Array(await e.randomBytes(cc));if(t.byteLength!==cc)throw new hc(`endpoint_key_invalid`,`The endpoint random source must return ${cc} bytes.`);try{return xc(t)}finally{t.fill(0)}}function Ec(e){return _c([uc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,bc(e.direction)])}function Dc(e){return _c([uc.encode(`forge-relay`),vc(4),e.binding.ticketDigest,uc.encode(e.binding.channelId),bc(e.binding.direction),gse(e.frameClass),yc(e.sequence),uc.encode(e.binding.runtimeId),yc(e.binding.connectionEpoch),vc(e.ciphertextLength)].map(hse))}async function Sse(e=Cc){let t=new Uint8Array(await e.randomBytes(cc));if(t.byteLength!==cc)throw new hc(`endpoint_key_invalid`,`The endpoint random source must return ${cc} bytes.`);try{return await mc.kem.deriveKeyPair(t)}catch(e){throw new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function Oc(e){try{return xc(gc(await mc.kem.serializePublicKey(e)))}catch(e){throw new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function Cse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new hc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function wse(e){try{let t=Sc(e);if(t.byteLength!==cc)throw Error(`Invalid endpoint key length.`);if(_se(t))throw new hc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await mc.kem.deserializePublicKey(t)}catch(e){throw e instanceof hc?e:new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var kc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Ac=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=lse||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new hc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function Tse(e,t){if(e.type!==`relay.encrypted-frame`||e.protocolVersion!==4||e.channelId!==t.channelId||e.direction!==t.direction||![`handshake`,`application`,`close`].includes(e.frameClass))throw new hc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var Ese=class{binding;context;encapsulatedKey;queue=new kc;budget=new Ac;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=xc(gc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new hc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+dse;this.budget.assertAvailable(t);let n=this.sequence,r=Dc({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=gc(await this.context.seal(e.plaintext,r))}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new hc(`channel_authentication_failed`,`Relay payload encryption returned an invalid ciphertext length.`);return this.sequence+=1,this.budget.commit(i.byteLength),{type:`relay.encrypted-frame`,protocolVersion:4,channelId:this.binding.channelId,direction:this.binding.direction,frameClass:e.frameClass,sequence:n,ciphertext:xc(i)}})}},Dse=class{binding;context;queue=new kc;budget=new Ac;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(Tse(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new hc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Sc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Dc({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=gc(await this.context.open(t,n))}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new hc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function Ose(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Cc).randomBytes(cc)),t.byteLength!==cc)throw Error(`The endpoint random source must return ${cc} bytes.`);let n=await mc.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:Ec(e.binding),ekm:t});return new Ese(e.binding,n)}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function kse(e){try{let t=await mc.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Sc(e.encapsulatedKey),info:Ec(e.binding)});return new Dse(e.binding,t)}catch(e){throw e instanceof hc?e:new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Ase=128,jse=2097152,Mse=864e5,jc=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Mc(e){return typeof e==`string`&&e.length>0}function Nc(e){return Mc(e)&&Number.isFinite(Date.parse(e))}function Nse(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function Pse(e){return Mc(e.transportRequestId)&&Mc(e.runtimeId)&&Mc(e.actorSessionId)&&Mc(e.durableRequestId)&&Mc(e.method)}function Fse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Ise(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Mc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function Lse(e){return!Nse(e.status)||e.errorCode!==null&&!Mc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Mc(e.errorCode):e.errorCode===null}function Rse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Pse(t)&&Fse(t)&&Ise(t)&&Lse(t)&&Nc(t.createdAt)&&Nc(t.updatedAt)}function zse(e){try{return JSON.parse(e)}catch{throw new jc(`Forge relay control journal is corrupt.`)}}function Bse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Mc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Rse)}function Vse(e){let t=new Set(e.map(Pc)),n=new Set(e.map(e=>e.durableRequestId)),r=new Set(e.map(e=>e.sequence));return t.size===e.length&&n.size===e.length&&r.size===e.length}function Hse(e){let t=zse(e);if(!Bse(t))throw new jc(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Vse(n)||t.nextSequence<=r)throw new jc(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Use(){return crypto.randomUUID()}function Pc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Fc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Wse(e,t){let n=e.filter(e=>e.runtimeId===t);if(n.length===0)return{state:`idle`,count:0};let r=n.reduce((e,t)=>Fc[t.status]>Fc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function Ic(e){let t=e.randomUUID??Use,n=e.now??(()=>new Date),r=e.maxRecords??Ase,i=e.maxBytes??jse,a=e.maxReplayAgeMs??Mse;if(r<1||i<1||a<1)throw new jc(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?Hse(o):{version:1,controlSessionId:t(),nextSequence:1,records:[]},l=new Map,u=new Set;function d(){return{controlSessionId:c.controlSessionId,records:[...c.records]}}function f(t){if(t.records.length>r)throw new jc(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new jc(`Forge relay control journal reached its storage limit.`);e.storage.write(n),c=t;let a=d();for(let e of u)e(a)}function p(e,t){return e.status!==`pending`&&e.status!==`retrying`?e:e.persistence===`metadata-only`||e.frame===null?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_COMMAND_OUTCOME_UNKNOWN`,updatedAt:t.toISOString()}:t.getTime()-Date.parse(e.createdAt)>a?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_RECOVERY_EXPIRED`,updatedAt:t.toISOString()}:e}let m=c.records.map(e=>p(e,s)),h=m.some((e,t)=>e!==c.records[t]);(o===null||h)&&f({...c,records:m});function g(e){let t=Pc(e);return{key:t,existing:c.records.find(e=>Pc(e)===t)??null}}function _(e,t,n){if([e.method===t.method,e.persistence===t.persistence,n===void 0||n===t.frame,e.frame===null||e.frame===t.frame,t.durableRequestId===void 0||e.durableRequestId===t.durableRequestId].includes(!1))throw new jc(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new jc(`Relay transport request ${t.transportRequestId} requires an explicit outcome acknowledgement.`)}function v(e){if(e.durableRequestId!==void 0&&c.records.some(t=>t.durableRequestId===e.durableRequestId))throw new jc(`Relay durable request ${e.durableRequestId} was reused by another transport request.`)}function y(e){let r=n().toISOString();return{runtimeId:e.runtimeId,actorSessionId:e.actorSessionId,transportRequestId:e.transportRequestId,durableRequestId:e.durableRequestId??t(),sequence:c.nextSequence,method:e.method,persistence:e.persistence,frame:e.persistence===`frame`?e.frame:null,status:`pending`,attemptCount:0,errorCode:null,createdAt:r,updatedAt:r}}function b(e){let{key:t,existing:n}=g(e);if(n!==null)return _(n,e,l.get(t)),l.set(t,e.frame),n;v(e);let r=y(e);return l.set(t,e.frame),f({...c,nextSequence:c.nextSequence+1,records:[...c.records,r]}),r}function x(e,t,n){let r=c.records.find(r=>r.runtimeId===e&&r.actorSessionId===t&&r.transportRequestId===n);if(!r)throw new jc(`Relay transport request ${n} is not journaled.`);return r}function S(e,t,r,i){x(e,t,r);let a=n().toISOString();l.delete(Pc({runtimeId:e,actorSessionId:t,transportRequestId:r})),f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?{...n,frame:null,status:`failed`,errorCode:i,updatedAt:a}:n)})}function C(e,t,r){let i=x(e,t,r);if(i.status===`failed`||i.status===`outcome-unknown`)throw new jc(`Relay transport request ${r} has no replayable outcome.`);let a={...i,status:i.attemptCount>0?`retrying`:`pending`,attemptCount:i.attemptCount+1,errorCode:null,updatedAt:n().toISOString()};return f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?a:n)}),a}function w(e,t,n){let r=c.records.filter(r=>r.runtimeId!==e||r.actorSessionId!==t||r.transportRequestId!==n);r.length!==c.records.length&&(l.delete(Pc({runtimeId:e,actorSessionId:t,transportRequestId:n})),f({...c,records:r}))}function T(e,t,n){let r=x(e,t,n);if(r.status!==`failed`&&r.status!==`outcome-unknown`)throw new jc(`Relay transport request ${n} does not have an acknowledgeable outcome.`);w(e,t,n)}function E(){let e=n(),t=c.records.map(t=>p(t,e));t.some((e,t)=>e!==c.records[t])&&f({...c,records:t})}function D(e,t){let r=n().toISOString(),i=c.records.map(n=>n.runtimeId!==e||n.actorSessionId===t||n.status!==`pending`&&n.status!==`retrying`?n:(l.delete(Pc(n)),{...n,frame:null,status:`outcome-unknown`,errorCode:`RELAY_ACTOR_SESSION_CHANGED`,updatedAt:r}));i.some((e,t)=>e!==c.records[t])&&f({...c,records:i})}return{controlSessionId:c.controlSessionId,prepare:b,records:()=>[...c.records],pending:()=>[...c.records],replayable:(e,t)=>(E(),c.records.filter(n=>n.runtimeId===e&&n.actorSessionId===t&&n.persistence===`frame`&&n.frame!==null&&(n.status===`pending`||n.status===`retrying`))),fenceActor:D,beginAttempt:C,markFailed:S,complete:w,acknowledge:T,subscribe:e=>(u.add(e),e(d()),()=>u.delete(e))}}function Gse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Kse=tn(pne),qse=gn(hne),Jse=gn(one),Yse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Lc(e,t){if(!Array.isArray(e))return null;for(let n of e)if(Array.isArray(n)&&n.length===2&&n[0]===t&&typeof n[1]==`string`)return n[1];return null}function Rc(e,t){let n=JSON.parse(e),r=hae(n);if(r!==null)return{messageType:`request`,...r};let i=Xse(n,t);if(i!==null)return i;let a=Zse(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function Xse(e,t){if(e._tag!==`Request`||typeof e.id!=`string`||e.id.length===0||typeof e.tag!=`string`||e.tag.length===0)return null;let n=Go({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Lc(e.headers,Qn.requestId)??e.id,method:e.tag,...n}}function Zse(e){return e._tag!==`Ack`&&e._tag!==`Interrupt`||typeof e.requestId!=`string`||e.requestId.length===0?null:{messageType:`acknowledgement`,requestId:e.requestId,correlationId:e.requestId,method:`@effect/rpc/${e._tag}`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`}}function zc(e,t){let n=new Event(`error`);return Object.defineProperties(n,{error:{value:Error(t),enumerable:!0},message:{value:`${e}: ${t}`,enumerable:!0}}),n}var Qse=new Set([`network`,`server`,`auth`,`permission`,`client`]),$se=new Set([`network`,`server`]);function ece(e){return e&&typeof e==`object`?e:{}}function tce(e){return typeof e.code==`string`&&e.code.length>0?e.code:typeof e.kind==`string`&&Qse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function nce(e){if(e.retryable===!0||typeof e.kind==`string`&&$se.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Bc(e){let t=ece(e);return{code:tce(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:nce(t)}}function Vc(e,t){let n=new Event(e.type),r=e;for(let e of t)r[e]!==void 0&&Object.defineProperty(n,e,{value:r[e],enumerable:!0});return n}function rce(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values(Qn).includes(e[0])}function Hc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function ice(e){if(!Array.isArray(e))return null;for(let t of e){let e=Hc(t);if(e?._tag!==`Fail`)continue;let n=Hc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function ace(e){let t=Hc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:ice(t.cause)??`RELAY_RPC_FAILED`}function Uc(e){if(typeof e!=`string`)return null;try{let t=Kse(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function oce(e,t){if(e.role===`control`&&e.protocolVersion===t&&e.protocolVersion>=1){if(e.protocolVersion===1)return null;if(e.actor!==void 0&&e.scopes!==void 0)return{runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch,protocolVersion:e.protocolVersion,actor:e.actor,scopes:e.scopes}}}function Wc(e,t,n){if(typeof e==`string`)try{let r=Hc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=ace(r);if(i===null){n.complete(t.runtimeId,t.actor.sessionId,r.requestId);return}n.markFailed(t.runtimeId,t.actor.sessionId,r.requestId,i)}catch{}}function sce(e){let t=Lc(e,Qn.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function cce(e){return{issuedAt:Lc(e,Qn.issuedAt)??new Date().toISOString(),expiresAt:Lc(e,Qn.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function lce(e){if(e!==2&&e!==3&&e!==4)throw new Ho(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function uce(e){let t=Cae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=dce(e.context);if(e.acquire===void 0)throw new Ho(`action_grant_required`,`CMMD action-grant issuance is unavailable for this remote response.`,!1);return e.acquire({...n,method:`orchestration.dispatchCommand`,...t,durableRequestId:e.identity.correlationId,payloadHash:e.payloadHash,requiredScope:`approval.respond`})}function dce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new Ho(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Gc(e.channelId),channelTicketDigest:Gc(e.channelTicketDigest),runtimeEndpointKeyId:Gc(e.runtimeEndpointKeyId),controlEndpointKeyId:Gc(e.controlEndpointKeyId)}}function Gc(e){if(typeof e==`string`&&e.length>0)return e;throw new Ho(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function fce(e){return e===void 0?{}:{sequence:e}}function Kc(e){return e===void 0?{}:{actionGrant:e}}async function pce(e){let t=Rc(e.data,e.context.scopes),n=JSON.parse(e.data),r=cce(n.headers),i=sce(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await uce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=lce(e.context.protocolVersion),c={messageType:t.messageType,requestId:t.requestId,correlationId:t.correlationId,method:t.method,requiredScope:t.requiredScope,deliveryClass:t.deliveryClass,runtimeId:e.context.runtimeId,connectionEpoch:e.context.connectionEpoch,actor:e.context.actor,...r,payloadHash:a,...fce(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Kc(o)}:{protocolVersion:4,...c,...Kc(o)}}function qc(e){return typeof e==`string`&&e.length>0}function mce(e){return[e.protocolVersion===4,qc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===sc,qc(e.channelId),qc(e.runtimeEndpointKeyId),qc(e.runtimeEndpointPublicKey),qc(e.controlEndpointKeyId),qc(e.controlEndpointPublicKey),qc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function Jc(e){if(!mce(e))throw new Ho(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function hce(e){if(await Oc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new Ho(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await wse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Tc({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Tc({exactCompactTicket:e.token,channelId:e.channelId,direction:`runtime-to-control`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider)]);return{controlToRuntimeBinding:n,runtimeToControlBinding:r,sender:await Ose({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function Yc(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function gce(e){return[e.confirmation.phase===e.expectedPhase,e.confirmation.channelId===e.route.channelId,e.confirmation.runtimeId===e.context.runtimeId,e.confirmation.connectionEpoch===e.context.connectionEpoch].every(Boolean)}function _ce(e){let{envelope:t}=e.application;return[t.runtimeId===e.context.runtimeId,t.connectionEpoch===e.context.connectionEpoch,t.actor.userId===e.context.actor.userId,t.actor.deviceId===e.context.actor.deviceId,t.actor.sessionId===e.context.actor.sessionId,t.payloadHash===e.payloadHash].every(Boolean)}async function vce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new Ho(`endpoint_key_invalid`,`The runtime attempted to replace its endpoint encapsulation.`,!1);return e.channel.recipient}if(e.message.sequence!==0||!e.message.encapsulatedKey)throw new Ho(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await kse({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var yce=class extends EventTarget{socket;route;relayCrypto;journal;lifecycle;acquireActionGrant;CONNECTING=WebSocket.CONNECTING;OPEN=WebSocket.OPEN;CLOSING=WebSocket.CLOSING;CLOSED=WebSocket.CLOSED;binaryType=`blob`;onopen=null;onclose=null;onerror=null;onmessage=null;authenticated=!1;context=null;payloadChannel=null;sendChain=Promise.resolve();constructor(e,t,n,r,i={},a){super(),this.socket=e,this.route=t,this.relayCrypto=n,this.journal=r,this.lifecycle=i,this.acquireActionGrant=a,e.addEventListener(`open`,()=>void this.beginAuthentication()),e.addEventListener(`message`,e=>void this.handleMessageSafely(e)),e.addEventListener(`error`,e=>{let t=Vc(e,[`error`,`message`]),n=typeof t.message==`string`?String(t.message):`Forge relay connection failed.`;this.lifecycle.onError?.({code:`RELAY_SOCKET_ERROR`,message:n}),this.emit(`error`,t)}),e.addEventListener(`close`,e=>{this.authenticated=!1,this.context=null,this.payloadChannel=null,this.lifecycle.onDisconnected?.({code:e.code,reason:e.reason}),this.emit(`close`,Vc(e,[`code`,`reason`,`wasClean`]))})}get bufferedAmount(){return this.socket.bufferedAmount}get extensions(){return this.socket.extensions}get protocol(){return this.socket.protocol}get readyState(){return this.authenticated?this.socket.readyState:WebSocket.CONNECTING}get url(){return this.route.relayWebSocketUrl}send(e){if(!this.authenticated||typeof e!=`string`)throw new DOMException(`Forge relay RPC socket is not open for text frames.`,`InvalidStateError`);if(this.route.protocolVersion===1){this.socket.send(JSON.stringify({type:`relay.frame`,payload:e}));return}let t=this.context;if(t===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);let n=Rc(e,t.scopes),r=n.messageType===`request`&&n.journalPersistence!==`none`?this.journal.prepare({runtimeId:t.runtimeId,actorSessionId:t.actor.sessionId,transportRequestId:n.requestId,...n.correlationId===n.requestId?{}:{durableRequestId:n.correlationId},method:n.method,frame:e,persistence:n.journalPersistence}):null;this.enqueueFrame(e,r)}enqueueFrame(e,t){this.sendChain=this.sendChain.then(()=>this.transmitFrame(e,t)).catch(e=>{let n=Bc(e);t!==null&&!n.retryable&&this.journal.markFailed(t.runtimeId,t.actorSessionId,t.transportRequestId,n.code),this.lifecycle.onError?.({code:n.code,message:n.message}),this.emit(`error`,zc(n.code,n.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${n.code}: ${n.message}`)})}async transmitFrame(e,t){let n=this.requireReadyContext(),r=await this.outboundFrame(e,t),i=await pce({data:r,context:n,crypto:this.relayCrypto,...this.acquireActionGrant?{acquireActionGrant:this.acquireActionGrant}:{}});if(n.protocolVersion===4){let e=await this.requirePayloadChannel().sender.seal({frameClass:`application`,plaintext:new TextEncoder().encode(JSON.stringify({payload:r,envelope:i}))});this.socket.send(JSON.stringify(e));return}this.socket.send(JSON.stringify({type:`relay.frame`,payload:r,envelope:i}))}requireReadyContext(){if(!this.authenticated||this.socket.readyState!==WebSocket.OPEN)throw new DOMException(`Forge relay RPC socket closed before send.`,`InvalidStateError`);if(this.context===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);return this.context}requirePayloadChannel(){let e=this.payloadChannel;if(e===null||e.phase!==`ready`)throw new Ho(`channel_confirmation_failed`,`The Forge relay endpoint channel is not confirmed.`,!1);return e}async outboundFrame(e,t){return t===null?e:this.withDurableHeaders(t,e)}async withDurableHeaders(e,t){let n=this.journal.beginAttempt(e.runtimeId,e.actorSessionId,e.transportRequestId),r=JSON.parse(t),i=await Oce({payload:Dce(e.method,r.payload),sequence:n.sequence,requestId:n.durableRequestId,issuedAt:new Date(n.updatedAt),crypto:this.relayCrypto}),a=Array.isArray(r.headers)?r.headers.filter(e=>!rce(e)):[];return JSON.stringify({...r,headers:[...a,...Object.entries(i)]})}close(e,t){this.socket.close(e,t)}asWebSocket(){return this}emit(e,t){this.dispatchEvent(t);let n=this[`on${e}`];n&&n.call(this.asWebSocket(),t)}async handleMessage(e){if(this.authenticated){if(this.context?.protocolVersion===4){await this.handleEncryptedApplicationMessage(e.data);return}this.context!==null&&Wc(e.data,this.context,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:e.data}));return}await this.handleAuthenticationMessage(e.data)}async handleMessageSafely(e){try{await this.handleMessage(e)}catch(e){let t=Bc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${t.code}: ${t.message}`)}}async beginAuthentication(){try{this.route.protocolVersion===4&&(this.payloadChannel=await hce(Jc(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Yse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Bc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Uc(e);if(t!==null){if(t.type===`relay.encrypted-frame`&&this.context?.protocolVersion===4){await this.handleEncryptedHandshakeMessage(t);return}if(t.type===`relay.error`){this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=oce(e,this.route.protocolVersion);if(t===void 0){this.socket.close(4400,`Forge relay authenticated the wrong role.`);return}if(t!==null&&t.protocolVersion===4){let n=Jc(this.route),r=this.payloadChannel;if(r===null||![e.runtimeId===n.runtimeId,e.connectionEpoch===n.connectionEpoch].every(Boolean)){this.socket.close(4400,`Forge relay authenticated stale endpoint metadata.`);return}t={...t,channelId:n.channelId,channelTicketDigest:bse(r.controlToRuntimeBinding),runtimeEndpointKeyId:n.runtimeEndpointKeyId,controlEndpointKeyId:n.controlEndpointKeyId},this.context=t;return}await this.activateAuthenticatedRelay(t)}async handleEncryptedHandshakeMessage(e){if(e.type!==`relay.encrypted-frame`)return;let t=this.payloadChannel,n=this.context,r=Jc(this.route);if(t===null||n===null||!Yc(e,r,`handshake`))throw new Ho(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await vce({channel:t,route:r,message:e})).open(e),a=qse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!gce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new Ho(`channel_confirmation_failed`,`The runtime endpoint confirmation does not match the CMMD route.`,!1);if(o===`runtime-hello`){let e=await t.sender.seal({frameClass:`handshake`,plaintext:new TextEncoder().encode(JSON.stringify({type:`relay.endpoint-confirmation`,protocolVersion:4,phase:`control-confirm`,channelId:r.channelId,runtimeId:n.runtimeId,connectionEpoch:n.connectionEpoch}))});t.phase=`awaiting-runtime-confirm`,this.socket.send(JSON.stringify(e));return}t.phase=`ready`,await this.activateAuthenticatedRelay(n)}async handleEncryptedApplicationMessage(e){let t=Uc(e);if(t?.type!==`relay.encrypted-frame`)throw new Ho(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!Yc(t,Jc(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new Ho(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Jse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!_ce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new Ho(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);Wc(i.payload,a,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:i.payload}))}async activateAuthenticatedRelay(e){this.context=e,this.authenticated=!0,this.lifecycle.onAuthenticated?.();let t=e===null?[]:this.replayForActor(e);for(let e of t)e.frame!==null&&this.enqueueFrame(e.frame,e);t.length>0&&await this.sendChain,this.emit(`open`,new Event(`open`))}replayForActor(e){return this.journal.fenceActor(e.runtimeId,e.actor.sessionId),this.journal.replayable(e.runtimeId,e.actor.sessionId)}};function bce(e,t,n=Xc,r=Ic({storage:Gse(),randomUUID:n.randomUUID}),i={},a){return new yce(e,t,n,r,i,a).asWebSocket()}var xce=Oo(Kn);async function Sce(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return btoa(String.fromCharCode(...new Uint8Array(n))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}var Xc={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:Sce},Zc=`forge-relay-binding=`,Cce=3e4;function wce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(Zc))throw Error(`Forge relay socket URL is missing its route binding.`);let n=decodeURIComponent(t.slice(20));if(n.length===0)throw Error(`Forge relay socket URL has an invalid route binding.`);return n}function Tce(e){let t=e.crypto??Xc,n=e.bindingTtlMs??Cce,r=e.createSocket??((e,t)=>new globalThis.WebSocket(e,t)),i=new Map;return{acquireSocketUrl:async()=>{let r=await e.acquireRoute(),a=t.randomUUID();if(i.has(a))throw Error(`Forge relay route binding identifier was reused.`);let o=new URL(r.relayWebSocketUrl);o.hash=`${Zc}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=wce(n),s=i.get(o);if(s===void 0)throw Error(`Forge relay route binding is missing, expired, or already consumed.`);return i.delete(o),clearTimeout(s.expires),e.lifecycle?.onConnecting?.(),bce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}var Qc=new Map;function Ece(e){let t=Qc.get(e);if(t!==void 0)return t;let n=Kn.requests.get(e);if(n===void 0)return null;let r=gn(n.payloadSchema);return Qc.set(e,r),r}function Dce(e,t){let n=Ece(e);if(n===null)return t;try{return n(t)}catch{return t}}async function Oce(e){let t=e.issuedAt??new Date,n=e.crypto??Xc;return{[Qn.requestId]:e.requestId??n.randomUUID(),[Qn.sequence]:String(e.sequence),[Qn.issuedAt]:t.toISOString(),[Qn.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[Qn.payloadHash]:await n.sha256Base64Url(pae(e.payload))}}function kce(e,t){return Qte(rne,({rpc:t,request:n,next:r})=>at(function*(){return Go({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function Ace(e,t=Xc){return xce.pipe(Se(kce(e,t)))}function jce(e){let t=e.crypto??Xc,n=Tce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=ht(n.acquireSocketUrl).pipe(c),i=he(aa,n.constructSocket),a=oa(r).pipe(E(i)),o=e.delayForRetry??fae,s=It(_(e.maxRetries??10),e=>rt(Ue(o(e)??0)));return mt(ko,Ao({retryPolicy:s,retryTransientErrors:!0})).pipe(E(De(a,Do)))}var $c=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Mce(e){let t=await Sse(e),n=await Oc(t.publicKey);return{keyPair:t,publicKey:n,keyId:Cse(`control`,n),channelNonce:await xse(e)}}function Nce(e){return{hpkeSuite:sc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function Pce(e){let t=e.route;if(t.protocolVersion!==4||t.hpkeSuite!==`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`||!t.channelId||!t.runtimeEndpointKeyId||!t.runtimeEndpointPublicKey||t.controlEndpointKeyId!==e.endpoint.keyId||t.controlEndpointPublicKey!==e.endpoint.publicKey||t.controlChannelNonce!==e.endpoint.channelNonce)throw new $c(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:sc,runtimeEndpointKeyId:t.runtimeEndpointKeyId,runtimeEndpointPublicKey:t.runtimeEndpointPublicKey,controlEndpointKeyId:e.endpoint.keyId,controlEndpointPublicKey:e.endpoint.publicKey,controlChannelNonce:e.endpoint.channelNonce,controlEndpointKeyPair:e.endpoint.keyPair,...e.digestProvider?{payloadDigestProvider:e.digestProvider}:{},...e.randomSource?{payloadRandomSource:e.randomSource}:{}}}var el=`~effect/ManagedRuntime`,tl=(e,t)=>{let n=t?.memoMap??eee(),r=gee(`parallel`),i=k(r,`sequential`),a={onFiberStart:pe(r)},s=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Nt(t=>(c||=f(Aee(o(e,n,i),e=>ft(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),Vee(ve(c)))),u={[el]:el,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?A(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return A(u.disposeEffect)},disposeEffect:kt(()=>(u.contextEffect=yee(`ManagedRuntime disposed`),u.cachedContext=void 0,He(u.scope,wt))),runFork(e,t){return u.cachedContext===void 0?f(nl(u,e),s(t)):We(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?cee(nl(u,e),s(t)):_te(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Qee(nl(u,e)):le(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?fe(nl(u,e)):See(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?pee(nl(u,e),s(t)):vee(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?A(nl(u,e),s(t)):ne(u.cachedContext)(e,s(t))}};return u};function nl(e,t){return Ct(e.contextEffect,e=>Te(t,e))}function rl(e,t=wne){return`${e}\0${t}`}function Fce(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=rl(e.threadId,e.terminalId);t.get(r)?.sessionEpoch!==e.sessionEpoch&&t.set(r,{sessionEpoch:e.sessionEpoch,nextControlSequence:1,tail:Promise.resolve(),pendingWriteBytes:0})},enqueue(r){if(n)return Promise.reject(Error(`Terminal control sequencer is disposed.`));let i=r.terminalId??`default`,a=t.get(rl(r.threadId,i));if(!a)return Promise.reject(Error(`Terminal must be opened before sending controls.`));let o=r.writeBytes??0;if(a.pendingWriteBytes+o>e.maxPendingWriteBytes)return Promise.reject(Error(`Terminal input queue is full while reconnecting.`));a.pendingWriteBytes+=o;let s=a.tail.then(async()=>{let t=a.nextControlSequence;await r.execute({sessionEpoch:a.sessionEpoch,controllerId:e.controllerId,controlSequence:t}),a.nextControlSequence=t+1});return a.tail=s.finally(()=>{a.pendingWriteBytes-=o}).catch(()=>void 0),s},remove(e,n){if(n){t.delete(rl(e,n));return}let r=`${e}\0`;for(let e of t.keys())e.startsWith(r)&&t.delete(e)},terminalIds(e){let n=`${e}\0`;return[...t.keys()].filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))},dispose(){n=!0,t.clear()}}}var il={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function al(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Ice(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?al(t.keyframe):null}function Lce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?il:t.streamGeneration>e.streamGeneration?al(t.keyframe):null}function Rce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return al(t.keyframe);if(t.sequence<=e.observedSequence)return il;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function zce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return il;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?il:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Bce(e,t){return Ice(e,t)??Lce(e,t)??Rce(e,t)??zce(e,t)}function Vce(e,t){let n=Bce(e,t);if(!n.observe)return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:e};let r=n.startsNewStream?t.sequence:Math.max(e.observedSequence,t.sequence),i={...e,observedSequence:r,gapCount:e.gapCount+n.missingFrameCount},a=n.accept?{...i,acceptedSequence:t.sequence,acceptedCapturedAt:t.capturedAt,...t.streamId?{streamId:t.streamId}:{},...t.streamGeneration===void 0?{}:{streamGeneration:t.streamGeneration}}:i;return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:a}}gn(sne);var ol=O(),sl=`Forge`,Hce=`Alpha`,cl=sl,ll=`0.13.4`,ul=Yt(`forge-app-top-bar drag-region @container/header-actions relative z-20 w-full min-w-0 shrink-0 bg-background`,`grid grid-cols-[minmax(0,1fr)_minmax(0,auto)] items-center`),dl=`flex h-full min-w-0 items-center gap-1 md:gap-1.5`,fl=`flex h-touch min-w-0 max-w-full touch-manipulation items-center justify-center rounded-lg px-3 text-foreground transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring md:h-7 md:px-2`,Uce={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`},Wce=`forge-app-shell flex w-full min-w-0 flex-row`,pl=`forge-app-shell flex w-full min-w-0 flex-col`,Gce=`flex min-h-0 min-w-0 flex-1 flex-col`,Kce=`relative flex h-[var(--forge-content-height)] min-h-0 min-w-0 flex-1 overflow-hidden`;function ml(e){let t=(0,ol.c)(19),{showStageBadge:n,tone:r,variant:i}=e,a=n!==void 0&&n,o=r===void 0?`default`:r,s=(i===void 0?`default`:i)===`auth`,c=s?20:16,l=s?`h-5 w-5 shrink-0`:`h-4 w-4 shrink-0`,u;t[0]!==c||t[1]!==l?(u=(0,Mr.jsx)(`img`,{className:l,src:`/forge-mark.svg`,width:c,height:c,alt:``,"aria-hidden":`true`}),t[0]=c,t[1]=l,t[2]=u):u=t[2];let d=u,f=s?`text-[15px] sm:text-base`:`text-sm`,p=o===`on-dark`?`text-primary-foreground`:`text-foreground`,m;t[3]!==f||t[4]!==p?(m=Yt(`truncate font-semibold tracking-tight`,f,p),t[3]=f,t[4]=p,t[5]=m):m=t[5];let h;t[6]===m?h=t[7]:(h=(0,Mr.jsx)(`span`,{className:m,children:sl}),t[6]=m,t[7]=h);let g=h,_=s?`rounded-full bg-muted/50 px-2 py-0.5 text-[9px] leading-none font-medium tracking-[0.14em] text-muted-foreground/70 uppercase [text-indent:0.14em]`:`rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] leading-none font-medium tracking-[0.18em] text-muted-foreground/60 uppercase [text-indent:0.18em]`,v;t[8]===_?v=t[9]:(v=(0,Mr.jsx)(`span`,{className:_,children:Hce}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Mr.jsxs)(`span`,{className:`flex items-center gap-2`,children:[d,g]}),t[10]=d,t[11]=g,t[12]=e):e=t[12];let n;return t[13]!==y||t[14]!==e?(n=(0,Mr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":cl,children:[e,y]}),t[13]=y,t[14]=e,t[15]=n):n=t[15],n}let b;return t[16]!==d||t[17]!==g?(b=(0,Mr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":cl,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function hl(e){let t=(0,ol.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Yt(`pointer-events-none flex select-none items-center`,n),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Mr.jsx)(ml,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Mr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}function qce(){let e=new Map;return{clear:()=>e.clear(),getItem:t=>e.get(t)??null,key:t=>Array.from(e.keys()).at(t)??null,get length(){return e.size},removeItem:t=>e.delete(t),setItem:(t,n)=>e.set(t,n)}}var gl=typeof window<`u`?window.localStorage:qce(),Jce=(e,t)=>nr(Rn(e))(t),Yce=(e,t)=>kte(Rn(e))(t),_l=(e,t)=>{let n=gl.getItem(e);return n?Jce(t,n):null},vl=(e,t,n)=>{let r=Yce(n,t);gl.setItem(e,r)},yl=e=>{gl.removeItem(e)},bl=`forge:local_storage_change`;function Xce(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(bl,{detail:{key:e}}))}function xl(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return _l(e,n)??t}catch(e){return console.error(`[LOCALSTORAGE] Error:`,e),t}}),a=(0,F.useCallback)(t=>{i(r=>{try{let i=typeof t==`function`?t(r):t;return i===null?yl(e):vl(e,i,n),queueMicrotask(()=>Xce(e)),i}catch(e){return console.error(`[LOCALSTORAGE] Error:`,e),r}})},[e,n]),o=(0,F.useRef)(e);return(0,F.useEffect)(()=>{if(o.current!==e){o.current=e;try{let r=_l(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=_l(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}},a=t=>{t.key===e&&r()},o=t=>{t.detail.key===e&&r()};return window.addEventListener(`storage`,a),window.addEventListener(bl,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(bl,o)}},[e,t,n]),[r,a]}var Sl=`cmmd-runtime:`;function Cl(e){return`${Sl}${e}`}var Zce=/^env_[0-9a-f]{32}$/,Qce=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,wl={shape:`local`,isCloud:!1,legacyRuntimeId:null},$ce={shape:`cloud-project-placeholder`,isCloud:!0,legacyRuntimeId:null},ele={shape:`durable-environment`,isCloud:!0,legacyRuntimeId:null};function Tl(e){if(typeof e!=`string`)return wl;if(e.startsWith(`cmmd-runtime:`)){let t=e.slice(Sl.length);return Qce.test(t)?{shape:`legacy-runtime`,isCloud:!0,legacyRuntimeId:t}:wl}return e.startsWith(`cmmd-cloud-project:`)?$ce:Zce.test(e)?ele:wl}var El=`forge:client-settings:v1`,tle=`forge:saved-environment-registry:v1`,nle=tr({environmentId:nn,label:j,httpBaseUrl:j,wsBaseUrl:j,createdAt:j,lastConnectedAt:Wn(j),cmmdOrganizationId:on(j),cmmdProjectId:on(j),runtimeId:on(j),runtimeTicketExpiresAt:on(j),lastAuthenticatedPullRequestCapability:on(Yn),bearerToken:on(j)}),Dl=tr({version:on(Fn),records:on(qn(nle))});function Ol(){return typeof window<`u`}var rle={uiFontSize:14,codeFontSize:15},ile=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function ale(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function ole(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(rle).filter(([t,n])=>e[t]===n);if(t.length===0)return null;let n={...e};for(let[e]of t)delete n[e];return n}function sle(e){let t=ile.flatMap(([t,n,r])=>{let i=e[t];if(typeof i!=`number`||!Number.isFinite(i))return[];let a=Math.min(r,Math.max(n,Math.round(i)));return a===i?[]:[[t,a]]});if(t.length===0)return null;let n={...e};for(let[e,r]of t)n[e]=r;return n}function kl(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[ale,ole,sle]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function cle(){if(!Ol())return null;try{let e=window.localStorage.getItem(El);return e?gn(er)(kl(JSON.parse(e))):null}catch{return null}}function lle(e){Ol()&&vl(El,e,er)}function Al(){if(!Ol())return{};try{return _l(`forge:saved-environment-registry:v1`,Dl)??{}}catch{return{}}}function jl(e){Ol()&&vl(tle,e,Dl)}function Ml(){return Al().records??[]}function ule(e){jl({version:1,records:e})}function dle(){return Ml().map(e=>Sn(e))}function fle(e){let t=new Map(Ml().map(e=>[e.environmentId,e]));ule(e.map(e=>{let n=Tl(e.environmentId).legacyRuntimeId===null?t.get(e.environmentId)?.bearerToken:void 0;return n?{...Sn(e),bearerToken:n}:Sn(e)}))}function ple(e){return Ml().find(t=>t.environmentId===e)?.bearerToken??null}function mle(e,t){let n=Al(),r=n.records??[],i=!1;return jl({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(Sn(n),{bearerToken:t})):n)}),i}function hle(e){let t=Al();jl({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?Sn(t):t)})}var gle=gn(er);function _le(){return typeof window>`u`?void 0:window.desktopBridge}function Nl(e){let t=_le(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function Pl(){let e=Nl(`getClientSettings`);if(e){let t=await e();return t?gle(t):null}return cle()}async function Fl(e){let t=Nl(`setClientSettings`);if(t)return t(e);lle(e)}async function Il(){let e=Nl(`getSavedEnvironmentRegistry`);return e?e():dle()}async function Ll(e){let t=Nl(`setSavedEnvironmentRegistry`);if(t)return t(e);fle(e)}async function Rl(e){let t=Nl(`getSavedEnvironmentSecret`);return t?t(e):ple(e)}async function zl(e,t){let n=Nl(`setSavedEnvironmentSecret`);return n?n(e,t):mle(e,t)}async function Bl(e){let t=Nl(`removeSavedEnvironmentSecret`);if(t)return t(e);hle(e)}var Vl=`token`;function Hl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Ul(e){let t=Hl(e).get(Vl)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Vl)?.trim()??``;return n.length>0?n:null}function vle(e){let t=new URL(e.toString()),n=Hl(t);return n.has(Vl)&&(n.delete(Vl),t.hash=n.toString()),t.searchParams.delete(Vl),t}function Wl(e,t){let n=new URL(e.toString());return n.searchParams.delete(Vl),n.hash=new URLSearchParams([[Vl,t]]).toString(),n}function yle(e,t){let n=new URL(e);return n.pathname=`/login`,Wl(n,t).toString()}function ble(e){return Wl(new URL(`/login`,window.location.href),e).toString()}var xle=`host`;function Sle(e){let t=new URL(e),n=Ul(t),r=new URL(`forge:///pair`);return r.searchParams.set(xle,t.origin),n&&r.searchParams.set(Vl,n),r.toString()}function Cle(e){return{_tag:`Value`,value:e}}function wle(e,t){return{_tag:`Record`,keys:e,value:t}}function Tle(e,t){return{_tag:`Array`,length:e,value:t}}Zt(`SourceError`);var Ele=$e(`effect/ConfigProvider`,{defaultValue:()=>kle()}),Dle={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Ole(e,t,n){let r=Object.create(Dle);return r.get=e,r.mapInput=t,r.prefix=n,r.load=r=>(t&&(r=t(r)),n&&(r=[...n,...r]),e(r)),r}function kle(e){let t=e?.env??{APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`56e2269e0c33f44c636004fc33f6c402fc8e59f4`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+56e2269e0c33f44c636004fc33f6c402fc8e59f4`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Ale(t);return Ole(e=>rt(Mle(n,t,e)))}function Ale(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e)i.children??={},i=i.children[t]??={};i.value=r}return t}var jle=/^(0|[1-9][0-9]*)$/;function Mle(e,t,n){let r=t[n.map(String).join(`_`)],i=Nle(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:Cle(r):a.every(e=>jle.test(e))?Tle(Math.max(...a.map(e=>parseInt(e,10)))+1,r):wle(new Set(a),r)}function Nle(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}var Gl=`~effect/Config`,Ple=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Fle={...Ke,...Cee,[Gl]:Gl,asEffect(){return Ct(Ele.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Ile(e){let t=Object.create(Fle);return t.parse=e,t}var Kl=Xe(function*(e,t){let n=yield*e.load(t);if(n!==void 0)switch(n._tag){case`Value`:return n.value;case`Record`:{if(n.value!==void 0)return n.value;let r={};for(let i of n.keys){let n=yield*Kl(e,[...t,i]);n!==void 0&&(r[i]=n)}return r}case`Array`:{if(n.value!==void 0)return n.value;let r=[];for(let i=0;i<n.length;i++)r.push(yield*Kl(e,[...t,i]));return r}}}),ql=Xe(function*(e,t,n){switch(e._tag){case`Objects`:{let r={};for(let i of e.propertySignatures){let e=i.name;if(typeof e==`string`){let a=yield*ql(i.type,t,[...n,e]);a!==void 0&&(r[e]=a)}}if(e.indexSignatures.length>0){let i=yield*t.load(n);if(i&&i._tag===`Record`)for(let a of e.indexSignatures){let e=Yte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*ql(a.type,t,[...n,o]);e!==void 0&&(r[o]=e)}}}return r}case`Arrays`:{let r=yield*t.load(n);if(r&&r._tag===`Value`)return r.value;let i=[];for(let r=0;r<e.elements.length;r++)i.push(yield*ql(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Kl(t,n);case`Suspend`:return yield*ql(e.thunk(),t,n);default:{let e=yield*t.load(n);return e===void 0?void 0:e._tag===`Value`||e._tag===`Record`&&e.value!==void 0||e._tag===`Array`&&e.value!==void 0?e.value:void 0}}});function Jl(e,t){let n=Gte(e),r=Ite(n),i=Zte(n.ast),a=typeof t==`string`?[t]:t??[];return Ile(e=>{let t=e.prefix?[...e.prefix,...a]:a;return ql(i,e,a).pipe(nte(e=>r(e).pipe(Ft(e=>new Ate(t.length>0?new Lte(t,e):e)))),Ft(e=>new Ple(e)))})}var Lle=(e,t,n)=>{let r=Pn(e,t),i=j.pipe(yn(Pn(j,j),Fte(n)),yn(r));return rr([r,i])},B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Yl=`10.74.0`;function Xl(){return Zl(V),V}function Zl(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.74.0`,t[Yl]=t[`10.74.0`]||{}}function Ql(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Yl]=r[`10.74.0`]||{};return i[e]||(i[e]=t())}var $l=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],Rle=`Sentry Logger `,eu={};function tu(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys(eu);r.forEach(e=>{let r=eu[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function zle(){iu().enabled=!0}function Ble(){iu().enabled=!1}function nu(){return iu().enabled}function Vle(...e){ru(`log`,...e)}function Hle(...e){ru(`warn`,...e)}function Ule(...e){ru(`error`,...e)}function ru(e,...t){B&&nu()&&tu(()=>{V.console[e](`${Rle}[${e}]:`,...t)})}function iu(){return B?Ql(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:zle,disable:Ble,isEnabled:nu,log:Vle,warn:Hle,error:Ule},au=50,ou=/\(error: (.*)\)/,su=/captureMessage|captureException/;function cu(...e){let t=e.sort((e,t)=>e[0]-t[0]).map(e=>e[1]);return(e,n=0,r=0)=>{let i=[],a=e.split(`
2
+ import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$t as i,Aa as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as h,Di as g,Dn as _,Dt as v,Ei as y,En as b,Er as x,Et as S,F as C,Fa as w,Fi as T,Fn as E,Fr as D,Ft as ee,Gn as te,Gt as ne,Ha as O,Hn as k,Hr as re,Ht as A,Ia as ie,Ir as ae,It as oe,J as se,Jn as ce,Jt as le,K as ue,Kn as de,Kt as fe,L as pe,La as me,Ln as he,Lr as ge,Lt as _e,M as ve,Ma as ye,Mi as be,Mr as xe,Mt as Se,N as Ce,Ni as we,Nn as eee,Nt as Te,O as tee,Oa as nee,On as ree,Ot as iee,P as aee,Pa as oee,Pi as Ee,Pn as De,Pt as Oe,Qi as ke,Qn as Ae,Qt as see,R as je,Rn as Me,Rr as Ne,Rt as cee,Si as lee,Sn as uee,T as Pe,Ta as Fe,Tn as dee,Tr as Ie,Tt as Le,U as Re,Ua as fee,Un as ze,Ur as Be,Ut as pee,V as mee,Va as Ve,Vn as He,Vr as Ue,Vt as We,W as Ge,Wa as hee,Wn as gee,Wr as _ee,Wt as vee,X as yee,Xn as bee,Y as xee,Yi as Ke,Yn as qe,Yt as See,Z as Je,Zi as Cee,Zn as wee,Zt as Tee,_ as Eee,_a as Ye,_n as Dee,_r as Oee,_t as kee,an as Aee,at as Xe,bn as jee,br as Mee,bt as Ze,ca as Qe,ci as $e,cn as Nee,ct as et,di as Pee,dn as Fee,dr as Iee,dt as tt,ea as nt,ei as Lee,en as rt,er as Ree,et as zee,fi as it,fr as Bee,ft as at,gi as ot,gn as st,gt as ct,hn as lt,hr as ut,ht as dt,in as ft,it as Vee,j as pt,ja as Hee,jn as mt,jr as Uee,jt as ht,ki as gt,kr as Wee,kt as _t,li as vt,ln as Gee,m as Kee,mn as yt,mr as bt,mt as xt,na as qee,ni as Jee,nr as St,nt as Ct,oa as Yee,on as Xee,or as wt,pi as Zee,pn as Tt,pt as Et,q as Dt,qn as Ot,qt as Qee,r as $ee,ri as ete,rn as kt,rr as tte,rt as nte,s as rte,si as ite,sn as ate,st as At,ui as ote,un as jt,ut as Mt,vn as Nt,vr as ste,vt as cte,w as Pt,wn as lte,wr as ute,wt as Ft,x as dte,xi as fte,xn as It,y as pte,yi as mte,yn as Lt,yt as hte,z as Rt,zn as gte,zt as _te}from"./Stream-mUTFnSY9.js";import{i as vte,l as zt,n as Bt,o as Vt,s as Ht}from"./atomRegistry-C1yW8tyM.js";import{En as yte,Fn as Ut,J as Wt,On as bte,Rn as xte,Tn as Gt,an as Kt,cn as Ste,dn as qt,fn as Jt,gn as Cte,hn as Yt,i as wte,ln as Tte,on as Ete,sn as Xt,un as Dte}from"./CompositeItem-B_Qce_Zi.js";import{$n as Zt,$t as Ote,A as Qt,An as kte,At as $t,Bn as Ate,Bt as jte,C as Mte,Ct as Nte,D as en,Dn as tn,Dt as nn,En as rn,Et as an,Fn as on,Ft as Pte,Gn as Fte,Gt as sn,H as cn,Hn as Ite,Ht as ln,In as un,It as dn,Jn as Lte,Jt as Rte,Kt as fn,L as zte,Ln as pn,Lt as Bte,Mn as Vte,Mt as mn,Nt as Hte,O as hn,On as gn,Pn as _n,Pt as Ute,Qt as Wte,Rn as Gte,Rt as Kte,St as vn,Tn as yn,Tt as bn,U as qte,Un as Jte,Ut as xn,V as Sn,Vn as Yte,Vt as Cn,W as Xte,Wn as Zte,Wt as wn,Xt as Tn,Y as Qte,Yt as $te,Z as ene,Zt as tne,_n as j,_t as En,a as nne,an as Dn,b as On,bn as kn,c as An,cn as jn,d as rne,dt as Mn,en as ine,et as ane,f as one,fn as Nn,g as sne,gn as Pn,gt as cne,hn as Fn,ht as In,i as lne,in as une,j as Ln,jn as Rn,jt as zn,k as dne,kn as fne,kt as Bn,l as Vn,ln as Hn,lt as Un,m as pne,mn as Wn,nn as mne,nt as Gn,o as Kn,on as qn,p as hne,pn as gne,pt as _ne,q as vne,qt as Jn,rn as yne,s as M,sn as Yn,tn as Xn,tt as Zn,u as Qn,ut as $n,v as er,vn as tr,w as bne,wn as nr,x as xne,xn as rr,yn as Sne,yt as Cne,z as wne,zt as ir}from"./src-IM0FnQax.js";import{A as ar,C as Tne,D as or,F as Ene,I as Dne,L as sr,M as cr,N as One,O as lr,S as kne,T as ur,a as dr,b as Ane,c as jne,d as Mne,j as fr,k as pr,l as Nne,n as mr,s as Pne,u as Fne,v as Ine,x as Lne,y as Rne}from"./cmmdAuthRedirect-lzr9SGGx.js";import{t as N}from"./preload-helper-Czpn1I53.js";import{n as P,t as hr}from"./transport-CgH8pQK3.js";import{n as zne,t as Bne}from"./workspaceReadinessAtom-D6bgTvKb.js";function Vne(e){return e[e.length-1]}function Hne(e,t){return typeof e==`function`?e(t):e}var gr=Object.prototype.hasOwnProperty,Une=Object.prototype.propertyIsEnumerable;function Wne(e){for(let t in e)if(gr.call(e,t))return!0;return!1}var Gne=()=>Object.create(null),Kne=(e,t)=>_r(e,t,Gne);function _r(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=xr(e)&&xr(i);if(!a&&!(yr(e)&&yr(i)))return i;let o=a?e:vr(e);if(!o)return i;let s=a?i:vr(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:gr.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=_r(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function vr(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!Une.call(e,r))return!1;t.push(r)}return t}function yr(e){if(!br(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!br(n)||!n.hasOwnProperty(`isPrototypeOf`))}function br(e){return Object.prototype.toString.call(e)===`[object Object]`}function xr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Sr(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!Sr(e[r],t[r],n))return!1;return!0}if(yr(e)&&yr(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Sr(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!Sr(e[o],t[o],n)))return!1;return i===a}return!1}var qne=/[\x00-\x1f\x7f"<>`{}]/g;function Jne(e){return e.replace(qne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Cr(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return Jne(t)}var Yne=[`http:`,`https:`,`mailto:`,`tel:`];function Xne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Zne(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=Cr(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Cr(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Qne(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function $ne(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function wr(){throw Error(`Invariant failed`)}var F=t(hee(),1),Tr=F.createContext(null);function Er(e){return F.useContext(Tr)}var Dr=F.createContext(void 0),ere=F.createContext(void 0),tre=xte();function nre(e,t){return e===t}function Or(e,t,n=nre){let r=(0,F.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,F.useCallback)(()=>e?.get(),[e]);return(0,tre.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var kr={};function Ar(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=_r(n.current,i):i}}function jr(e){let t=Er(),n=F.useContext(e.from?ere:Dr),r=e.from??n,i=t.stores.getMatchStore(r),a=Ar(e,t),o=Or(i,e=>e?a(e):kr);if(o!==kr)return o;(e.shouldThrow??!0)&&wr()}function rre(e){return jr({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}var Mr=fee(),Nr=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Pr=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Fr=new class extends Pr{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},ire={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ir=new class{#e=ire;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function are(e){setTimeout(e,0)}var ore=typeof window>`u`||`Deno`in globalThis;function Lr(){}function sre(e,t){return typeof e==`function`?e(t):e}function Rr(e){return typeof e==`number`&&e>=0&&e!==1/0}function zr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Br(e,t){return typeof e==`function`?e(t):e}function Vr(e,t){return typeof e==`function`?e(t):e}function cre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Hr(o,t.options))return!1}else if(!Wr(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function lre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Ur(t.options.mutationKey)!==Ur(a))return!1}else if(!Wr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Hr(e,t){return(t?.queryKeyHashFn||Ur)(e)}function Ur(e){return JSON.stringify(e,(e,t)=>Jr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Wr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Wr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Wr(e[r],t[r]))return!1;return!0}return!1}var ure=Object.prototype.hasOwnProperty;function Gr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=qr(e)&&qr(t);if(!r&&!(Jr(e)&&Jr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ure.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Gr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Kr(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function qr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Jr(e){if(!Yr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Yr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Yr(e){return Object.prototype.toString.call(e)===`[object Object]`}function dre(e){return new Promise(t=>{Ir.setTimeout(t,e)})}function Xr(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Gr(e,t)}function fre(e){return e}function pre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function mre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Zr=Symbol();function Qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Zr?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function $r(e,t){return typeof e==`function`?e(...t):!!e}function hre(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ei=(()=>{let e=()=>ore;return{isServer(){return e()},setIsServer(t){e=t}}})();function ti(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var gre=are;function _re(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=gre,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var ni=_re(),ri=new class extends Pr{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function vre(e){return Math.min(1e3*2**e,3e4)}function ii(e){return(e??`online`)!==`online`||ri.isOnline()}var ai=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function oi(e){let t=!1,n=0,r,i=ti(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ai(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Fr.isFocused()&&(e.networkMode===`always`||ri.isOnline())&&e.canRun(),u=()=>ii(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ei.isServer()?0:3),o=e.retryDelay??vre,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),dre(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var si=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rr(this.gcTime)&&(this.#e=Ir.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ei.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Ir.clearTimeout(this.#e),this.#e=void 0)}};function yre(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{hre(e,()=>t.signal,()=>n=!0)},u=Qr(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?mre:pre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?li:ci,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ci(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ci(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function li(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bre(e,t){return t?ci(e,t)!=null:!1}function xre(e,t){return!t||!e.getPreviousPageParam?!1:li(e,t)!=null}var Sre=class extends si{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fi(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=fi(this.options);e.data!==void 0&&(this.setState(di(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Xr(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Vr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zr||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Br(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!zr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Qr(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?yre(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=oi({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ai&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ai){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...ui(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...di(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),ni.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function ui(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ii(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function di(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function fi(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var pi=class extends Pr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ti(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),mi(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return hi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return hi(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Vr(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Kr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&gi(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Vr(this.options.enabled,this.#t)!==Vr(t.enabled,this.#t)||Br(this.options.staleTime,this.#t)!==Br(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Vr(this.options.enabled,this.#t)!==Vr(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return wre(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Lr)),t}#g(){this.#b();let e=Br(this.options.staleTime,this.#t);if(ei.isServer()||this.#r.isStale||!Rr(e))return;let t=zr(this.#r.dataUpdatedAt,e)+1;this.#d=Ir.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(ei.isServer()||Vr(this.options.enabled,this.#t)===!1||!Rr(this.#p)||this.#p===0)&&(this.#f=Ir.setInterval(()=>{(this.options.refetchIntervalInBackground||Fr.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Ir.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Ir.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&mi(e,t),o=i&&gi(e,n,t,r);(a||o)&&(l={...l,...ui(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=Xr(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=Xr(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:_i(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Vr(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{let e=this.#o=x.promise=ti();i(e)},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a()}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!Kr(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){ni.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Cre(e,t){return Vr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Vr(t.retryOnMount,e)!==!1)}function mi(e,t){return Cre(e,t)||e.state.data!==void 0&&hi(e,t,t.refetchOnMount)}function hi(e,t,n){if(Vr(t.enabled,e)!==!1&&Br(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&_i(e,t)}return!1}function gi(e,t,n,r){return(e!==t||Vr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&_i(e,n)}function _i(e,t){return Vr(t.enabled,e)!==!1&&e.isStaleByTime(Br(t.staleTime,e))}function wre(e,t){return!Kr(e.getCurrentResult(),t)}var vi=F.createContext(void 0),yi=e=>{let t=F.useContext(vi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Tre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Mr.jsx)(vi.Provider,{value:e,children:t})),bi=F.createContext(!1),xi=()=>F.useContext(bi);bi.Provider;function Ere(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Dre=F.createContext(Ere()),Si=()=>F.useContext(Dre),Ci=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?$r(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},wi=e=>{F.useEffect(()=>{e.clearReset()},[e])},Ti=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||$r(n,[e.error,r])),Ei=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Ore=(e,t)=>e.isLoading&&e.isFetching&&!t,Di=(e,t)=>e?.suspense&&t.isPending,Oi=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ki(e,t,n){let r=xi(),i=Si(),a=yi(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Ei(o),Ci(o,i,s),wi(i);let l=!a.getQueryCache().get(o.queryHash),[u]=F.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(F.useSyncExternalStore(F.useCallback(e=>{let t=f?u.subscribe(ni.batchCalls(e)):Lr;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Di(o,d))throw Oi(o,u,i);if(Ti({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!ei.isServer()&&Ore(d,r)&&(l?Oi(o,u,i):s?.promise)?.catch(Lr).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Ai(e,t){return ki(e,pi,t)}function kre(e){return e}var Are={[Symbol.iterator](){return jre}},jre={next(){return{done:!0,value:void 0}}},Mre=()=>Are,Nre=x,ji=globalThis.Number,Pre=e=>{if(e===`NaN`)return T(NaN);if(e===`Infinity`)return T(1/0);if(e===`-Infinity`)return T(-1/0);if(e.trim()===``)return Ee();let t=ji(e);return ji.isNaN(t)?Ee():T(t)},Fre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Mi=`~effect/http/HttpClientRequest`,Ire={[Mi]:Mi,...ke,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Yee(this.headers),body:this.body.toJSON()}},pipe(){return Ve(this,arguments)}};function Ni(e,t,n,r,i,a){let o=Object.create(Ire);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Lre=Ni(`GET`,``,tne,Ee(),Cn,$te),Pi=e=>(t,n)=>zre(Lre,{method:e,url:t,...n??void 0}),Rre=Pi(`POST`),zre=w(2,(e,t)=>{let n=e;return t.method&&(n=Bre(n,t.method)),t.url&&(n=Ure(n,t.url)),t.headers&&(n=Fi(n,t.headers)),t.urlParams&&(n=Wre(n,t.urlParams)),t.hash&&(n=Gre(n,t.hash)),t.body&&(n=Li(n,t.body)),t.accept&&(n=Ii(n,t.accept)),t.acceptJson&&(n=Hre(n)),n}),Bre=w(2,(e,t)=>Ni(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Vre=w(3,(e,t,n)=>Ni(e.method,e.url,e.urlParams,e.hash,Jn(e.headers,t,n),e.body)),Fi=w(2,(e,t)=>Ni(e.method,e.url,e.urlParams,e.hash,Rte(e.headers,t),e.body)),Ii=w(2,(e,t)=>Vre(e,`Accept`,t)),Hre=Ii(`application/json`),Ure=w(2,(e,t)=>{if(typeof t==`string`)return Ni(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Wte(n.searchParams),i=fte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Ni(e.method,n.toString(),r,i,e.headers,e.body)}),Wre=w(2,(e,t)=>Ni(e.method,e.url,ine(e.urlParams,t),e.hash,e.headers,e.body)),Gre=w(2,(e,t)=>Ni(e.method,e.url,e.urlParams,T(t),e.headers,e.body)),Li=w(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=fn(fn(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Jn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Jn(n,`content-length`,t.contentLength.toString()))),Ni(e.method,e.url,e.urlParams,e.hash,n,t)}),Kre=e=>xn({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${we(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),Ri=`~effect/http/HttpClient`,zi=vt(`effect/HttpClient`),Bi=w(2,(e,t)=>Vi(n=>t(e.postprocess(n)),e.preprocess)),qre=Bi(Ct(Bte)),Vi=(e,t)=>{let n=Object.create(Jre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Jre={[Ri]:Ri,pipe(){return Ve(this,arguments)},...ke,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Fre.map(([e,t])=>[t,function(t,n){return this.execute(Pi(e)(t,n))}]))},Yre=e=>Vi(t=>Ct(t,t=>Nt(n=>{let i=$re.get(t),a=i??new AbortController,o=Ote(t.url,t.urlParams,y(t.hash));if(Jee(o))return r(new Xn({reason:new yne({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Wee)||n.getRef(Hi)(t)){let r=e(t,s,a.signal,n);return i?r:Tt(e=>Le(e(r),{onSuccess(e){return Wi.register(e,a),rt(new Gi(e,a))},onFailure(e){return bt(e)&&a.abort(),zee(e)}}))}return lt(n.getRef(Zre)(t),{kind:`client`},r=>{r.attribute(`http.request.method`,t.method),r.attribute(`server.address`,s.origin),s.port!==``&&r.attribute(`server.port`,+s.port),r.attribute(`url.full`,s.toString()),r.attribute(`url.path`,s.pathname),r.attribute(`url.scheme`,s.protocol.slice(0,-1));let o=s.search.slice(1);o!==``&&r.attribute(`url.query`,o);let c=n.getRef(jte),l=sn(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Ui)?Fi(t,Kre(r)):t,Tt(o=>o(e(t,s,a.signal,n)).pipe(Lt(r,{captureStackTrace:!1}),Le({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=sn(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?rt(e):(Wi.register(e,a),rt(new Gi(e,a)))},onFailure(e){return!i&&bt(e)&&a.abort(),zee(e)}})))})})),rt),Xre=w(2,(e,t)=>{let n=dee(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,o=i&&b(i),s=n?void 0:t.times;return Bi(e,ie(r===`errors-only`?me:oe({schedule:o,times:s,while:qi}),r===`response-only`?me:_e({while:n||t.while===void 0?Ki:a(Ki,t.while),schedule:i,times:s})))}),Hi=$e(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Hee}),Ui=$e(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:ye}),Zre=$e(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Qre=e=>mt(zi)(se(t=>Ze(e,e=>Bi(e,yt(e=>ot(t,e)))))),Wi=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new Map;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),$re=new WeakMap,Gi=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[dn]=dn;[ir]=ir;applyInterrupt(e){return kt(()=>(Wi.unregister(this.original),_t(e,()=>ft(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return Eee(()=>(Wi.unregister(this.original),$ee(this.original.stream,ft(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[nt](){return this.original[nt]()}pipe(){return Ve(this,arguments)}},Ki=e=>Mee(e)||eie(e),eie=e=>Dn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&qi(e.reason.response)),qi=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Ji=`~effect/FiberSet`,tie=e=>Ye(e,Ji),nie={[Ji]:Ji,[Symbol.iterator](){return this.state._tag===`Closed`?Mre():this.state.backing[Symbol.iterator]()},...Ke,toJSON(){return{_id:`FiberMap`,state:this.state}}},rie=(e,t)=>{let n=Object.create(nie);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},iie=()=>je(ft(()=>rie(new Set,qe())),e=>kt(()=>{let t=e.state;if(t._tag===`Closed`)return st;e.state={_tag:`Closed`};let n=t.backing;return C(n).pipe(ce(e.deferred))})),Yi=-1,aie=ge(D(Iee,ae(Yi))),oie=w(e=>tie(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Yi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),St(r)&&(n?.propagateInterruption===!0?!aie(r.cause):!ut(r.cause))&&Ot(e.deferred,r))}))}),sie=function(){let e;return()=>(e===void 0&&(e=f(xt)),e)}(),cie=e=>()=>Ze(Dt(),t=>{let n=We(t);return(t,r)=>{if(e.state._tag===`Closed`)return sie();let i=n(t,r);return oie(e,i),i}}),Xi=e=>de(e.deferred),Zi=`~effect/socket/Socket`,Qi=vt(`effect/socket/Socket`),lie=`~effect/socket/Socket/CloseEvent`,uie=e=>Ye(e,lie),$i=`~effect/socket/Socket/SocketError`,die=e=>Ye(e,$i),ea=class extends Hn(`effect/socket/Socket/SocketReadError`)({_tag:un(`SocketReadError`),cause:jn}){message=`An error occurred during Read`},fie=class extends Hn(`effect/socket/Socket/SocketWriteError`)({_tag:un(`SocketWriteError`),cause:jn}){message=`An error occurred during Write`},ta=class extends Hn(`effect/socket/Socket/SocketOpenError`)({_tag:un(`SocketOpenError`),kind:Nn([`Unknown`,`Timeout`]),cause:jn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},na=class extends Hn(`effect/socket/Socket/SocketCloseError`)({_tag:un(`SocketCloseError`),code:Fn,closeReason:_n(j)}){static filterClean(e){return function(t){return ia.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?ite(t.reason):Lee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},ra=rr([ea,fie,ta,na]),ia=class extends Sne($i)(`SocketError`,{_tag:un(`SocketError`),reason:ra}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[$i]=$i;static is(e){return die(e)}message=this.reason.message},pie=e=>!0,mie=class extends vt()(`~effect/socket/Socket/WebSocket`){},aa=class extends vt()(`@effect/platform/Socket/WebSocketConstructor`){},hie=(e,t)=>aa.use(n=>gie(je((typeof e==`string`?rt(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>ft(()=>e.close(1e3))),t)),gie=(e,t)=>Nt(n=>{let i,a=pt(!1),o=n.context,s=t?.closeCodeIsError??pie,c=(n,c)=>Tee(Xe(function*(o){let l=yield*iie().pipe(te(o)),u=yield*te(e,o),d=yield*Oe(cie(l)(),mie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=Ct(ht(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return ct(t)?t:st});return d(t)}let t=n(e.data);ct(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),Ot(l.deferred,r(new ia({reason:f?new ea({cause:e}):new ta({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),Ot(l.deferred,r(new ia({reason:new na({code:t,closeReason:e.reason})})))}if(u.addEventListener(`close`,h,{once:!0}),u.addEventListener(`error`,m,{once:!0}),u.addEventListener(`message`,p),u.readyState!==1){let e=qe();u.addEventListener(`open`,()=>{f=!0,Ot(e,st)},{once:!0}),yield*de(e).pipe(jt({duration:t?.openTimeout??1e4,orElse:()=>r(new ia({reason:new ta({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),ee(Xi(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ue(Xi(l),na.filterClean(e=>!s(e)),()=>st)})).pipe(yt(e=>ot(o,e)),Je(ft(()=>{a.closeUnsafe(),i=void 0}))),l=new TextEncoder,u=(e,t)=>c(t=>typeof t==`string`?e(l.encode(t)):t instanceof Uint8Array?e(t):e(new Uint8Array(t)),t),d=rt(e=>a.whenOpen(ft(()=>{let t=i;uie(e)?t.close(e.code,e.reason):t.send(e)})));return rt(Qi.of({[Zi]:Zi,run:u,runRaw:c,writer:d}))}),oa=ie(hie,mt(Qi)),sa=class extends vt()(`effect/workers/Transferable/Collector`){},_ie=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return sa.of({addAllUnsafe:t,addAll:e=>ft(()=>t(e)),readUnsafe:n,read:ft(n),clearUnsafe:r,clear:ft(r)})},vie=`~effect/workers/WorkerError`,yie=class extends Hn(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:un(`WorkerSpawnError`),message:j,cause:_n(jn)}){},bie=class extends Hn(`effect/workers/WorkerError/WorkerSendError`)({_tag:un(`WorkerSendError`),message:j,cause:_n(jn)}){},xie=class extends Hn(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:un(`WorkerReceiveError`),message:j,cause:_n(jn)}){},Sie=class extends Hn(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:un(`WorkerUnknownError`),message:j,cause:_n(jn)}){},ca=rr([yie,bie,xie,Sie]);Hn(vie)({_tag:un(`WorkerError`),reason:ca});var la=`~effect/rpc/RpcClientError`,ua=class extends Hn(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:un(`RpcClientDefect`),message:j,cause:jn}){},da=class extends Hn(la)({_tag:un(`RpcClientError`),reason:rr([ca,ra,mne,ua])}){[la]=la;get message(){return`${this.reason._tag}: ${this.reason.message}`}},fa=e=>typeof e==`bigint`?e:BigInt(e),Cie={_tag:`Ping`},pa;try{pa=new TextDecoder}catch{}var I,ma,L=0,ha=[],ga=ha,_a=0,va={},ya,ba,xa=0,Sa=0,Ca,wa,Ta=[],Ea,Da={useRecords:!1,mapsAsObjects:!0},Oa=class{},ka=new Oa;ka.name=`MessagePack 0xC1`;var Aa=!1,ja=2,Ma,Na,Pa;try{Function(``)}catch{ja=1/0}var Fa=class e{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=0&&(e.structures=[],e.maxSharedStructures||=0)),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType=`number`)),Object.assign(this,e)}unpack(t,n){if(I)return io(()=>(ao(),this?this.unpack(t,n):e.prototype.unpack.call(Da,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(ma=n.end||t.length,L=n.start||0):(L=0,ma=n>-1?n:t.length),_a=0,Sa=0,ba=null,ga=ha,Ca=null,I=t;try{Ea=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){throw I=null,t instanceof Uint8Array?e:Error(`Source must be a Uint8Array or Buffer but was a `+(t&&typeof t==`object`?t.constructor.name:typeof t))}if(this instanceof e){if(va=this,this.structures)return ya=this.structures,Ia(n);(!ya||ya.length>0)&&(ya=[])}else va=Da,(!ya||ya.length>0)&&(ya=[]);return Ia(n)}unpackMultiple(e,t){let n,r=0;try{Aa=!0;let i=e.length,a=this?this.unpack(e,i):so.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(Ia(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(Ia());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Aa=!1,ao()}}_mergeStructures(e,t){Na&&(e=Na.call(this,e)),e||=[],Object.isFrozen(e)&&(e=e.map(e=>e.slice(0)));for(let t=0,n=e.length;t<n;t++){let n=e[t];n&&(n.isShared=!0,t>=32&&(n.highByte=t-32>>5))}e.sharedLength=e.length;for(let n in t||[])if(n>=0){let r=e[n],i=t[n];i&&(r&&((e.restoreStructures||(e.restoreStructures=[]))[n]=r),e[n]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function Ia(e){try{if(!va.trusted&&!Aa){let e=ya.sharedLength||0;e<ya.length&&(ya.length=e)}let t;if(va.randomAccessStructure&&I[L]<64&&I[L]>=32&&Ma?(t=Ma(I,L,ma,va),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=ma):t=Ra(),Ca&&=(L=Ca.postBundlePosition,null),Aa&&(ya.restoreStructures=null),L==ma)ya&&ya.restoreStructures&&La(),ya=null,I=null,wa&&=null;else if(L>ma)throw Error(`Unexpected end of MessagePack data`);else if(!Aa){let e;try{e=JSON.stringify(t,(e,t)=>typeof t==`bigint`?`${t}n`:t).slice(0,100)}catch(t){e=`(JSON view not available `+t+`)`}throw Error(`Data read, but end of buffer not reached `+e)}return t}catch(e){throw ya&&ya.restoreStructures&&La(),ao(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>ma)&&(e.incomplete=!0),e}}function La(){for(let e in ya.restoreStructures)ya[e]=ya.restoreStructures[e];ya.restoreStructures=null}function Ra(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=ya[e&63]||va.getStructures&&Va()[e&63];return t?(t.read||=za(t,e&63),t.read()):e}}else if(e<144){if(e-=128,va.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=$a();e===`__proto__`&&(e=`__proto_`),t[e]=Ra()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Ra(),Ra());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=Ra();return va.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Sa>=L)return ba.slice(L-xa,(L+=t)-xa);if(Sa==0&&ma<140){let e=t<16?Ja(t):qa(t);if(e!=null)return e}return Ha(t)}{let t;switch(e){case 192:return null;case 193:return Ca?(t=Ra(),t>0?Ca[1].slice(Ca.position1,Ca.position1+=t):Ca[0].slice(Ca.position0,Ca.position0-=t)):ka;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return Xa(t);case 197:return t=Ea.getUint16(L),L+=2,Xa(t);case 198:return t=Ea.getUint32(L),L+=4,Xa(t);case 199:return Za(I[L++]);case 200:return t=Ea.getUint16(L),L+=2,Za(t);case 201:return t=Ea.getUint32(L),L+=4,Za(t);case 202:if(t=Ea.getFloat32(L),va.useFloat32>2){let e=oo[(I[L]&127)<<1|I[L+1]>>7];return L+=4,(e*t+(t>0?.5:-.5)>>0)/e}return L+=4,t;case 203:return t=Ea.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=Ea.getUint16(L),L+=2,t;case 206:return t=Ea.getUint32(L),L+=4,t;case 207:return va.int64AsType===`number`?(t=Ea.getUint32(L)*4294967296,t+=Ea.getUint32(L+4)):va.int64AsType===`string`?t=Ea.getBigUint64(L).toString():va.int64AsType===`auto`?(t=Ea.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Ea.getBigUint64(L),L+=8,t;case 208:return Ea.getInt8(L++);case 209:return t=Ea.getInt16(L),L+=2,t;case 210:return t=Ea.getInt32(L),L+=4,t;case 211:return va.int64AsType===`number`?(t=Ea.getInt32(L)*4294967296,t+=Ea.getUint32(L+4)):va.int64AsType===`string`?t=Ea.getBigInt64(L).toString():va.int64AsType===`auto`?(t=Ea.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Ea.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return to(I[L++]&63);{let e=Ta[t];if(e)return e.read?(L++,e.read(Ra())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,to(I[L++]&63,I[L++])):Za(2);case 214:return Za(4);case 215:return Za(8);case 216:return Za(16);case 217:return t=I[L++],Sa>=L?ba.slice(L-xa,(L+=t)-xa):Tie(t);case 218:return t=Ea.getUint16(L),L+=2,Sa>=L?ba.slice(L-xa,(L+=t)-xa):Eie(t);case 219:return t=Ea.getUint32(L),L+=4,Sa>=L?ba.slice(L-xa,(L+=t)-xa):Die(t);case 220:return t=Ea.getUint16(L),L+=2,Wa(t);case 221:return t=Ea.getUint32(L),L+=4,Wa(t);case 222:return t=Ea.getUint16(L),L+=2,Ga(t);case 223:return t=Ea.getUint32(L),L+=4,Ga(t);default:if(e>=224)return e-256;if(e===void 0){let e=Error(`Unexpected end of MessagePack data`);throw e.incomplete=!0,e}throw Error(`Unknown MessagePack token `+e)}}}var wie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function za(e,t){function n(){if(n.count++>ja){let n=e.read=Function(`r`,`return function(){return `+(va.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:wie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(Ra);return e.highByte===0&&(e.read=Ba(t,e.read)),n()}let r={};for(let t=0,n=e.length;t<n;t++){let n=e[t];n===`__proto__`&&(n=`__proto_`),r[n]=Ra()}return va.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Ba(t,n):n}var Ba=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=ya[r]||Va()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=za(i,e),i.read()};function Va(){let e=io(()=>(I=null,va.getStructures()));return ya=va._mergeStructures(e,ya)}var Ha=Ua,Tie=Ua,Eie=Ua,Die=Ua;function Ua(e){let t;if(e<16&&(t=Ja(e)))return t;if(e>64&&pa)return pa.decode(I.subarray(L,L+=e));let n=L+e,r=[];for(t=``;L<n;){let e=I[L++];if(!(e&128))r.push(e);else if((e&224)==192){let t=I[L++]&63,n=(e&31)<<6|t;n<128?r.push(65533):r.push(n)}else if((e&240)==224){let t=I[L++]&63,n=I[L++]&63,i=(e&31)<<12|t<<6|n;i<2048||i>=55296&&i<=57343?r.push(65533):r.push(i)}else if((e&248)==240){let t=I[L++]&63,n=I[L++]&63,i=I[L++]&63,a=(e&7)<<18|t<<12|n<<6|i;a<65536||a>1114111?r.push(65533):a>65535?(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023,r.push(a)):r.push(a)}else r.push(65533);r.length>=4096&&(t+=Ka.apply(String,r),r.length=0)}return r.length>0&&(t+=Ka.apply(String,r)),t}function Wa(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Ra();return va.freezeData?Object.freeze(t):t}function Ga(e){if(va.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=$a();e===`__proto__`&&(e=`__proto_`),t[e]=Ra()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Ra(),Ra());return t}}var Ka=String.fromCharCode;function qa(e){let t=L,n=Array(e);for(let r=0;r<e;r++){let e=I[L++];if((e&128)>0){L=t;return}n[r]=e}return Ka.apply(String,n)}function Ja(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return Ka(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return Ka(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return Ka(t,n,r)}{let t=I[L++],n=I[L++],r=I[L++],i=I[L++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){L-=4;return}if(e<6){if(e===4)return Ka(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return Ka(t,n,r,i,e)}}if(e<8){let a=I[L++],o=I[L++];if((a&128)>0||(o&128)>0){L-=6;return}if(e<7)return Ka(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return Ka(t,n,r,i,a,o,s)}{let a=I[L++],o=I[L++],s=I[L++],c=I[L++];if((a&128)>0||(o&128)>0||(s&128)>0||(c&128)>0){L-=8;return}if(e<10){if(e===8)return Ka(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return Ka(t,n,r,i,a,o,s,c,e)}}if(e<12){let l=I[L++],u=I[L++];if((l&128)>0||(u&128)>0){L-=10;return}if(e<11)return Ka(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return Ka(t,n,r,i,a,o,s,c,l,u,d)}{let l=I[L++],u=I[L++],d=I[L++],f=I[L++];if((l&128)>0||(u&128)>0||(d&128)>0||(f&128)>0){L-=12;return}if(e<14){if(e===12)return Ka(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return Ka(t,n,r,i,a,o,s,c,l,u,d,f,e)}}{let p=I[L++],m=I[L++];if((p&128)>0||(m&128)>0){L-=14;return}if(e<15)return Ka(t,n,r,i,a,o,s,c,l,u,d,f,p,m);let h=I[L++];if((h&128)>0){L-=15;return}return Ka(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Ya(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=Ea.getUint16(L),L+=2;break;case 219:t=Ea.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Ua(t)}function Xa(e){return va.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function Za(e){let t=I[L++];if(Ta[t]){let n;return Ta[t](I.subarray(L,n=L+=e),e=>{L=e;try{return Ra()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var Qa=Array(4096);function $a(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Sa>=L)return ba.slice(L-xa,(L+=e)-xa);if(!(Sa==0&&ma<180))return Ha(e)}else return L--,eo(Ra());let t=(e<<5^(e>1?Ea.getUint16(L):e>0?I[L]:0))&4095,n=Qa[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=Ea.getUint32(r),a!=n[o++]){r=1879048192;break}r+=4}for(i+=3;r<i;)if(a=I[r++],a!=n[o++]){r=1879048192;break}if(r===i)return L=r,n.string;i-=3,r=L}for(n=[],Qa[t]=n,n.bytes=e;r<i;)a=Ea.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Ja(e):qa(e);return s==null?n.string=Ha(e):n.string=s}function eo(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(e==null)return e+``;if(va.allowArraysInMapKeys&&Array.isArray(e)&&e.flat().every(e=>[`string`,`number`,`boolean`,`bigint`].includes(typeof e)))return e.flat().toString();throw Error(`Invalid property type for record: ${typeof e}`)}var to=(e,t)=>{let n=Ra().map(eo),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=ya[e];return i&&(i.isShared||Aa)&&((ya.restoreStructures||(ya.restoreStructures=[]))[e]=i),ya[e]=n,n.read=za(n,r),n.read()};Ta[0]=()=>{},Ta[0].noBuffer=!0,Ta[66]=e=>{let t=e.byteLength%8||8,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r<t;r++)n<<=BigInt(8),n+=BigInt(e[r]);if(e.byteLength!==t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=(e,t)=>{let n=t-e;if(n<=40){let n=r.getBigUint64(e);for(let i=e+8;i<t;i+=8)n<<=64n,n|=r.getBigUint64(i);return n}let a=e+(n>>4<<3),o=i(e,a),s=i(a,t);return o<<BigInt((t-a)*8)|s};n=n<<BigInt((r.byteLength-t)*8)|i(t,r.byteLength)}return n};var no={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Ta[101]=()=>{let e=Ra();if(!no[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return no[e[0]](e[1],{cause:e[2]})},Ta[105]=e=>{if(va.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Ea.getUint32(L-4);wa||=new Map;let n=I[L],r;r=n>=144&&n<160||n==220||n==221?[]:n>=128&&n<144||n==222||n==223?new Map:(n>=199&&n<=201||n>=212&&n<=216)&&I[L+1]===115?new Set:{};let i={target:r};wa.set(t,i);let a=Ra();if(i.used)Object.assign(r,a);else return i.target=a;if(r instanceof Map)for(let[e,t]of a.entries())r.set(e,t);if(r instanceof Set)for(let e of Array.from(a))r.add(e);return r},Ta[112]=e=>{if(va.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Ea.getUint32(L-4),n=wa.get(t);return n.used=!0,n.target},Ta[115]=()=>new Set(Ra());var ro=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Oie=typeof globalThis==`object`?globalThis:window;Ta[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=ro[t];if(!r){if(t===16)return n;if(t===17)return new DataView(n);throw Error(`Could not find typed array for code `+t)}return new Oie[r](n)},Ta[120]=()=>{let e=Ra();return new RegExp(e[0],e[1])};var kie=[];Ta[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,Ca=kie,Ca=[Ya(),Ya()],Ca.position0=0,Ca.position1=0,Ca.postBundlePosition=L,L=n,Ra()},Ta[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date(`invalid`);function io(e){Pa&&Pa();let t=ma,n=L,r=_a,i=xa,a=Sa,o=ba,s=ga,c=wa,l=Ca,u=new Uint8Array(I.slice(0,ma)),d=ya,f=ya.slice(0,ya.length),p=va,m=Aa,h=e();return ma=t,L=n,_a=r,xa=i,Sa=a,ba=o,ga=s,wa=c,Ca=l,I=u,Aa=m,ya=d,ya.splice(0,ya.length,...f),va=p,Ea=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function ao(){I=null,wa=null,ya=null}var oo=Array(147);for(let e=0;e<256;e++)oo[e]=+(`1e`+Math.floor(45.15-e*.30103));var so=new Fa({useRecords:!1});so.unpack,so.unpackMultiple,so.unpack;var Aie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var co;try{co=new TextEncoder}catch{}var lo,uo,fo=typeof Buffer<`u`,po=fo?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,mo=fo?Buffer:Uint8Array,ho=fo?4294967296:2144337920,R,go,_o,z=0,vo,yo=null,jie,Mie=21760,Nie=/[\u0080-\uFFFF]/,bo=Symbol(`record-id`),Pie=class extends Fa{constructor(e){super(e),this.offset=0;let t,n,r,i,a=mo.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:co&&co.encodeInto?function(e,t){return co.encodeInto(e,R.subarray(t)).written}:!1,o=this;e||={};let s=e&&e.sequential,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(l??=c?32:0,l>8160)throw Error(`Maximum maxSharedStructure is 8160`);e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let u=e.maxOwnStructures;u??=c?32:64,!this.structures&&e.useRecords!=0&&(this.structures=[]);let d=l>32||u+l>64,f=l+64,p=l+u+64;if(p>8256)throw Error(`Maximum maxSharedStructure + maxOwnStructure is 8192`);let m=[],h=0,g=0;this.pack=this.encode=function(e,a){if(R||(R=new po(8192),_o=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),vo=R.length-10,vo-z<2048?(R=new po(R.length),_o=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),vo=R.length-10,z=0):z=z+7&2147483640,t=z,a&2048&&(z+=a&255),i=o.structuredClone?new Map:null,o.bundleStrings&&typeof e!=`string`?(yo=[],yo.size=1/0):yo=null,r=o.structures,r){r.uninitialized&&(r=o._mergeStructures(o.getStructures()));let e=r.sharedLength||0;if(e>l)throw Error(`Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to `+r.sharedLength);if(!r.transitions){r.transitions=Object.create(null);for(let t=0;t<e;t++){let e=r[t];if(!e)continue;let n,i=r.transitions;for(let t=0,r=e.length;t<r;t++){let r=e[t];n=i[r],n||=i[r]=Object.create(null),i=n}i[bo]=t+64}this.lastNamedStructuresLength=e}s||(r.nextId=e+64)}n&&=!1;let c;try{o.randomAccessStructure&&e&&typeof e==`object`?e.constructor===Object?D(e):e.constructor!==Map&&!Array.isArray(e)&&!uo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=yo;if(yo&&wo(t,y,0),i&&i.idsToInsert){let e=i.idsToInsert.sort((e,t)=>e.offset>t.offset?1:-1),r=e.length,a=-1;for(;n&&r>0;){let i=e[--r].offset+t;i<n.stringsPosition+t&&a===-1&&(a=0),i>n.position+t?a>=0&&(a+=6):(a>=0&&(_o.setUint32(n.position+t,_o.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&_o.setUint32(n.position+t,_o.getUint32(n.position+t)+a),z+=e.length*6,z>vo&&w(z),o.offset=z;let s=Fie(R.subarray(t,z),e);return i=null,s}return o.offset=z,a&512?(R.start=t,R.end=z,R):R.subarray(t,z)}catch(e){throw c=e,e}finally{if(r&&(_(),n&&o.saveStructures)){let n=r.sharedLength||0,i=R.subarray(t,z),s=Iie(r,o);if(!c)return o.saveStructures(s,s.isCompatible)===!1?o.pack(e,a):(o.lastNamedStructuresLength=n,R.length>1073741824&&(R=null),i)}R.length>1073741824&&(R=null),a&1024&&(z=t)}};let _=()=>{g<10&&g++;let e=r.sharedLength||0;if(r.length>e&&!s&&(r.length=e),h>1e4)r.transitions=null,g=0,h=0,m.length>0&&(m=[]);else if(m.length>0&&!s){for(let e=0,t=m.length;e<t;e++)m[e][bo]=0;m=[]}},v=e=>{var t=e.length;t<16?R[z++]=144|t:t<65536?(R[z++]=220,R[z++]=t>>8,R[z++]=t&255):(R[z++]=221,_o.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>vo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(yo&&n>=4&&n<4096){if((yo.size+=n)>Mie){let e,n=(yo[0]?yo[0].length*3+yo[1].length:0)+10;z+n>vo&&(R=w(z+n));let r;yo.position?(r=yo,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,wo(t,y,0),_o.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),yo=[``,``],yo.previous=r,yo.size=0,yo.position=e}let r=Nie.test(e);yo[+!r]+=e,R[z++]=193,y(r?-n:n);return}let i;i=n<32?1:n<256?2:n<65536?3:5;let o=n*3;if(z+o>vo&&(R=w(z+o)),n<64||!a){let t,a,o,s=z+i;for(t=0;t<n;t++)a=e.charCodeAt(t),a<128?R[s++]=a:a<2048?(R[s++]=a>>6|192,R[s++]=a&63|128):(a&64512)==55296&&((o=e.charCodeAt(t+1))&64512)==56320?(a=65536+((a&1023)<<10)+(o&1023),t++,R[s++]=a>>18|240,R[s++]=a>>12&63|128,R[s++]=a>>6&63|128,R[s++]=a&63|128):(R[s++]=a>>12|224,R[s++]=a>>6&63|128,R[s++]=a&63|128);r=s-z-i}else r=a(e,z+i);r<32?R[z++]=160|r:r<256?(i<2&&R.copyWithin(z+2,z+1,z+1+r),R[z++]=217,R[z++]=r):r<65536?(i<3&&R.copyWithin(z+3,z+2,z+2+r),R[z++]=218,R[z++]=r>>8,R[z++]=r&255):(i<5&&R.copyWithin(z+5,z+3,z+3+r),R[z++]=219,_o.setUint32(z,r),z+=4),z+=r}else if(n===`number`)if(e>>>0===e)e<32||e<128&&this.useRecords===!1||e<64&&!this.randomAccessStructure?R[z++]=e:e<256?(R[z++]=204,R[z++]=e):e<65536?(R[z++]=205,R[z++]=e>>8,R[z++]=e&255):(R[z++]=206,_o.setUint32(z,e),z+=4);else if(e>>0===e)e>=-32?R[z++]=256+e:e>=-128?(R[z++]=208,R[z++]=e+256):e>=-32768?(R[z++]=209,_o.setInt16(z,e),z+=2):(R[z++]=210,_o.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,_o.setFloat32(z,e);let n;if(t<4||(n=e*oo[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,_o.setFloat64(z,e),z+=8}else if(n===`object`||n===`function`)if(!e)R[z++]=192;else{if(i){let n=i.get(e);if(n){n.id||=(i.idsToInsert||(i.idsToInsert=[])).push(n),R[z++]=214,R[z++]=112,_o.setUint32(z,n.id),z+=4;return}i.set(e,{offset:z-t})}let a=e.constructor;if(a===Object)C(e);else if(a===Array)v(e);else if(a===Map)if(this.mapAsEmptyObject)R[z++]=128;else{r=e.size,r<16?R[z++]=128|r:r<65536?(R[z++]=222,R[z++]=r>>8,R[z++]=r&255):(R[z++]=223,_o.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=lo.length;t<n;t++){let n=uo[t];if(e instanceof n){let n=lo[t];if(n.write){n.type&&(R[z++]=212,R[z++]=n.type,R[z++]=0);let t=n.write.call(this,e);t===e?Array.isArray(e)?v(e):C(e):y(t);return}let r=R,i=_o,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>vo&&w(z),{target:R,targetView:_o,position:z-e}),y)}finally{r&&(R=r,_o=i,z=a,vo=R.length-10)}o&&(o.length+z>vo&&w(o.length+z),z=Co(o,R,z,n.type));return}}if(Array.isArray(e))v(e);else{if(e.toJSON){let t=e.toJSON();if(t!==e)return y(t)}if(n===`function`)return y(this.writeFunction&&this.writeFunction(e));C(e)}}}else if(n===`boolean`)R[z++]=e?195:194;else if(n===`bigint`){if(e<0x8000000000000000&&e>=-0x8000000000000000)R[z++]=211,_o.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,_o.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,_o.setFloat64(z,Number(e));else if(this.largeBigIntToString)return y(e.toString());else if(this.useBigIntExtension||this.moreTypes){let t=BigInt(e<0?-1:0),n;if(e>>BigInt(65536)===t){let r=BigInt(0x10000000000000000)-BigInt(1),i=[];for(;i.push(e&r),e>>BigInt(63)!==t;)e>>=BigInt(64);n=new Uint8Array(new BigUint64Array(i).buffer),n.reverse()}else{let t=e<0,r=(t?~e:e).toString(16);if(r.length%2?r=`0`+r:parseInt(r.charAt(0),16)>=8&&(r=`00`+r),fo)n=Buffer.from(r,`hex`);else{n=new Uint8Array(r.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(r.slice(e*2,e*2+2),16)}if(t)for(let e=0;e<n.length;e++)n[e]=~n[e]}n.length+z>vo&&w(n.length+z),z=Co(n,R,z,66);return}else throw RangeError(e+` was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string`);z+=8}else if(n===`undefined`)this.encodeUndefinedAsNil?R[z++]=192:(R[z++]=212,R[z++]=0,R[z++]=0);else throw Error(`Unknown type: `+n)},b=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?e=>{let t;if(this.skipValues){t=[];for(let n in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(n))&&!this.skipValues.includes(e[n])&&t.push(n)}else t=Object.keys(e);let n=t.length;n<16?R[z++]=128|n:n<65536?(R[z++]=222,R[z++]=n>>8,R[z++]=n&255):(R[z++]=223,_o.setUint32(z,n),z+=4);let r;if(this.coercibleKeyAsNumber)for(let i=0;i<n;i++){r=t[i];let n=Number(r);y(isNaN(n)?r:n),y(e[r])}else for(let i=0;i<n;i++)y(r=t[i]),y(e[r])}:e=>{R[z++]=222;let n=z-t;z+=2;let r=0;for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(y(t),y(e[t]),r++);if(r>65535)throw Error(`Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object`);R[n+++t]=r>>8,R[n+t]=r&255},x=this.useRecords===!1?b:e.progressiveRecords&&!d?e=>{let n,i=r.transitions||(r.transitions=Object.create(null)),a=z++-t,o;for(let s in e)if(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(s)){if(n=i[s],n)i=n;else{let c=Object.keys(e),l=i;i=r.transitions;let u=0;for(let e=0,t=c.length;e<t;e++){let t=c[e];n=i[t],n||(n=i[t]=Object.create(null),u++),i=n}a+t+1==z?(z--,T(i,c,u)):E(i,c,a,u),o=!0,i=l[s]}y(e[s])}if(!o){let n=i[bo];n?R[a+t]=n:E(i,Object.keys(e),a,0)}}:e=>{let t,n=r.transitions||(r.transitions=Object.create(null)),i=0;for(let r in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(r))&&(t=n[r],t||(t=n[r]=Object.create(null),i++),n=t);let a=n[bo];a?a>=96&&d?(R[z++]=((a-=96)&31)+96,R[z++]=a>>5):R[z++]=a:T(n,n.__keys__||Object.keys(e),i);for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&y(e[t])},S=typeof this.useRecords==`function`&&this.useRecords,C=S?e=>{S(e)?x(e):b(e)}:x,w=e=>{let n;if(e>16777216){if(e-t>ho)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(ho,Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096)*4096)}else n=(Math.max(e-t<<2,R.length-1)>>12)+1<<12;let r=new po(n);return _o=r.dataView||=new DataView(r.buffer,0,n),e=Math.min(e,R.length),R.copy?R.copy(r,0,t,e):r.set(R.slice(t,e)),z-=t,t=0,vo=r.length-10,R=r},T=(e,t,i)=>{let a=r.nextId;a||=64,a<f&&this.shouldShareStructure&&!this.shouldShareStructure(t)?(a=r.nextOwnId,a<p||(a=f),r.nextOwnId=a+1):(a>=p&&(a=f),r.nextId=a+1);let o=t.highByte=a>=96&&d?a-96>>5:-1;e[bo]=a,e.__keys__=t,r[a-64]=t,a<f?(t.isShared=!0,r.sharedLength=a-63,n=!0,o>=0?(R[z++]=(a&31)+96,R[z++]=o):R[z++]=a):(o>=0?(R[z++]=213,R[z++]=114,R[z++]=(a&31)+96,R[z++]=o):(R[z++]=212,R[z++]=114,R[z++]=a),i&&(h+=g*i),m.length>=u&&(m.shift()[bo]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=vo,c=t;R=go,z=0,t=0,R||(go=R=new po(8192)),vo=R.length-10,T(e,n,i),go=R;let l=z;if(R=a,z=o,vo=s,t=c,l>1){let e=z+l-1;e>vo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(go.slice(0,l),n),z=e}else R[r+t]=go[0]},D=e=>{let i=jie(e,R,t,z,r,w,(e,t,r)=>{if(r)return n=!0;z=t;let i=R;return y(e),_(),i===R?z:{position:z,targetView:_o,target:R}},this);if(i===0)return C(e);z=i}}useBuffer(e){R=e,R.dataView||(R.dataView=new DataView(R.buffer,R.byteOffset,R.byteLength)),_o=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};uo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Oa],lo=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:e,targetView:n,position:i}=t(6);e[i++]=214,e[i++]=255,n.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:n,targetView:i,position:a}=t(10);n[a++]=215,n[a++]=255,i.setUint32(a,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(a+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:e,targetView:r,position:i}=t(3);e[i++]=212,e[i++]=255,e[i++]=255}else{let{target:n,targetView:i,position:a}=t(15);n[a++]=199,n[a++]=12,n[a++]=255,i.setUint32(a,e.getMilliseconds()*1e6),i.setBigInt64(a+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:a}=t(this.moreTypes?3:0);this.moreTypes&&(i[a++]=212,i[a++]=115,i[a++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?xo(e,16,t):So(fo?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==mo&&this.moreTypes?xo(e,ro.indexOf(n.name),t):So(e,t)}},{pack(e,t){this.moreTypes?xo(e,17,t):So(fo?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function xo(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:a,position:o}=n(4+i);a[o++]=199,a[o++]=i+1}else if(i+1<65536){var{target:a,position:o}=n(5+i);a[o++]=200,a[o++]=i+1>>8,a[o++]=i+1&255}else{var{target:a,position:o,targetView:s}=n(7+i);a[o++]=201,s.setUint32(o,i+1),o+=4}a[o++]=116,a[o++]=t,e.buffer||(e=new Uint8Array(e)),a.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function So(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:a}=t(n+5);r[i++]=198,a.setUint32(i,n),i+=4}r.set(e,i)}function Co(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function Fie(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let t=n.offset,a=n.id;e.copyWithin(t+r,t,i),r-=6;let o=t+r;e[o++]=214,e[o++]=105,e[o++]=a>>24,e[o++]=a>>16&255,e[o++]=a>>8&255,e[o++]=a&255,i=t}return e}function wo(e,t,n){if(yo.length>0){_o.setUint32(yo.position+e,z+n-yo.position-e),yo.stringsPosition=z-e;let r=yo;yo=null,t(r[0]),t(r[1])}}function Iie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var To=new Pie({useRecords:!1});To.pack,To.pack;var{NEVER:Lie,ALWAYS:Rie,DECIMAL_ROUND:zie,DECIMAL_FIT:Bie}=Aie,Eo=class extends vt()(`effect/rpc/RpcSerialization`){},Vie=Eo.of({contentType:`application/json`,includesFraming:!1,makeUnsafe:()=>{let e=new TextDecoder;return{decode:t=>{let n=JSON.parse(typeof t==`string`?t:e.decode(t));return Array.isArray(n)?n:[n]},encode:e=>JSON.stringify(e)}}}),Do=he(Eo)(Vie),Hie=e=>kt(()=>{let t=new Set,n=new Map,r=new Map,i=(e,t)=>se(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),st});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return at(function*(){t.add(e),r.set(e,i);let a=n.get(e);if(a){n.delete(e);for(let[e,t]of a)yield*Te(kt(()=>i(e)),t)}return yield*iee(S,()=>(t.delete(e),r.delete(e),st))})}}))}),Uie=BigInt(0),Wie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Uie++),o=yield*Dt(),s=it(o,Me),c=new Map,l=!1;yield*gte(s,Nt(e=>(l=!0,d(Ree(e.id)))));let d=Xe(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?Pt(n.queue):Pe(n.queue,e.cause):n.resume(e)}),f=e=>{let r=Pte(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?ln(s.headers):Cn,l=s?.context??Pee();if(!r){let r=t=>m(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):lt(`${n}.${e._tag}`,{attributes:t.spanAttributes},r)}let u=h(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:dte(Ze(u,rte))}},m=(e,n,r,i,o,s,u)=>Nt(d=>{if(l)return xt;let f=a(),p=n(e=>t.onFromClient({message:e,context:s,discard:u}),{_tag:`Request`,id:f,tag:e._tag,payload:i,...r?{traceId:r.traceId,spanId:r.spanId,sampled:r.sampled}:{},headers:wn(d.getRef(Jie),o)});if(u)return p;let m;return _t(Re(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?Lt(r,{captureStackTrace:!1}):me,We(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),Rt(aee(m),_(f,Array.from(e),s))))}),h=Xe(function*(e,r,o,s,d,f){if(l)return yield*xt;let m=i?void 0:yield*hte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),h=Ce(),g=a(),v=Zee(h.context,Me);yield*u(v,e=>c.has(g)?(c.delete(g),_(g,St(e)?Array.from(Oee(e.cause)):[],f)):st);let y=yield*p(d);return c.set(g,{_tag:`Queue`,rpc:e,queue:y,scope:v,context:f}),yield*r(e=>t.onFromClient({message:e,context:f,discard:!1}),{_tag:`Request`,id:g,tag:e._tag,payload:o,...m?{traceId:m.traceId,spanId:m.spanId,sampled:m.sampled}:{},headers:wn(h.getRef(Jie),s)}).pipe(m?Lt(m,{captureStackTrace:!1}):me,Ge(e=>Pe(y,e)),dt,Mt(v,{startImmediately:!0})),y}),g=e=>{let t=[];for(let n of e.middlewares.values()){let e=o.mapUnsafe.get(`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},_=(e,n,r)=>Re(i=>{let a=Ce();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Nee(1e3),We(a.context)).addObserver(()=>{i(st)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?st:tee(i.queue,e.values).pipe(r?Ct(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):me,Ge(e=>Pe(i.queue,e)))}case`Exit`:{let t=e.requestId,n=c.get(t);return n?(c.delete(t),n._tag===`Effect`?(n.resume(e.exit),st):e.exit._tag===`Success`?Pt(n.queue):Pe(n.queue,e.exit.cause)):st}case`Defect`:return d(bee(e.defect));case`ClientEnd`:return st}},y;if(t.flatten){let t=new Map;y=function(n,r,i){let a=t.get(n);return a||(a=f(e.requests.get(n)),t.set(n,a)),a(r,i)}}else y={},e.requests.forEach(e=>{y[e._tag]=f(e)});return{client:y,write:v}}),Gie=0,Oo=Xe(function*(e,t){let n=Gie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*ko,s=new Map,{client:l,write:u}=yield*Wie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?_ie():void 0,l=Ce(),u={rpc:r,context:a?ote(l.context,sa,a):l.context,schemas:qie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Te(u.context),c,Ct(e=>i(n,{...t,id:String(t.id),payload:e,headers:Object.entries(t.headers)},a&&a.readUnsafe())))}case`Ack`:return s.get(t.requestId)?i(n,{_tag:`Ack`,requestId:String(t.requestId)}):st;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):st;case`Eof`:return st}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=fa(e.requestId),n=s.get(t);return!n||g(n.schemas.decodeChunk)?st:n.schemas.decodeChunk.value(e.values).pipe(Te(n.context),c,Ct(t=>u({_tag:`Chunk`,clientId:0,requestId:fa(e.requestId),values:t})),v(t=>u({_tag:`Exit`,clientId:0,requestId:fa(e.requestId),exit:Ae(t)})))}case`Exit`:{let t=fa(e.requestId),n=s.get(t);return n?(s.delete(t),n.schemas.decodeExit(e.exit).pipe(Te(n.context),c,Le({onSuccess:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:Ae(e)})}))):st}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Qie(e.defect)});case`ClientProtocolError`:{let t=wee(e.error);return At(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return st}}).pipe(Ge(cte),dt,tt),l}),Kie=new WeakMap,qie=e=>{let t=Kie.get(e);if(t!==void 0)return t;let n=Ute(e.successSchema);return t={decodeChunk:be(n,e=>rn(pn(gne(e.success)))),encodePayload:fne(pn(e.payloadSchema)),decodeExit:rn(pn(Hte(e)))},Kie.set(e,t),t},Jie=$e(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Cn}),ko=class extends vt()(`effect/rpc/RpcClient/Protocol`){static make=Hie},Ao=e=>ko.make(Xe(function*(t,n){let i=yield*Qi,a=yield*Eo,o=yield*see(Zie),s=new Map,u=yield*i.writer,d=a.makeUnsafe(),f=yield*Xie(u(d.encode(Cie))),p,m=kt(()=>(p=void 0,gt(o)?o.value.onConnect:st)),h=e=>At(n,n=>t(n,e));return yield*kt(()=>(d=a.makeUnsafe(),f.reset(),i.runRaw(e=>{try{let n=d.decode(e);if(n.length===0)return;let r=0;return Dee({while:()=>r<n.length,body:()=>{let e=n[r++];if(e._tag===`Pong`)return f.onPong(),st;if(`requestId`in e){let n=s.get(e.requestId);if(n!==void 0)return e._tag===`Exit`&&s.delete(e.requestId),t(n,e)}return h(e)},step:oee})}catch(e){return h({_tag:`ClientProtocolError`,error:new da({reason:new ua({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(ee(Ct(f.timeout,()=>r(new ia({reason:new ta({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(Ct(()=>r(new ia({reason:new na({code:1e3})}))),gt(o)?Je(o.value.onDisconnect):me,Xee(t=>{let n=Bee(t),r=ete(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?st:(p=new da({reason:r?n.success.reason:new ua({message:`Unknown socket error`,cause:Ie(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),_e(e?.retryPolicy??Yie),l({module:`RpcClient`,method:`makeProtocolSocket`}),tt),{send(e,t){if(p)return r(p);t._tag===`Request`&&s.set(t.id,e);let n=d.encode(t);return n===void 0?st:c(u(n))},supportsAck:!0,supportsTransferables:!1}})),Yie=h(500,1.5).pipe(uee(ree(5e3))),Xie=Xe(function*(e){let t=!0,n=0,r=pt();return yield*kt(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(xee(`5 seconds`),Et,et,dt,tt),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Zie=class extends vt()(`effect/rpc/RpcClient/ConnectionHooks`){},Qie=nr(jn);function jo(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function $ie(e){return e?.target.wsBaseUrl??null}function eae(e){return e?.target.httpBaseUrl??null}function tae(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function nae(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function rae(e){let t=nae(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function iae(e){let t=e.topology===`cmmd-cloud-runtime`;return{cmmd:!0,ownerBootstrapPromotion:e.topology!==`cloud-shell`&&!t,bearerBootstrap:!0,desktopBootstrap:e.topology===`desktop-local`,providerCredentialBroker:e.topology===`cmmd-control-plane`}}function aae(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function oae(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Mo(e){let t=e.capabilities,n=t.runtime??rae(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??iae(n),tools:t.tools??aae(n),projects:t.projects??oae(t,n)}}function sae(e){return e?Mo(e).projects.cloudProjects:!1}function cae(e){return e?Mo(e).runtime.workspaceProxy??!1:!1}function No(e,t){return{environmentId:e,projectId:t}}function Po(e,t){return{environmentId:e,threadId:t}}var Fo=`scoped:v1:`;function Io(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Fo)?`${Fo}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Lo(e){return Io(e)}function Ro(e){return Io(e)}function lae(e){let t=e.slice(10),n=t.indexOf(`:`);if(n<=0||n>=t.length-1||t.indexOf(`:`,n+1)!==-1)return null;try{let e=decodeURIComponent(t.slice(0,n)),r=decodeURIComponent(t.slice(n+1));return e.length>0&&r.length>0?{environmentId:e,localId:r}:null}catch{return null}}function zo(e){if(e.startsWith(Fo))return lae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Bo(e){let t=zo(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Vo(e){let t=zo(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var uae=1e3,dae=64e3;Oo(An);function fae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(uae*2**e),dae)}var Ho=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Uo(e){return Array.isArray(e)?e.map(Uo):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Uo(t)])):e}function pae(e){let t=JSON.stringify(Uo(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var mae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function hae(e){return e._tag===`Ping`?mae:null}function gae(e){if(e.policy===null||e.policy.method!==e.method)throw new Ho(`method_not_remotable`,`Relay method has no exact dispatch policy: ${e.method}`,!1);if(e.policy.requiredScope!==null&&!e.grantedScopes.includes(e.policy.requiredScope))throw new Ho(`scope_denied`,`Relay method ${e.method} requires scope ${e.policy.requiredScope}`,!1);return{requiredScope:e.policy.requiredScope,deliveryClass:e.policy.deliveryClass,journalPersistence:e.policy.journalPersistence}}function _ae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new Ho(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new Ho(`method_not_remotable`,`Relay dispatch policy targets an unregistered method: ${r.method}`,!1);if((r.deliveryClass===`idempotent-command`||r.deliveryClass===`create-command`)==(r.journalPersistence===`none`))throw new Ho(`method_not_remotable`,`Relay dispatch policy has incompatible journal persistence: ${r.method}`,!1);n.set(r.method,r)}for(let t of e.registeredMethods)if(!n.has(t))throw new Ho(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var vae=[{method:M.projectsSearchContents,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.projectsSearchEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.projectsListEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.serverDiscoverSourceControl,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.serverReportClientActivity,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.projectsWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.projectCheckoutDeletionPreview,requiredScope:`workspace.write`,deliveryClass:`read`},{method:M.projectCheckoutDeletionExecute,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.reviewGetDiffPreview,requiredScope:`diff.read`,deliveryClass:`read`},{method:M.projectsReadFile,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.cloudListRuntimes,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.filesystemBrowse,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.workspaceReadFile,requiredScope:`workspace.read`,deliveryClass:`bulk-transfer`},{method:M.workspaceBeginWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.workspaceWriteFileChunk,requiredScope:`workspace.write`,deliveryClass:`bulk-transfer`},{method:M.workspaceCommitWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.workspaceCancelWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.shellOpenInEditor,requiredScope:`shell.open`,deliveryClass:`idempotent-command`},{method:M.gitPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:M.gitRunStackedAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitListBranches,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsListRefs,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:M.vcsPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.vcsRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsCreateRef,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.vcsSwitchRef,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.vcsInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.gitRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitCreateBranch,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.gitCheckout,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.gitResolvePullRequest,requiredScope:`git.read`,deliveryClass:`read`},{method:M.gitPreparePullRequestThread,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.terminalOpen,requiredScope:`terminal.write`,deliveryClass:`create-command`},{method:M.terminalAttach,requiredScope:`terminal.write`,deliveryClass:`terminal-output`},{method:M.terminalWrite,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalResize,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalSignal,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalClear,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalRestart,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.terminalClose,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:M.browserOpenSession,requiredScope:`browser.control`,deliveryClass:`create-command`},{method:M.browserListSessions,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.browserCloseSession,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserGetSession,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.browserCommand,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserClearBrowsingData,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserAttachDisplay,requiredScope:`browser.read`,deliveryClass:`subscription`},{method:M.computerInput,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:M.browserAddDisplayIceCandidate,requiredScope:`browser.read`,deliveryClass:`browser-control`},{method:M.devTunnelRegister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:M.devTunnelUnregister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:M.devTunnelList,requiredScope:`browser.read`,deliveryClass:`read`},{method:M.threadDevRuntimeGet,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.threadDevRuntimeAllocatePort,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:M.threadDevRuntimeRelease,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:M.workspaceEnvironmentPreflight,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.workspaceEnsureScratch,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:M.serverGetConfig,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.serverRefreshProviders,requiredScope:`provider.read`,deliveryClass:`read`},{method:M.serverStartProviderAuth,requiredScope:`provider.manage`,deliveryClass:`create-command`},{method:M.serverRepairProviderAuthRuntime,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverDisconnectProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverGetProviderAuthSession,requiredScope:`provider.read`,deliveryClass:`read`},{method:M.serverCancelProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSubmitProviderAuthCode,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSyncPersonalCodexToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverSyncPersonalClaudeToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:M.serverUpsertKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverRemoveKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverGetSettings,requiredScope:`settings.read`,deliveryClass:`read`},{method:M.serverUpdateSettings,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverUpdateEnvironmentDisplayName,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:M.serverGetTraceDiagnostics,requiredScope:`settings.read`,deliveryClass:`read`},{method:M.serverHeartbeat,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.usageGetSummary,requiredScope:`runtime.read`,deliveryClass:`read`},{method:M.pullRequestsList,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsListStats,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsDetail,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsActivity,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsThreadComments,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsDiffFileContents,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsRunAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsUpdate,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsComment,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsUpdateComment,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsSubmitReview,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsReplyToThread,requiredScope:`git.write`,deliveryClass:`create-command`},{method:M.pullRequestsSetThreadResolution,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsSetReaction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.pullRequestsInvalidate,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsReviewerCandidates,requiredScope:`git.read`,deliveryClass:`read`},{method:M.pullRequestsRequestReviewers,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:M.subscribeGitStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:M.subscribeVcsStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:M.subscribeTerminalEvents,requiredScope:`terminal.read`,deliveryClass:`terminal-output`},{method:M.subscribeTerminalMetadata,requiredScope:`terminal.read`,deliveryClass:`read`},{method:M.subscribeBrowserEvents,requiredScope:`browser.read`,deliveryClass:`browser-frame`},{method:M.subscribeServerConfig,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:M.subscribeServerLifecycle,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:M.subscribeAuthAccess,requiredScope:`provider.read`,deliveryClass:`subscription`},{method:M.subscribeWorkspaceReadiness,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:Gn.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:Gn.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:Gn.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:Gn.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:Gn.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:Gn.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.getArchivedShellSnapshot,requiredScope:`thread.read`,deliveryClass:`read`},{method:Gn.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:Gn.getThreadDetailPage,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.assetsCreateUrl,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.attachmentsCreateUploadUrl,requiredScope:`turn.dispatch`,deliveryClass:`create-command`},{method:M.attachmentsDelete,requiredScope:`turn.dispatch`,deliveryClass:`idempotent-command`},{method:Gn.searchThreads,requiredScope:`thread.read`,deliveryClass:`read`},{method:M.providerUploadFeedback,requiredScope:`thread.read`,deliveryClass:`create-command`},{method:M.sourceControlLookupRepository,requiredScope:`git.read`,deliveryClass:`read`},{method:M.sourceControlCloneRepository,requiredScope:`project.write`,deliveryClass:`idempotent-command`}],yae=new Set([M.gitPull,M.gitRunStackedAction,M.gitCreateWorktree,M.gitRemoveWorktree,M.gitCreateBranch,M.gitCheckout,M.gitInit,M.gitPreparePullRequestThread,M.threadDevRuntimeAllocatePort,M.threadDevRuntimeRelease,M.serverUpsertKeybinding,M.serverRemoveKeybinding,M.serverUpdateEnvironmentDisplayName,Gn.dispatchCommand]),bae=vae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?yae.has(e.method)?`frame`:`metadata-only`:`none`}}),xae=_ae({registeredMethods:[...An.requests.keys()],policies:bae}),Wo={"project.create":{requiredScope:`project.write`,deliveryClass:`create-command`},"project.meta.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.script.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.delete":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"thread.create":{requiredScope:`thread.create`,deliveryClass:`create-command`},"thread.delete":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.archive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.settle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unsettle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unarchive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.meta.update":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.runtime-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.interaction-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.turn.start":{requiredScope:`turn.dispatch`,deliveryClass:`create-command`},"thread.turn.interrupt":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.user-input.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.checkpoint.revert":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.session.stop":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.plan-approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`}},Sae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function Cae(e){if(e.method!==Gn.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!Sae.has(t.type))return null;let n=t.type===`thread.plan-approval.respond`?t.promptId:t.requestId;if(typeof t.commandId!=`string`||t.commandId.length===0||typeof n!=`string`||n.length===0)throw new Ho(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Go(e){let t=xae.get(e.method)??null,n=gae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==Gn.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new Ho(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in Wo))throw new Ho(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=Wo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new Ho(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Ko=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},qo=class extends Ko{},Jo=class extends Ko{},Yo=class extends Ko{},wae=class extends Ko{},Tae=class extends Ko{},Eae=class extends Ko{},Dae=class extends Ko{},Oae=class extends Ko{},kae=class extends Ko{},Aae=class extends Ko{},Xo=class extends Ko{},Zo=jae(globalThis,{});function jae(e,t){return new Proxy(e,{get(n,r,i){return r in t?t[r]:e[r]},set(n,r,i){return r in t&&delete t[r],e[r]=i,!0},deleteProperty(n,r){let i=!1;return r in t&&(delete t[r],i=!0),r in e&&(delete e[r],i=!0),i},ownKeys(n){let r=Reflect.ownKeys(e),i=Reflect.ownKeys(t),a=new Set(i);return[...r.filter(e=>!a.has(e)),...i]},defineProperty(n,r,i){return r in t&&delete t[r],Reflect.defineProperty(e,r,i),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}async function Mae(){if(Zo!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e.subtle}catch(e){throw new Xo(e)}}var Qo=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await Mae())}},$o={Base:0,Psk:1,Auth:2,AuthPsk:3},Nae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},es={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},ts={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},ns=new Uint8Array,rs=0n,is=1n,as=2n,Pae=new Uint8Array([75,69,77,0,0]),os=new Uint8Array([72,80,75,69,45,118,49]);function ss(e){return new Uint8Array(cs(e))}function cs(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var Fae=class extends Qo{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:es.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:ns}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}init(e){this._suiteId=e}buildLabeledIkm(e,t){this._checkInit();let n=new Uint8Array(7+this._suiteId.byteLength+e.byteLength+t.byteLength);return n.set(os,0),n.set(this._suiteId,7),n.set(e,7+this._suiteId.byteLength),n.set(t,7+this._suiteId.byteLength+e.byteLength),n}buildLabeledInfo(e,t,n){this._checkInit();let r=new Uint8Array(9+this._suiteId.byteLength+e.byteLength+t.byteLength);return r.set(new Uint8Array([0,n]),0),r.set(os,2),r.set(this._suiteId,9),r.set(e,9+this._suiteId.byteLength),r.set(t,9+this._suiteId.byteLength+e.byteLength),r}async extract(e,t){await this._setup();let n=e.byteLength===0?new ArrayBuffer(this.hashSize):cs(e);if(n.byteLength!==this.hashSize)throw new qo(`The salt length must be the same as the hashSize`);let r=cs(t),i=await this._api.importKey(`raw`,n,this.algHash,!1,[`sign`]);return await this._api.sign(`HMAC`,i,r)}async expand(e,t,n){await this._setup();let r=cs(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=ns,c=ss(t),l=new Uint8Array(1);if(n>255*this.hashSize)throw Error(`Entropy limit reached`);let u=new Uint8Array(this.hashSize+c.length+1);for(let e=1,t=0;t<o.length;e++)l[0]=e,u.set(s,0),u.set(c,s.length),u.set(l,s.length+c.length),s=new Uint8Array(await this._api.sign(`HMAC`,i,u.slice(0,s.length+c.length+1))),o.length-t>=s.length?(o.set(s,t),t+=s.length):(o.set(s.slice(0,o.length-t),t),t+=o.length-t);return a}async extractAndExpand(e,t,n,r){await this._setup();let i=cs(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:cs(e),info:cs(n)},a,r*8)}async labeledExtract(e,t,n){return await this.extract(e,this.buildLabeledIkm(t,n))}async labeledExpand(e,t,n,r){return await this.expand(e,this.buildLabeledInfo(t,n,r),r)}_checkInit(){if(this._suiteId===ns)throw Error(`Not initialized. Call init()`)}},Iae=class extends Fae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:es.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}},ls=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function us(e,t){if(t<=0)throw Error(`i2Osp: too small size`);if(e>=256**t)throw Error(`i2Osp: too large integer`);let n=new Uint8Array(t);for(let r=0;r<t&&e;r++)n[t-(r+1)]=e%256,e=Math.floor(e/256);return n}function ds(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function fs(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function Lae(){if(Zo!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e}catch{throw Error(`failed to load Crypto`)}}function Rae(e,t){if(e.byteLength!==t.byteLength)throw Error(`xor: different length inputs`);let n=new Uint8Array(e.byteLength);for(let r=0;r<e.byteLength;r++)n[r]=e[r]^t[r];return n}var zae=new Uint8Array([101,97,101,95,112,114,107]),Bae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Vae(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(e,0),r.set(t,e.length),r.set(n,e.length+t.length),r}var Hae=class{constructor(e,t,n){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e,this._prim=t,this._kdf=n;let r=new Uint8Array(Pae);r.set(us(this.id,2),3),this._kdf.init(r)}async serializePublicKey(e){return await this._prim.serializePublicKey(e)}async deserializePublicKey(e){return await this._prim.deserializePublicKey(cs(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(cs(e))}async importKey(e,t,n=!0){return await this._prim.importKey(e,t,n)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(e){let t=cs(e);if(t.byteLength>8192)throw new qo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():ls(e.ekm)?e.ekm:await this.deriveKeyPair(e.ekm);let n=await this._prim.serializePublicKey(t.publicKey),r=await this._prim.serializePublicKey(e.recipientPublicKey);try{let i;if(e.senderKey===void 0)i=new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey));else{let n=ls(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=ds(new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey)),new Uint8Array(await this._prim.dh(n,e.recipientPublicKey)))}let a;if(e.senderKey===void 0)a=ds(new Uint8Array(n),new Uint8Array(r));else{let t=ls(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Vae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new wae(e)}}async decap(e){let t=cs(e.enc),n=await this._prim.deserializePublicKey(t),r=ls(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=ls(e.recipientKey)?e.recipientKey.publicKey:await this._prim.derivePublicKey(e.recipientKey),a=await this._prim.serializePublicKey(i);try{let i;i=e.senderPublicKey===void 0?new Uint8Array(await this._prim.dh(r,n)):ds(new Uint8Array(await this._prim.dh(r,n)),new Uint8Array(await this._prim.dh(r,e.senderPublicKey)));let o;if(e.senderPublicKey===void 0)o=ds(new Uint8Array(t),new Uint8Array(a));else{let n=await this._prim.serializePublicKey(e.senderPublicKey);o=new Uint8Array(t.byteLength+a.byteLength+n.byteLength),o.set(new Uint8Array(t),0),o.set(new Uint8Array(a),t.byteLength),o.set(new Uint8Array(n),t.byteLength+a.byteLength)}return await this._generateSharedSecret(i,o)}catch(e){throw new Tae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(zae,e),r=this._kdf.buildLabeledInfo(Bae,t,this.secretSize);return await this._kdf.extractAndExpand(ns,n,r,this.secretSize)}},ps=[`deriveBits`],Uae=new Uint8Array([100,107,112,95,112,114,107]),Wae=new Uint8Array([115,107]),ms=class{constructor(e,t,n,r=[]){Object.defineProperty(this,"key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extractable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"algorithm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.key=t,this.type=n,this.algorithm={name:e},this.usages=r,n===`public`&&(this.usages=[])}},Gae=class{constructor(e,t,n,r){Object.defineProperty(this,"_algName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_curve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._algName=e,this._nPk=t,this._nSk=t,this._curve=n,this._hkdf=r}serializePublicKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Jo(e))}}async deserializePublicKey(e){try{return await this._importRawKey(cs(e),!0)}catch(e){throw new Yo(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Jo(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(cs(e),!1)}catch(e){throw new Yo(e)}}async importKey(e,t,n){try{if(e===`raw`)return await this._importRawKey(t,n);if(t instanceof ArrayBuffer)throw Error(`Invalid jwk key format`);return await this._importJWK(t,n)}catch(e){throw new Yo(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new ms(this._algName,e,`private`,ps);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new Xo(e)}}async deriveKeyPair(e){try{let t=cs(e),n=await this._hkdf.labeledExtract(ns.buffer,Uae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Wae,ns,this._nSk),i=new ms(this._algName,new Uint8Array(r),`private`,ps);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Aae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new ms(this._algName,t,`public`))}catch(e){return Promise.reject(new Yo(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new Jo(e))}}_importRawKey(e,t){return new Promise((n,r)=>{t&&e.byteLength!==this._nPk&&r(Error(`Invalid length of the key`)),!t&&e.byteLength!==this._nSk&&r(Error(`Invalid length of the key`)),n(new ms(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:ps))})}_importJWK(e,t){return new Promise((n,r)=>{e.kty!==`OKP`&&r(Error(`Invalid kty: ${e.kty}`)),e.crv!==this._algName&&r(Error(`Invalid crv: ${e.crv}`)),t?(e.d!==void 0&&r(Error("Invalid key: `d` should not be set")),typeof e.x!=`string`&&r(Error("Invalid key: `x` not found")),n(new ms(this._algName,fs(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new ms(this._algName,fs(e.d),`private`,ps)))})}};function Kae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function hs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function gs(e,t,n=``){let r=Kae(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function _s(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function vs(e,t){gs(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function qae(e){if(typeof e==`bigint`){if(!ks(e))throw Error(`positive bigint expected, got `+e)}else hs(e);return e}function ys(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function bs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Jae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ss(e,t){return e<<32-t|e>>>t}var Cs=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Yae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Xae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Zae(e){if(gs(e),Cs)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Yae[e[n]];return t}var ws={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ts(e){if(e>=ws._0&&e<=ws._9)return e-ws._0;if(e>=ws.A&&e<=ws.F)return e-(ws.A-10);if(e>=ws.a&&e<=ws.f)return e-(ws.a-10)}function Qae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Cs)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=Ts(e.charCodeAt(i)),a=Ts(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function $ae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=rs;for(let n=0;n<e.length;n++){let r=Ts(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|Xae[r]}return t}function Es(e){hs(e,`numberToBigint`);let t=e,n=rs,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function Ds(e){return $ae(Zae(Os(gs(e)).reverse()))}function eoe(e,t){hs(t),e=qae(e);let n=Qae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function toe(e,t){return eoe(e,t).reverse()}function Os(e){return Uint8Array.from(e)}function ks(e){return typeof e==`bigint`&&0n<=e}function noe(e,t,n){return ks(e)&&ks(t)&&ks(n)&&t<=e&&e<n}function As(e,t,n,r){if(!noe(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function roe(e,t={},n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}let i=(e,t)=>Object.entries(e).forEach(([e,n])=>r(e,n,t));i(t,!1),i(n,!0)}async function ioe(e=32){let t=await Lae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function aoe(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function ooe(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);hs(e.outputLen),hs(e.blockLen)}function soe(e,t={}){let n=(t,n)=>e(n).update(t).digest(),r=e(void 0),i=Object.assign(n,{outputLen:r.outputLen,blockLen:r.blockLen,create:t=>e(t),...t});return Object.freeze(i)}var js=class{constructor(e,t){if(Object.defineProperty(this,"oHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),ooe(e),gs(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),bs(r)}update(e){return _s(this),this.iHash.update(e),this}digestInto(e){_s(this),gs(e,this.outputLen,`output`),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ms=(e,t,n)=>new js(e,t).update(n).digest();Ms.create=(e,t)=>new js(e,t);function coe(e,t,n){return e&t^~e&n}function loe(e,t,n){return e&t^e&n^t&n}var uoe=class{constructor(e,t,n,r){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"padOffset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isLE",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"view",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=xs(this.buffer)}update(e){_s(this),gs(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=xs(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){_s(this),vs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,bs(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;n.setBigUint64(r-8,Es(this.length*8),i),this.process(n,0);let o=xs(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen must be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ns=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),doe=Uint32Array.from([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]),Ps=new Uint32Array(64),foe=class extends uoe{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Ps[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ps[e-15],n=Ps[e-2],r=Ss(t,7)^Ss(t,18)^t>>>3,i=Ss(n,17)^Ss(n,19)^n>>>10;Ps[e]=i+Ps[e-7]+r+Ps[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=Ss(o,6)^Ss(o,11)^Ss(o,25),u=l+t+coe(o,s,c)+doe[e]+Ps[e]|0,d=(Ss(n,2)^Ss(n,13)^Ss(n,22))+loe(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){bs(Ps)}destroy(){this.set(0,0,0,0,0,0,0,0),bs(this.buffer)}},poe=class extends foe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Ns[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Ns[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Ns[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Ns[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Ns[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Ns[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Ns[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Ns[7]|0})}},Fs=soe(()=>new poe,aoe(1));function Is(e,t){let n=e%t;return n>=0n?n:t+n}function Ls(e,t,n){let r=e;for(;t-->rs;)r*=r,r%=n;return r}function moe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function hoe(e){return roe(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function goe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=hoe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||ioe,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?as**254n:as**447n,p=f+(o?8n*as**251n-is:4n*as**445n-is)+is,m=e=>Is(e,t),h=g(u);function g(e){return toe(m(e),l)}function _(e){let t=Os(gs(e,l,`uCoordinate`));return o&&(t[31]&=127),m(Ds(t))}function v(e){return Ds(r(Os(gs(e,l,`scalar`))))}function y(e,t){let n=w(_(t),v(e));if(n===0n)throw Error(`invalid private or public key received`);return g(n)}function b(e){return y(e,h)}let x=b,S=y;function C(e,t,n){let r=m(e*(t-n));return t=m(t-r),n=m(n+r),{x_2:t,x_3:n}}function w(e,n){As(`u`,e,rs,t),As(`scalar`,n,f,p);let r=n,a=e,o=is,s=rs,l=e,u=is,h=rs;for(let e=c-1n;e>=rs;e--){let t=r>>e&is;h^=t,{x_2:o,x_3:l}=C(h,o,l),{x_2:s,x_3:u}=C(h,s,u),h=t;let n=o+s,i=m(n*n),c=o-s,f=m(c*c),p=i-f,g=l+u,_=l-u,v=m(_*n),y=m(g*c),b=v+y,x=v-y;l=m(b*b),u=m(a*m(x*x)),o=m(i*f),s=m(p*(i+m(d*p)))}({x_2:o,x_3:l}=C(h,o,l)),{x_2:s,x_3:u}=C(h,s,u);let g=i(s);return m(o*g)}let T={secretKey:l,publicKey:l,seed:l},E=async e=>(e===void 0&&(e=await s(l)),gs(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:moe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Rs(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var _oe=(e,t)=>{function n(n,...r){if(gs(n,void 0,`key`),!Jae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];gs(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&gs(r[1],void 0,`AAD`);let a=t(n,...r),o=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);gs(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,gs(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(gs(e),i&&e.length<i)throw Error(`"ciphertext" expected length bigger than tagLength=`+i);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(n,e),n};function voe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function yoe(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function zs(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error(`"output" expected Uint8Array of length `+e+`, got: `+t.length);if(n&&!xoe(t))throw Error(`invalid output, must be aligned`);return t}function boe(e,t,n){Rs(n);let r=new Uint8Array(16),i=xs(r);return i.setBigUint64(0,Es(t),n),i.setBigUint64(8,Es(e),n),r}function xoe(e){return e.byteOffset%4==0}var Bs=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),Soe=Bs(`expand 16-byte k`),Coe=Bs(`expand 32-byte k`),woe=ys(Soe),Toe=ys(Coe);function Vs(e,t){return e<<t|e>>>32-t}function Hs(e){return e.byteOffset%4==0}var Us=64,Eoe=16,Ws=2**32-1,Gs=Uint32Array.of();function Doe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Us),u=ys(l),d=Hs(i)&&Hs(a),f=d?ys(i):Gs,p=d?ys(a):Gs;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Ws)throw Error(`arx: counter overflow`);let h=Math.min(Us,c-m);if(d&&h===Us){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Eoe;t++)n=e+t,p[n]=f[n]^u[t];m+=Us;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function Ooe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=voe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return hs(i),hs(o),Rs(a),Rs(n),(t,s,c,l,u=0)=>{gs(t,void 0,`key`),gs(s,void 0,`nonce`),gs(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),gs(l,void 0,`output`),hs(u),u<0||u>=Ws)throw Error(`arx: counter overflow`);if(l.length<d)throw Error(`arx: output (${l.length}) is shorter than data (${d})`);let f=[],p=t.length,m,h;if(p===32)f.push(m=Os(t)),h=Toe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=woe,f.push(m);else throw gs(t,32,`arx key`),Error(`invalid key size`);Hs(s)||f.push(s=Os(s));let g=ys(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,ys(s.subarray(0,16)),g),s=s.subarray(16)}let _=16-i;if(_!==s.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let v=ys(s);return Doe(e,h,g,v,c,l,u,o),bs(...f),l}}function Ks(e,t){return e[t++]&255|(e[t++]&255)<<8}var koe=class{constructor(e){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:new Uint8Array(16)}),Object.defineProperty(this,"r",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"h",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"pad",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(8)}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e=Os(gs(e,32,`key`));let t=Ks(e,0),n=Ks(e,2),r=Ks(e,4),i=Ks(e,6),a=Ks(e,8),o=Ks(e,10),s=Ks(e,12),c=Ks(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Ks(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=Ks(e,t+0),_=Ks(e,t+2),v=Ks(e,t+4),y=Ks(e,t+6),b=Ks(e,t+8),x=Ks(e,t+10),S=Ks(e,t+12),C=Ks(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),ee=i[4]+((y>>>4|b<<12)&8191),te=i[5]+(b>>>1&8191),ne=i[6]+((b>>>14|x<<2)&8191),O=i[7]+((x>>>11|S<<5)&8191),k=i[8]+((S>>>8|C<<8)&8191),re=i[9]+(C>>>5|r),A=0,ie=A+w*o+5*h*T+5*m*E+5*p*D+5*f*ee;A=ie>>>13,ie&=8191,ie+=5*d*te+5*u*ne+5*l*O+5*c*k+5*s*re,A+=ie>>>13,ie&=8191;let ae=A+w*s+T*o+5*h*E+5*m*D+5*p*ee;A=ae>>>13,ae&=8191,ae+=5*f*te+5*d*ne+5*u*O+5*l*k+5*c*re,A+=ae>>>13,ae&=8191;let oe=A+w*c+T*s+E*o+5*h*D+5*m*ee;A=oe>>>13,oe&=8191,oe+=5*p*te+5*f*ne+5*d*O+5*u*k+5*l*re,A+=oe>>>13,oe&=8191;let se=A+w*l+T*c+E*s+D*o+5*h*ee;A=se>>>13,se&=8191,se+=5*m*te+5*p*ne+5*f*O+5*d*k+5*u*re,A+=se>>>13,se&=8191;let ce=A+w*u+T*l+E*c+D*s+ee*o;A=ce>>>13,ce&=8191,ce+=5*h*te+5*m*ne+5*p*O+5*f*k+5*d*re,A+=ce>>>13,ce&=8191;let le=A+w*d+T*u+E*l+D*c+ee*s;A=le>>>13,le&=8191,le+=te*o+5*h*ne+5*m*O+5*p*k+5*f*re,A+=le>>>13,le&=8191;let ue=A+w*f+T*d+E*u+D*l+ee*c;A=ue>>>13,ue&=8191,ue+=te*s+ne*o+5*h*O+5*m*k+5*p*re,A+=ue>>>13,ue&=8191;let de=A+w*p+T*f+E*d+D*u+ee*l;A=de>>>13,de&=8191,de+=te*c+ne*s+O*o+5*h*k+5*m*re,A+=de>>>13,de&=8191;let fe=A+w*m+T*p+E*f+D*d+ee*u;A=fe>>>13,fe&=8191,fe+=te*l+ne*c+O*s+k*o+5*h*re,A+=fe>>>13,fe&=8191;let pe=A+w*h+T*m+E*p+D*f+ee*d;A=pe>>>13,pe&=8191,pe+=te*u+ne*l+O*c+k*s+re*o,A+=pe>>>13,pe&=8191,A=(A<<2)+A|0,A=A+ie|0,ie=A&8191,A>>>=13,ae+=A,i[0]=ie,i[1]=ae,i[2]=oe,i[3]=se,i[4]=ce,i[5]=le,i[6]=ue,i[7]=de,i[8]=fe,i[9]=pe}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;bs(n)}update(e){_s(this),gs(e),e=Os(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){bs(this.h,this.r,this.buffer,this.pad)}digestInto(e){_s(this),vs(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function Aoe(e){let t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}var joe=Aoe(e=>new koe(e));function Moe(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,ee=f,te=p,ne=m,O=h,k=g,re=_,A=v,ie=y,ae=b,oe=x;for(let e=0;e<a;e+=2)S=S+E|0,A=Vs(A^S,16),ne=ne+A|0,E=Vs(E^ne,12),S=S+E|0,A=Vs(A^S,8),ne=ne+A|0,E=Vs(E^ne,7),C=C+D|0,ie=Vs(ie^C,16),O=O+ie|0,D=Vs(D^O,12),C=C+D|0,ie=Vs(ie^C,8),O=O+ie|0,D=Vs(D^O,7),w=w+ee|0,ae=Vs(ae^w,16),k=k+ae|0,ee=Vs(ee^k,12),w=w+ee|0,ae=Vs(ae^w,8),k=k+ae|0,ee=Vs(ee^k,7),T=T+te|0,oe=Vs(oe^T,16),re=re+oe|0,te=Vs(te^re,12),T=T+te|0,oe=Vs(oe^T,8),re=re+oe|0,te=Vs(te^re,7),S=S+D|0,oe=Vs(oe^S,16),k=k+oe|0,D=Vs(D^k,12),S=S+D|0,oe=Vs(oe^S,8),k=k+oe|0,D=Vs(D^k,7),C=C+ee|0,A=Vs(A^C,16),re=re+A|0,ee=Vs(ee^re,12),C=C+ee|0,A=Vs(A^C,8),re=re+A|0,ee=Vs(ee^re,7),w=w+te|0,ie=Vs(ie^w,16),ne=ne+ie|0,te=Vs(te^ne,12),w=w+te|0,ie=Vs(ie^w,8),ne=ne+ie|0,te=Vs(te^ne,7),T=T+E|0,ae=Vs(ae^T,16),O=O+ae|0,E=Vs(E^O,12),T=T+E|0,ae=Vs(ae^T,8),O=O+ae|0,E=Vs(E^O,7);let se=0;r[se++]=o+S|0,r[se++]=s+C|0,r[se++]=c+w|0,r[se++]=l+T|0,r[se++]=u+E|0,r[se++]=d+D|0,r[se++]=f+ee|0,r[se++]=p+te|0,r[se++]=m+ne|0,r[se++]=h+O|0,r[se++]=g+k|0,r[se++]=_+re|0,r[se++]=v+A|0,r[se++]=y+ie|0,r[se++]=b+ae|0,r[se++]=x+oe|0}var Noe=Ooe(Moe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Poe=new Uint8Array(16),qs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Poe.subarray(n))},Foe=new Uint8Array(32);function Js(e,t,n,r,i){i!==void 0&&gs(i,void 0,`AAD`);let a=e(t,n,Foe),o=boe(r.length,i?i.length:0,!0),s=joe.create(a);i&&qs(s,i),qs(s,r),s.update(o);let c=s.digest();return bs(a,o),c}var Ys=_oe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=zs(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Js(e,t,n,s,r);return a.set(c,o),bs(c),a},decrypt(i,a){a=zs(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Js(e,t,n,o,r);if(!yoe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),bs(c),a}}))(Noe)),Ioe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(cs(e))}async seal(e,t,n){return await this._seal(cs(e),cs(t),cs(n))}async open(e,t,n){return await this._open(cs(e),cs(t),cs(n))}_seal(e,t,n){return new Promise(r=>{r(Ys(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(Ys(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},Loe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:ts.Chacha20Poly1305}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(e){return new Ioe(e)}};function Xs(){return new Promise((e,t)=>{t(new Xo(`Not supported`))})}var Roe=new Uint8Array([115,101,99]),Zs=class{constructor(e,t,n){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=e,this._kdf=t,this.exporterSecret=n}async seal(e,t){return await Xs()}async open(e,t){return await Xs()}async export(e,t){let n=cs(e);if(n.byteLength>8192)throw new qo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Roe,new Uint8Array(n),t)}catch(e){throw new Eae(e)}}},zoe=class extends Zs{},Boe=class extends Zs{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=r}},Qs=class extends Zs{constructor(e,t,n){if(super(e,t,n.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.key===void 0||n.baseNonce===void 0||n.seq===void 0)throw Error(`Required parameters are missing`);this._aead=n.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;let r=this._aead.createEncryptionContext(n.key);this._ctx={key:r,baseNonce:n.baseNonce,seq:n.seq}}computeNonce(e){let t=us(e.seq,e.baseNonce.byteLength);return Rae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new kae(`Message limit reached`);e.seq+=1}},Voe=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Hoe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},$s,ec=class{constructor(){$s.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Voe(this,$s,`f`);return Hoe(this,$s,t,`f`),await n,e}};$s=new WeakMap;var tc=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Uoe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},nc,Woe=class extends Qs{constructor(){super(...arguments),nc.set(this,void 0)}async open(e,t=ns.buffer){Uoe(this,nc,tc(this,nc,`f`)??new ec,`f`);let n=await tc(this,nc,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),cs(e),cs(t))}catch(e){throw new Oae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};nc=new WeakMap;var rc=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Goe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},ic,Koe=class extends Qs{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ic.set(this,void 0),this.enc=r}async seal(e,t=ns.buffer){Goe(this,ic,rc(this,ic,`f`)??new ec,`f`);let n=await rc(this,ic,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),cs(e),cs(t))}catch(e){throw new Dae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};ic=new WeakMap;var qoe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Joe=new Uint8Array([101,120,112]),Yoe=new Uint8Array([105,110,102,111,95,104,97,115,104]),Xoe=new Uint8Array([107,101,121]),Zoe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Qoe=new Uint8Array([115,101,99,114,101,116]),$oe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),ese=class extends Qo{constructor(e){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof e.kem==`number`)throw new qo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new qo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new qo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array($oe),this._suiteId.set(us(this._kem.id,2),4),this._suiteId.set(us(this._kdf.id,2),6),this._suiteId.set(us(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.encap(e),n;return n=e.psk===void 0?e.senderKey===void 0?$o.Base:$o.Auth:e.senderKey===void 0?$o.Psk:$o.AuthPsk,await this._keyScheduleS(n,t.sharedSecret,t.enc,e)}async createRecipientContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.decap(e),n;return n=e.psk===void 0?e.senderPublicKey===void 0?$o.Base:$o.Auth:e.senderPublicKey===void 0?$o.Psk:$o.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=ns.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=ns.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?ns:ss(n.psk.id),i=await this._kdf.labeledExtract(ns,Zoe,r),a=n.info===void 0?ns:ss(n.info),o=await this._kdf.labeledExtract(ns,Yoe,a),s=new Uint8Array(1+i.byteLength+o.byteLength);s.set(new Uint8Array([e]),0),s.set(new Uint8Array(i),1),s.set(new Uint8Array(o),1+i.byteLength);let c=n.psk===void 0?ns:ss(n.psk.key),l=this._kdf.buildLabeledIkm(Qoe,c),u=this._kdf.buildLabeledInfo(Joe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===ts.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(Xoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(qoe,s,this._aead.nonceSize),h=await this._kdf.extractAndExpand(t,l,m,this._aead.nonceSize);return{aead:this._aead,exporterSecret:d,key:p,baseNonce:new Uint8Array(h),seq:0}}async _keyScheduleS(e,t,n,r){let i=await this._keySchedule(e,t,r);return i.key===void 0?new Boe(this._api,this._kdf,i.exporterSecret,n):new Koe(this._api,this._kdf,i,n)}async _keyScheduleR(e,t,n){let r=await this._keySchedule(e,t,n);return r.key===void 0?new zoe(this._api,this._kdf,r.exporterSecret):new Woe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new qo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new qo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new qo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new qo(`Too long psk.id`)}}},tse=class extends ese{},nse=1n,ac=2n,rse=3n,ise=5n,oc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function ase(e){let t=10n,n=80n,r=oc,i=e*e%r*e%r,a=Ls(Ls(i,ac,r)*i%r,nse,r)*e%r,o=Ls(a,ise,r)*a%r,s=Ls(o,t,r)*o%r,c=Ls(s,20n,r)*s%r,l=Ls(c,40n,r)*c%r;return{pow_p_5_8:Ls(Ls(Ls(Ls(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,ac,r)*e%r,b2:i}}function ose(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var sse=(()=>{let e=oc;return goe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=ase(t);return Is(Ls(n,rse,e)*r,e)},adjustScalarBytes:ose})})(),cse=class extends Gae{constructor(e){super(`X25519`,32,sse,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new Jo(e))}}},sc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,lse=2**31,use=65536,dse=16,cc=32,lc=(1n<<255n)-19n,uc=new TextEncoder,dc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function fc(e){let t=0n;for(let n=0;n<e.length;n+=2)t|=BigInt(Number.parseInt(e.slice(n,n+2),16))<<BigInt(n/2*8);return t}var fse=new Set([0n,1n,fc(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),fc(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),lc-1n]),pse=new Uint8Array,pc=class extends Iae{async extract(e,t){return cs(Ms(Fs,e.byteLength===0?new Uint8Array(this.hashSize):ss(e),ss(t)))}async expand(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>255*this.hashSize)throw Error(`HKDF output length exceeds the RFC 5869 limit.`);let r=ss(e),i=ss(t),a=new Uint8Array(n),o=pse;for(let e=1,t=0;t<a.byteLength;e+=1){let n=_c([o,i,Uint8Array.of(e)]);o=new Uint8Array(Ms(Fs,r,n));let s=a.byteLength-t;a.set(o.subarray(0,Math.min(o.byteLength,s)),t),t+=Math.min(o.byteLength,s)}return cs(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},mc=new tse({kem:new class extends Hae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Nae.DhkemX25519HkdfSha256,new cse(e),e)}}(new pc),kdf:new pc,aead:new Loe}),hc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function gc(e){return new Uint8Array(e.slice(0))}function mse(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function _c(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}function vc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new hc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function yc(e){if(!Number.isSafeInteger(e)||e<0)throw new hc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function hse(e){return _c([vc(e.byteLength),e])}function bc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function gse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function xc(e){let t=``;for(let n=0;n<e.byteLength;n+=3){let r=e[n]??0,i=e[n+1]??0,a=e[n+2]??0,o=r<<16|i<<8|a;t+=dc[o>>>18&63],t+=dc[o>>>12&63],n+1<e.byteLength&&(t+=dc[o>>>6&63]),n+2<e.byteLength&&(t+=dc[o&63])}return t}function Sc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new hc(`channel_authentication_failed`,`Encrypted relay frame is not canonical base64url.`);let t=new Uint8Array(Math.floor(e.length*6/8)),n=0,r=0,i=0;for(let a of e){let e=dc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(xc(t)!==e)throw new hc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function _se(e){let t=new Uint8Array(e);t[31]=(t[31]??0)&127;let n=0n;for(let e=0;e<t.byteLength;e+=1)n|=BigInt(t[e]??0)<<BigInt(e*8);return fse.has(n%lc)}var vse={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new hc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return gc(await globalThis.crypto.subtle.digest(`SHA-256`,mse(e)))}},Cc={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new hc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function wc(e,t){let n=uc.encode(e).byteLength;if(n===0||n>256)throw new hc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function yse(e){let t=uc.encode(e).byteLength;if(t===0||t>65536)throw new hc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${use} UTF-8 bytes.`)}async function Tc(e,t=vse){yse(e.exactCompactTicket),wc(e.channelId,`Channel ID`),wc(e.runtimeId,`Runtime ID`),yc(e.connectionEpoch);let n=await t.sha256(uc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new hc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function bse(e){return xc(e.ticketDigest)}async function xse(e=Cc){let t=new Uint8Array(await e.randomBytes(cc));if(t.byteLength!==cc)throw new hc(`endpoint_key_invalid`,`The endpoint random source must return ${cc} bytes.`);try{return xc(t)}finally{t.fill(0)}}function Ec(e){return _c([uc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,bc(e.direction)])}function Dc(e){return _c([uc.encode(`forge-relay`),vc(4),e.binding.ticketDigest,uc.encode(e.binding.channelId),bc(e.binding.direction),gse(e.frameClass),yc(e.sequence),uc.encode(e.binding.runtimeId),yc(e.binding.connectionEpoch),vc(e.ciphertextLength)].map(hse))}async function Sse(e=Cc){let t=new Uint8Array(await e.randomBytes(cc));if(t.byteLength!==cc)throw new hc(`endpoint_key_invalid`,`The endpoint random source must return ${cc} bytes.`);try{return await mc.kem.deriveKeyPair(t)}catch(e){throw new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function Oc(e){try{return xc(gc(await mc.kem.serializePublicKey(e)))}catch(e){throw new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function Cse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new hc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function wse(e){try{let t=Sc(e);if(t.byteLength!==cc)throw Error(`Invalid endpoint key length.`);if(_se(t))throw new hc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await mc.kem.deserializePublicKey(t)}catch(e){throw e instanceof hc?e:new hc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var kc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Ac=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=lse||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new hc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function Tse(e,t){if(e.type!==`relay.encrypted-frame`||e.protocolVersion!==4||e.channelId!==t.channelId||e.direction!==t.direction||![`handshake`,`application`,`close`].includes(e.frameClass))throw new hc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var Ese=class{binding;context;encapsulatedKey;queue=new kc;budget=new Ac;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=xc(gc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new hc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+dse;this.budget.assertAvailable(t);let n=this.sequence,r=Dc({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=gc(await this.context.seal(e.plaintext,r))}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new hc(`channel_authentication_failed`,`Relay payload encryption returned an invalid ciphertext length.`);return this.sequence+=1,this.budget.commit(i.byteLength),{type:`relay.encrypted-frame`,protocolVersion:4,channelId:this.binding.channelId,direction:this.binding.direction,frameClass:e.frameClass,sequence:n,ciphertext:xc(i)}})}},Dse=class{binding;context;queue=new kc;budget=new Ac;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(Tse(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new hc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Sc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Dc({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=gc(await this.context.open(t,n))}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new hc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function Ose(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Cc).randomBytes(cc)),t.byteLength!==cc)throw Error(`The endpoint random source must return ${cc} bytes.`);let n=await mc.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:Ec(e.binding),ekm:t});return new Ese(e.binding,n)}catch(e){throw new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function kse(e){try{let t=await mc.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Sc(e.encapsulatedKey),info:Ec(e.binding)});return new Dse(e.binding,t)}catch(e){throw e instanceof hc?e:new hc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Ase=128,jse=2097152,Mse=864e5,jc=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Mc(e){return typeof e==`string`&&e.length>0}function Nc(e){return Mc(e)&&Number.isFinite(Date.parse(e))}function Nse(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function Pse(e){return Mc(e.transportRequestId)&&Mc(e.runtimeId)&&Mc(e.actorSessionId)&&Mc(e.durableRequestId)&&Mc(e.method)}function Fse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Ise(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Mc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function Lse(e){return!Nse(e.status)||e.errorCode!==null&&!Mc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Mc(e.errorCode):e.errorCode===null}function Rse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Pse(t)&&Fse(t)&&Ise(t)&&Lse(t)&&Nc(t.createdAt)&&Nc(t.updatedAt)}function zse(e){try{return JSON.parse(e)}catch{throw new jc(`Forge relay control journal is corrupt.`)}}function Bse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Mc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Rse)}function Vse(e){let t=new Set(e.map(Pc)),n=new Set(e.map(e=>e.durableRequestId)),r=new Set(e.map(e=>e.sequence));return t.size===e.length&&n.size===e.length&&r.size===e.length}function Hse(e){let t=zse(e);if(!Bse(t))throw new jc(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Vse(n)||t.nextSequence<=r)throw new jc(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Use(){return crypto.randomUUID()}function Pc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Fc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Wse(e,t){let n=e.filter(e=>e.runtimeId===t);if(n.length===0)return{state:`idle`,count:0};let r=n.reduce((e,t)=>Fc[t.status]>Fc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function Ic(e){let t=e.randomUUID??Use,n=e.now??(()=>new Date),r=e.maxRecords??Ase,i=e.maxBytes??jse,a=e.maxReplayAgeMs??Mse;if(r<1||i<1||a<1)throw new jc(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?Hse(o):{version:1,controlSessionId:t(),nextSequence:1,records:[]},l=new Map,u=new Set;function d(){return{controlSessionId:c.controlSessionId,records:[...c.records]}}function f(t){if(t.records.length>r)throw new jc(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new jc(`Forge relay control journal reached its storage limit.`);e.storage.write(n),c=t;let a=d();for(let e of u)e(a)}function p(e,t){return e.status!==`pending`&&e.status!==`retrying`?e:e.persistence===`metadata-only`||e.frame===null?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_COMMAND_OUTCOME_UNKNOWN`,updatedAt:t.toISOString()}:t.getTime()-Date.parse(e.createdAt)>a?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_RECOVERY_EXPIRED`,updatedAt:t.toISOString()}:e}let m=c.records.map(e=>p(e,s)),h=m.some((e,t)=>e!==c.records[t]);(o===null||h)&&f({...c,records:m});function g(e){let t=Pc(e);return{key:t,existing:c.records.find(e=>Pc(e)===t)??null}}function _(e,t,n){if([e.method===t.method,e.persistence===t.persistence,n===void 0||n===t.frame,e.frame===null||e.frame===t.frame,t.durableRequestId===void 0||e.durableRequestId===t.durableRequestId].includes(!1))throw new jc(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new jc(`Relay transport request ${t.transportRequestId} requires an explicit outcome acknowledgement.`)}function v(e){if(e.durableRequestId!==void 0&&c.records.some(t=>t.durableRequestId===e.durableRequestId))throw new jc(`Relay durable request ${e.durableRequestId} was reused by another transport request.`)}function y(e){let r=n().toISOString();return{runtimeId:e.runtimeId,actorSessionId:e.actorSessionId,transportRequestId:e.transportRequestId,durableRequestId:e.durableRequestId??t(),sequence:c.nextSequence,method:e.method,persistence:e.persistence,frame:e.persistence===`frame`?e.frame:null,status:`pending`,attemptCount:0,errorCode:null,createdAt:r,updatedAt:r}}function b(e){let{key:t,existing:n}=g(e);if(n!==null)return _(n,e,l.get(t)),l.set(t,e.frame),n;v(e);let r=y(e);return l.set(t,e.frame),f({...c,nextSequence:c.nextSequence+1,records:[...c.records,r]}),r}function x(e,t,n){let r=c.records.find(r=>r.runtimeId===e&&r.actorSessionId===t&&r.transportRequestId===n);if(!r)throw new jc(`Relay transport request ${n} is not journaled.`);return r}function S(e,t,r,i){x(e,t,r);let a=n().toISOString();l.delete(Pc({runtimeId:e,actorSessionId:t,transportRequestId:r})),f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?{...n,frame:null,status:`failed`,errorCode:i,updatedAt:a}:n)})}function C(e,t,r){let i=x(e,t,r);if(i.status===`failed`||i.status===`outcome-unknown`)throw new jc(`Relay transport request ${r} has no replayable outcome.`);let a={...i,status:i.attemptCount>0?`retrying`:`pending`,attemptCount:i.attemptCount+1,errorCode:null,updatedAt:n().toISOString()};return f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?a:n)}),a}function w(e,t,n){let r=c.records.filter(r=>r.runtimeId!==e||r.actorSessionId!==t||r.transportRequestId!==n);r.length!==c.records.length&&(l.delete(Pc({runtimeId:e,actorSessionId:t,transportRequestId:n})),f({...c,records:r}))}function T(e,t,n){let r=x(e,t,n);if(r.status!==`failed`&&r.status!==`outcome-unknown`)throw new jc(`Relay transport request ${n} does not have an acknowledgeable outcome.`);w(e,t,n)}function E(){let e=n(),t=c.records.map(t=>p(t,e));t.some((e,t)=>e!==c.records[t])&&f({...c,records:t})}function D(e,t){let r=n().toISOString(),i=c.records.map(n=>n.runtimeId!==e||n.actorSessionId===t||n.status!==`pending`&&n.status!==`retrying`?n:(l.delete(Pc(n)),{...n,frame:null,status:`outcome-unknown`,errorCode:`RELAY_ACTOR_SESSION_CHANGED`,updatedAt:r}));i.some((e,t)=>e!==c.records[t])&&f({...c,records:i})}return{controlSessionId:c.controlSessionId,prepare:b,records:()=>[...c.records],pending:()=>[...c.records],replayable:(e,t)=>(E(),c.records.filter(n=>n.runtimeId===e&&n.actorSessionId===t&&n.persistence===`frame`&&n.frame!==null&&(n.status===`pending`||n.status===`retrying`))),fenceActor:D,beginAttempt:C,markFailed:S,complete:w,acknowledge:T,subscribe:e=>(u.add(e),e(d()),()=>u.delete(e))}}function Gse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Kse=tn(pne),qse=gn(hne),Jse=gn(one),Yse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Lc(e,t){if(!Array.isArray(e))return null;for(let n of e)if(Array.isArray(n)&&n.length===2&&n[0]===t&&typeof n[1]==`string`)return n[1];return null}function Rc(e,t){let n=JSON.parse(e),r=hae(n);if(r!==null)return{messageType:`request`,...r};let i=Xse(n,t);if(i!==null)return i;let a=Zse(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function Xse(e,t){if(e._tag!==`Request`||typeof e.id!=`string`||e.id.length===0||typeof e.tag!=`string`||e.tag.length===0)return null;let n=Go({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Lc(e.headers,Qn.requestId)??e.id,method:e.tag,...n}}function Zse(e){return e._tag!==`Ack`&&e._tag!==`Interrupt`||typeof e.requestId!=`string`||e.requestId.length===0?null:{messageType:`acknowledgement`,requestId:e.requestId,correlationId:e.requestId,method:`@effect/rpc/${e._tag}`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`}}function zc(e,t){let n=new Event(`error`);return Object.defineProperties(n,{error:{value:Error(t),enumerable:!0},message:{value:`${e}: ${t}`,enumerable:!0}}),n}var Qse=new Set([`network`,`server`,`auth`,`permission`,`client`]),$se=new Set([`network`,`server`]);function ece(e){return e&&typeof e==`object`?e:{}}function tce(e){return typeof e.code==`string`&&e.code.length>0?e.code:typeof e.kind==`string`&&Qse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function nce(e){if(e.retryable===!0||typeof e.kind==`string`&&$se.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Bc(e){let t=ece(e);return{code:tce(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:nce(t)}}function Vc(e,t){let n=new Event(e.type),r=e;for(let e of t)r[e]!==void 0&&Object.defineProperty(n,e,{value:r[e],enumerable:!0});return n}function rce(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values(Qn).includes(e[0])}function Hc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function ice(e){if(!Array.isArray(e))return null;for(let t of e){let e=Hc(t);if(e?._tag!==`Fail`)continue;let n=Hc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function ace(e){let t=Hc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:ice(t.cause)??`RELAY_RPC_FAILED`}function Uc(e){if(typeof e!=`string`)return null;try{let t=Kse(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function oce(e,t){if(e.role===`control`&&e.protocolVersion===t&&e.protocolVersion>=1){if(e.protocolVersion===1)return null;if(e.actor!==void 0&&e.scopes!==void 0)return{runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch,protocolVersion:e.protocolVersion,actor:e.actor,scopes:e.scopes}}}function Wc(e,t,n){if(typeof e==`string`)try{let r=Hc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=ace(r);if(i===null){n.complete(t.runtimeId,t.actor.sessionId,r.requestId);return}n.markFailed(t.runtimeId,t.actor.sessionId,r.requestId,i)}catch{}}function sce(e){let t=Lc(e,Qn.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function cce(e){return{issuedAt:Lc(e,Qn.issuedAt)??new Date().toISOString(),expiresAt:Lc(e,Qn.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function lce(e){if(e!==2&&e!==3&&e!==4)throw new Ho(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function uce(e){let t=Cae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=dce(e.context);if(e.acquire===void 0)throw new Ho(`action_grant_required`,`CMMD action-grant issuance is unavailable for this remote response.`,!1);return e.acquire({...n,method:`orchestration.dispatchCommand`,...t,durableRequestId:e.identity.correlationId,payloadHash:e.payloadHash,requiredScope:`approval.respond`})}function dce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new Ho(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Gc(e.channelId),channelTicketDigest:Gc(e.channelTicketDigest),runtimeEndpointKeyId:Gc(e.runtimeEndpointKeyId),controlEndpointKeyId:Gc(e.controlEndpointKeyId)}}function Gc(e){if(typeof e==`string`&&e.length>0)return e;throw new Ho(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function fce(e){return e===void 0?{}:{sequence:e}}function Kc(e){return e===void 0?{}:{actionGrant:e}}async function pce(e){let t=Rc(e.data,e.context.scopes),n=JSON.parse(e.data),r=cce(n.headers),i=sce(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await uce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=lce(e.context.protocolVersion),c={messageType:t.messageType,requestId:t.requestId,correlationId:t.correlationId,method:t.method,requiredScope:t.requiredScope,deliveryClass:t.deliveryClass,runtimeId:e.context.runtimeId,connectionEpoch:e.context.connectionEpoch,actor:e.context.actor,...r,payloadHash:a,...fce(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Kc(o)}:{protocolVersion:4,...c,...Kc(o)}}function qc(e){return typeof e==`string`&&e.length>0}function mce(e){return[e.protocolVersion===4,qc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===sc,qc(e.channelId),qc(e.runtimeEndpointKeyId),qc(e.runtimeEndpointPublicKey),qc(e.controlEndpointKeyId),qc(e.controlEndpointPublicKey),qc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function Jc(e){if(!mce(e))throw new Ho(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function hce(e){if(await Oc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new Ho(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await wse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Tc({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Tc({exactCompactTicket:e.token,channelId:e.channelId,direction:`runtime-to-control`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider)]);return{controlToRuntimeBinding:n,runtimeToControlBinding:r,sender:await Ose({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function Yc(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function gce(e){return[e.confirmation.phase===e.expectedPhase,e.confirmation.channelId===e.route.channelId,e.confirmation.runtimeId===e.context.runtimeId,e.confirmation.connectionEpoch===e.context.connectionEpoch].every(Boolean)}function _ce(e){let{envelope:t}=e.application;return[t.runtimeId===e.context.runtimeId,t.connectionEpoch===e.context.connectionEpoch,t.actor.userId===e.context.actor.userId,t.actor.deviceId===e.context.actor.deviceId,t.actor.sessionId===e.context.actor.sessionId,t.payloadHash===e.payloadHash].every(Boolean)}async function vce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new Ho(`endpoint_key_invalid`,`The runtime attempted to replace its endpoint encapsulation.`,!1);return e.channel.recipient}if(e.message.sequence!==0||!e.message.encapsulatedKey)throw new Ho(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await kse({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var yce=class extends EventTarget{socket;route;relayCrypto;journal;lifecycle;acquireActionGrant;CONNECTING=WebSocket.CONNECTING;OPEN=WebSocket.OPEN;CLOSING=WebSocket.CLOSING;CLOSED=WebSocket.CLOSED;binaryType=`blob`;onopen=null;onclose=null;onerror=null;onmessage=null;authenticated=!1;context=null;payloadChannel=null;sendChain=Promise.resolve();constructor(e,t,n,r,i={},a){super(),this.socket=e,this.route=t,this.relayCrypto=n,this.journal=r,this.lifecycle=i,this.acquireActionGrant=a,e.addEventListener(`open`,()=>void this.beginAuthentication()),e.addEventListener(`message`,e=>void this.handleMessageSafely(e)),e.addEventListener(`error`,e=>{let t=Vc(e,[`error`,`message`]),n=typeof t.message==`string`?String(t.message):`Forge relay connection failed.`;this.lifecycle.onError?.({code:`RELAY_SOCKET_ERROR`,message:n}),this.emit(`error`,t)}),e.addEventListener(`close`,e=>{this.authenticated=!1,this.context=null,this.payloadChannel=null,this.lifecycle.onDisconnected?.({code:e.code,reason:e.reason}),this.emit(`close`,Vc(e,[`code`,`reason`,`wasClean`]))})}get bufferedAmount(){return this.socket.bufferedAmount}get extensions(){return this.socket.extensions}get protocol(){return this.socket.protocol}get readyState(){return this.authenticated?this.socket.readyState:WebSocket.CONNECTING}get url(){return this.route.relayWebSocketUrl}send(e){if(!this.authenticated||typeof e!=`string`)throw new DOMException(`Forge relay RPC socket is not open for text frames.`,`InvalidStateError`);if(this.route.protocolVersion===1){this.socket.send(JSON.stringify({type:`relay.frame`,payload:e}));return}let t=this.context;if(t===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);let n=Rc(e,t.scopes),r=n.messageType===`request`&&n.journalPersistence!==`none`?this.journal.prepare({runtimeId:t.runtimeId,actorSessionId:t.actor.sessionId,transportRequestId:n.requestId,...n.correlationId===n.requestId?{}:{durableRequestId:n.correlationId},method:n.method,frame:e,persistence:n.journalPersistence}):null;this.enqueueFrame(e,r)}enqueueFrame(e,t){this.sendChain=this.sendChain.then(()=>this.transmitFrame(e,t)).catch(e=>{let n=Bc(e);t!==null&&!n.retryable&&this.journal.markFailed(t.runtimeId,t.actorSessionId,t.transportRequestId,n.code),this.lifecycle.onError?.({code:n.code,message:n.message}),this.emit(`error`,zc(n.code,n.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${n.code}: ${n.message}`)})}async transmitFrame(e,t){let n=this.requireReadyContext(),r=await this.outboundFrame(e,t),i=await pce({data:r,context:n,crypto:this.relayCrypto,...this.acquireActionGrant?{acquireActionGrant:this.acquireActionGrant}:{}});if(n.protocolVersion===4){let e=await this.requirePayloadChannel().sender.seal({frameClass:`application`,plaintext:new TextEncoder().encode(JSON.stringify({payload:r,envelope:i}))});this.socket.send(JSON.stringify(e));return}this.socket.send(JSON.stringify({type:`relay.frame`,payload:r,envelope:i}))}requireReadyContext(){if(!this.authenticated||this.socket.readyState!==WebSocket.OPEN)throw new DOMException(`Forge relay RPC socket closed before send.`,`InvalidStateError`);if(this.context===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);return this.context}requirePayloadChannel(){let e=this.payloadChannel;if(e===null||e.phase!==`ready`)throw new Ho(`channel_confirmation_failed`,`The Forge relay endpoint channel is not confirmed.`,!1);return e}async outboundFrame(e,t){return t===null?e:this.withDurableHeaders(t,e)}async withDurableHeaders(e,t){let n=this.journal.beginAttempt(e.runtimeId,e.actorSessionId,e.transportRequestId),r=JSON.parse(t),i=await Oce({payload:Dce(e.method,r.payload),sequence:n.sequence,requestId:n.durableRequestId,issuedAt:new Date(n.updatedAt),crypto:this.relayCrypto}),a=Array.isArray(r.headers)?r.headers.filter(e=>!rce(e)):[];return JSON.stringify({...r,headers:[...a,...Object.entries(i)]})}close(e,t){this.socket.close(e,t)}asWebSocket(){return this}emit(e,t){this.dispatchEvent(t);let n=this[`on${e}`];n&&n.call(this.asWebSocket(),t)}async handleMessage(e){if(this.authenticated){if(this.context?.protocolVersion===4){await this.handleEncryptedApplicationMessage(e.data);return}this.context!==null&&Wc(e.data,this.context,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:e.data}));return}await this.handleAuthenticationMessage(e.data)}async handleMessageSafely(e){try{await this.handleMessage(e)}catch(e){let t=Bc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${t.code}: ${t.message}`)}}async beginAuthentication(){try{this.route.protocolVersion===4&&(this.payloadChannel=await hce(Jc(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Yse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Bc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Uc(e);if(t!==null){if(t.type===`relay.encrypted-frame`&&this.context?.protocolVersion===4){await this.handleEncryptedHandshakeMessage(t);return}if(t.type===`relay.error`){this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,zc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=oce(e,this.route.protocolVersion);if(t===void 0){this.socket.close(4400,`Forge relay authenticated the wrong role.`);return}if(t!==null&&t.protocolVersion===4){let n=Jc(this.route),r=this.payloadChannel;if(r===null||![e.runtimeId===n.runtimeId,e.connectionEpoch===n.connectionEpoch].every(Boolean)){this.socket.close(4400,`Forge relay authenticated stale endpoint metadata.`);return}t={...t,channelId:n.channelId,channelTicketDigest:bse(r.controlToRuntimeBinding),runtimeEndpointKeyId:n.runtimeEndpointKeyId,controlEndpointKeyId:n.controlEndpointKeyId},this.context=t;return}await this.activateAuthenticatedRelay(t)}async handleEncryptedHandshakeMessage(e){if(e.type!==`relay.encrypted-frame`)return;let t=this.payloadChannel,n=this.context,r=Jc(this.route);if(t===null||n===null||!Yc(e,r,`handshake`))throw new Ho(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await vce({channel:t,route:r,message:e})).open(e),a=qse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!gce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new Ho(`channel_confirmation_failed`,`The runtime endpoint confirmation does not match the CMMD route.`,!1);if(o===`runtime-hello`){let e=await t.sender.seal({frameClass:`handshake`,plaintext:new TextEncoder().encode(JSON.stringify({type:`relay.endpoint-confirmation`,protocolVersion:4,phase:`control-confirm`,channelId:r.channelId,runtimeId:n.runtimeId,connectionEpoch:n.connectionEpoch}))});t.phase=`awaiting-runtime-confirm`,this.socket.send(JSON.stringify(e));return}t.phase=`ready`,await this.activateAuthenticatedRelay(n)}async handleEncryptedApplicationMessage(e){let t=Uc(e);if(t?.type!==`relay.encrypted-frame`)throw new Ho(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!Yc(t,Jc(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new Ho(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Jse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!_ce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new Ho(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);Wc(i.payload,a,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:i.payload}))}async activateAuthenticatedRelay(e){this.context=e,this.authenticated=!0,this.lifecycle.onAuthenticated?.();let t=e===null?[]:this.replayForActor(e);for(let e of t)e.frame!==null&&this.enqueueFrame(e.frame,e);t.length>0&&await this.sendChain,this.emit(`open`,new Event(`open`))}replayForActor(e){return this.journal.fenceActor(e.runtimeId,e.actor.sessionId),this.journal.replayable(e.runtimeId,e.actor.sessionId)}};function bce(e,t,n=Xc,r=Ic({storage:Gse(),randomUUID:n.randomUUID}),i={},a){return new yce(e,t,n,r,i,a).asWebSocket()}var xce=Oo(Kn);async function Sce(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return btoa(String.fromCharCode(...new Uint8Array(n))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}var Xc={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:Sce},Zc=`forge-relay-binding=`,Cce=3e4;function wce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(Zc))throw Error(`Forge relay socket URL is missing its route binding.`);let n=decodeURIComponent(t.slice(20));if(n.length===0)throw Error(`Forge relay socket URL has an invalid route binding.`);return n}function Tce(e){let t=e.crypto??Xc,n=e.bindingTtlMs??Cce,r=e.createSocket??((e,t)=>new globalThis.WebSocket(e,t)),i=new Map;return{acquireSocketUrl:async()=>{let r=await e.acquireRoute(),a=t.randomUUID();if(i.has(a))throw Error(`Forge relay route binding identifier was reused.`);let o=new URL(r.relayWebSocketUrl);o.hash=`${Zc}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=wce(n),s=i.get(o);if(s===void 0)throw Error(`Forge relay route binding is missing, expired, or already consumed.`);return i.delete(o),clearTimeout(s.expires),e.lifecycle?.onConnecting?.(),bce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}var Qc=new Map;function Ece(e){let t=Qc.get(e);if(t!==void 0)return t;let n=Kn.requests.get(e);if(n===void 0)return null;let r=gn(n.payloadSchema);return Qc.set(e,r),r}function Dce(e,t){let n=Ece(e);if(n===null)return t;try{return n(t)}catch{return t}}async function Oce(e){let t=e.issuedAt??new Date,n=e.crypto??Xc;return{[Qn.requestId]:e.requestId??n.randomUUID(),[Qn.sequence]:String(e.sequence),[Qn.issuedAt]:t.toISOString(),[Qn.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[Qn.payloadHash]:await n.sha256Base64Url(pae(e.payload))}}function kce(e,t){return Qte(rne,({rpc:t,request:n,next:r})=>at(function*(){return Go({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function Ace(e,t=Xc){return xce.pipe(Se(kce(e,t)))}function jce(e){let t=e.crypto??Xc,n=Tce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=ht(n.acquireSocketUrl).pipe(c),i=he(aa,n.constructSocket),a=oa(r).pipe(E(i)),o=e.delayForRetry??fae,s=It(_(e.maxRetries??10),e=>rt(Ue(o(e)??0)));return mt(ko,Ao({retryPolicy:s,retryTransientErrors:!0})).pipe(E(De(a,Do)))}var $c=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Mce(e){let t=await Sse(e),n=await Oc(t.publicKey);return{keyPair:t,publicKey:n,keyId:Cse(`control`,n),channelNonce:await xse(e)}}function Nce(e){return{hpkeSuite:sc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function Pce(e){let t=e.route;if(t.protocolVersion!==4||t.hpkeSuite!==`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`||!t.channelId||!t.runtimeEndpointKeyId||!t.runtimeEndpointPublicKey||t.controlEndpointKeyId!==e.endpoint.keyId||t.controlEndpointPublicKey!==e.endpoint.publicKey||t.controlChannelNonce!==e.endpoint.channelNonce)throw new $c(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:sc,runtimeEndpointKeyId:t.runtimeEndpointKeyId,runtimeEndpointPublicKey:t.runtimeEndpointPublicKey,controlEndpointKeyId:e.endpoint.keyId,controlEndpointPublicKey:e.endpoint.publicKey,controlChannelNonce:e.endpoint.channelNonce,controlEndpointKeyPair:e.endpoint.keyPair,...e.digestProvider?{payloadDigestProvider:e.digestProvider}:{},...e.randomSource?{payloadRandomSource:e.randomSource}:{}}}var el=`~effect/ManagedRuntime`,tl=(e,t)=>{let n=t?.memoMap??eee(),r=gee(`parallel`),i=k(r,`sequential`),a={onFiberStart:pe(r)},s=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Nt(t=>(c||=f(Aee(o(e,n,i),e=>ft(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),Vee(ve(c)))),u={[el]:el,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?A(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return A(u.disposeEffect)},disposeEffect:kt(()=>(u.contextEffect=yee(`ManagedRuntime disposed`),u.cachedContext=void 0,He(u.scope,wt))),runFork(e,t){return u.cachedContext===void 0?f(nl(u,e),s(t)):We(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?cee(nl(u,e),s(t)):_te(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Qee(nl(u,e)):le(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?fe(nl(u,e)):See(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?pee(nl(u,e),s(t)):vee(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?A(nl(u,e),s(t)):ne(u.cachedContext)(e,s(t))}};return u};function nl(e,t){return Ct(e.contextEffect,e=>Te(t,e))}function rl(e,t=wne){return`${e}\0${t}`}function Fce(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=rl(e.threadId,e.terminalId);t.get(r)?.sessionEpoch!==e.sessionEpoch&&t.set(r,{sessionEpoch:e.sessionEpoch,nextControlSequence:1,tail:Promise.resolve(),pendingWriteBytes:0})},enqueue(r){if(n)return Promise.reject(Error(`Terminal control sequencer is disposed.`));let i=r.terminalId??`default`,a=t.get(rl(r.threadId,i));if(!a)return Promise.reject(Error(`Terminal must be opened before sending controls.`));let o=r.writeBytes??0;if(a.pendingWriteBytes+o>e.maxPendingWriteBytes)return Promise.reject(Error(`Terminal input queue is full while reconnecting.`));a.pendingWriteBytes+=o;let s=a.tail.then(async()=>{let t=a.nextControlSequence;await r.execute({sessionEpoch:a.sessionEpoch,controllerId:e.controllerId,controlSequence:t}),a.nextControlSequence=t+1});return a.tail=s.finally(()=>{a.pendingWriteBytes-=o}).catch(()=>void 0),s},remove(e,n){if(n){t.delete(rl(e,n));return}let r=`${e}\0`;for(let e of t.keys())e.startsWith(r)&&t.delete(e)},terminalIds(e){let n=`${e}\0`;return[...t.keys()].filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))},dispose(){n=!0,t.clear()}}}var il={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function al(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Ice(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?al(t.keyframe):null}function Lce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?il:t.streamGeneration>e.streamGeneration?al(t.keyframe):null}function Rce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return al(t.keyframe);if(t.sequence<=e.observedSequence)return il;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function zce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return il;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?il:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Bce(e,t){return Ice(e,t)??Lce(e,t)??Rce(e,t)??zce(e,t)}function Vce(e,t){let n=Bce(e,t);if(!n.observe)return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:e};let r=n.startsNewStream?t.sequence:Math.max(e.observedSequence,t.sequence),i={...e,observedSequence:r,gapCount:e.gapCount+n.missingFrameCount},a=n.accept?{...i,acceptedSequence:t.sequence,acceptedCapturedAt:t.capturedAt,...t.streamId?{streamId:t.streamId}:{},...t.streamGeneration===void 0?{}:{streamGeneration:t.streamGeneration}}:i;return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:a}}gn(sne);var ol=O(),sl=`Forge`,Hce=`Alpha`,cl=sl,ll=`0.13.4`,ul=Yt(`forge-app-top-bar drag-region @container/header-actions relative z-20 w-full min-w-0 shrink-0 bg-background`,`grid grid-cols-[minmax(0,1fr)_minmax(0,auto)] items-center`),dl=`flex h-full min-w-0 items-center gap-1 md:gap-1.5`,fl=`flex h-touch min-w-0 max-w-full touch-manipulation items-center justify-center rounded-lg px-3 text-foreground transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring md:h-7 md:px-2`,Uce={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`},Wce=`forge-app-shell flex w-full min-w-0 flex-row`,pl=`forge-app-shell flex w-full min-w-0 flex-col`,Gce=`flex min-h-0 min-w-0 flex-1 flex-col`,Kce=`relative flex h-[var(--forge-content-height)] min-h-0 min-w-0 flex-1 overflow-hidden`;function ml(e){let t=(0,ol.c)(19),{showStageBadge:n,tone:r,variant:i}=e,a=n!==void 0&&n,o=r===void 0?`default`:r,s=(i===void 0?`default`:i)===`auth`,c=s?20:16,l=s?`h-5 w-5 shrink-0`:`h-4 w-4 shrink-0`,u;t[0]!==c||t[1]!==l?(u=(0,Mr.jsx)(`img`,{className:l,src:`/forge-mark.svg`,width:c,height:c,alt:``,"aria-hidden":`true`}),t[0]=c,t[1]=l,t[2]=u):u=t[2];let d=u,f=s?`text-[15px] sm:text-base`:`text-sm`,p=o===`on-dark`?`text-primary-foreground`:`text-foreground`,m;t[3]!==f||t[4]!==p?(m=Yt(`truncate font-semibold tracking-tight`,f,p),t[3]=f,t[4]=p,t[5]=m):m=t[5];let h;t[6]===m?h=t[7]:(h=(0,Mr.jsx)(`span`,{className:m,children:sl}),t[6]=m,t[7]=h);let g=h,_=s?`rounded-full bg-muted/50 px-2 py-0.5 text-[9px] leading-none font-medium tracking-[0.14em] text-muted-foreground/70 uppercase [text-indent:0.14em]`:`rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] leading-none font-medium tracking-[0.18em] text-muted-foreground/60 uppercase [text-indent:0.18em]`,v;t[8]===_?v=t[9]:(v=(0,Mr.jsx)(`span`,{className:_,children:Hce}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Mr.jsxs)(`span`,{className:`flex items-center gap-2`,children:[d,g]}),t[10]=d,t[11]=g,t[12]=e):e=t[12];let n;return t[13]!==y||t[14]!==e?(n=(0,Mr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":cl,children:[e,y]}),t[13]=y,t[14]=e,t[15]=n):n=t[15],n}let b;return t[16]!==d||t[17]!==g?(b=(0,Mr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":cl,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function hl(e){let t=(0,ol.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Yt(`pointer-events-none flex select-none items-center`,n),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Mr.jsx)(ml,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Mr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}function qce(){let e=new Map;return{clear:()=>e.clear(),getItem:t=>e.get(t)??null,key:t=>Array.from(e.keys()).at(t)??null,get length(){return e.size},removeItem:t=>e.delete(t),setItem:(t,n)=>e.set(t,n)}}var gl=typeof window<`u`?window.localStorage:qce(),Jce=(e,t)=>nr(Rn(e))(t),Yce=(e,t)=>kte(Rn(e))(t),_l=(e,t)=>{let n=gl.getItem(e);return n?Jce(t,n):null},vl=(e,t,n)=>{let r=Yce(n,t);gl.setItem(e,r)},yl=e=>{gl.removeItem(e)},bl=`forge:local_storage_change`;function Xce(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(bl,{detail:{key:e}}))}function xl(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return _l(e,n)??t}catch(e){return console.error(`[LOCALSTORAGE] Error:`,e),t}}),a=(0,F.useCallback)(t=>{i(r=>{try{let i=typeof t==`function`?t(r):t;return i===null?yl(e):vl(e,i,n),queueMicrotask(()=>Xce(e)),i}catch(e){return console.error(`[LOCALSTORAGE] Error:`,e),r}})},[e,n]),o=(0,F.useRef)(e);return(0,F.useEffect)(()=>{if(o.current!==e){o.current=e;try{let r=_l(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=_l(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}},a=t=>{t.key===e&&r()},o=t=>{t.detail.key===e&&r()};return window.addEventListener(`storage`,a),window.addEventListener(bl,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(bl,o)}},[e,t,n]),[r,a]}var Sl=`cmmd-runtime:`;function Cl(e){return`${Sl}${e}`}var Zce=/^env_[0-9a-f]{32}$/,Qce=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,wl={shape:`local`,isCloud:!1,legacyRuntimeId:null},$ce={shape:`cloud-project-placeholder`,isCloud:!0,legacyRuntimeId:null},ele={shape:`durable-environment`,isCloud:!0,legacyRuntimeId:null};function Tl(e){if(typeof e!=`string`)return wl;if(e.startsWith(`cmmd-runtime:`)){let t=e.slice(Sl.length);return Qce.test(t)?{shape:`legacy-runtime`,isCloud:!0,legacyRuntimeId:t}:wl}return e.startsWith(`cmmd-cloud-project:`)?$ce:Zce.test(e)?ele:wl}var El=`forge:client-settings:v1`,tle=`forge:saved-environment-registry:v1`,nle=tr({environmentId:nn,label:j,httpBaseUrl:j,wsBaseUrl:j,createdAt:j,lastConnectedAt:Wn(j),cmmdOrganizationId:on(j),cmmdProjectId:on(j),runtimeId:on(j),runtimeTicketExpiresAt:on(j),lastAuthenticatedPullRequestCapability:on(Yn),bearerToken:on(j)}),Dl=tr({version:on(Fn),records:on(qn(nle))});function Ol(){return typeof window<`u`}var rle={uiFontSize:14,codeFontSize:15},ile=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function ale(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function ole(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(rle).filter(([t,n])=>e[t]===n);if(t.length===0)return null;let n={...e};for(let[e]of t)delete n[e];return n}function sle(e){let t=ile.flatMap(([t,n,r])=>{let i=e[t];if(typeof i!=`number`||!Number.isFinite(i))return[];let a=Math.min(r,Math.max(n,Math.round(i)));return a===i?[]:[[t,a]]});if(t.length===0)return null;let n={...e};for(let[e,r]of t)n[e]=r;return n}function kl(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[ale,ole,sle]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function cle(){if(!Ol())return null;try{let e=window.localStorage.getItem(El);return e?gn(er)(kl(JSON.parse(e))):null}catch{return null}}function lle(e){Ol()&&vl(El,e,er)}function Al(){if(!Ol())return{};try{return _l(`forge:saved-environment-registry:v1`,Dl)??{}}catch{return{}}}function jl(e){Ol()&&vl(tle,e,Dl)}function Ml(){return Al().records??[]}function ule(e){jl({version:1,records:e})}function dle(){return Ml().map(e=>Sn(e))}function fle(e){let t=new Map(Ml().map(e=>[e.environmentId,e]));ule(e.map(e=>{let n=Tl(e.environmentId).legacyRuntimeId===null?t.get(e.environmentId)?.bearerToken:void 0;return n?{...Sn(e),bearerToken:n}:Sn(e)}))}function ple(e){return Ml().find(t=>t.environmentId===e)?.bearerToken??null}function mle(e,t){let n=Al(),r=n.records??[],i=!1;return jl({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(Sn(n),{bearerToken:t})):n)}),i}function hle(e){let t=Al();jl({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?Sn(t):t)})}var gle=gn(er);function _le(){return typeof window>`u`?void 0:window.desktopBridge}function Nl(e){let t=_le(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function Pl(){let e=Nl(`getClientSettings`);if(e){let t=await e();return t?gle(t):null}return cle()}async function Fl(e){let t=Nl(`setClientSettings`);if(t)return t(e);lle(e)}async function Il(){let e=Nl(`getSavedEnvironmentRegistry`);return e?e():dle()}async function Ll(e){let t=Nl(`setSavedEnvironmentRegistry`);if(t)return t(e);fle(e)}async function Rl(e){let t=Nl(`getSavedEnvironmentSecret`);return t?t(e):ple(e)}async function zl(e,t){let n=Nl(`setSavedEnvironmentSecret`);return n?n(e,t):mle(e,t)}async function Bl(e){let t=Nl(`removeSavedEnvironmentSecret`);if(t)return t(e);hle(e)}var Vl=`token`;function Hl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Ul(e){let t=Hl(e).get(Vl)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Vl)?.trim()??``;return n.length>0?n:null}function vle(e){let t=new URL(e.toString()),n=Hl(t);return n.has(Vl)&&(n.delete(Vl),t.hash=n.toString()),t.searchParams.delete(Vl),t}function Wl(e,t){let n=new URL(e.toString());return n.searchParams.delete(Vl),n.hash=new URLSearchParams([[Vl,t]]).toString(),n}function yle(e,t){let n=new URL(e);return n.pathname=`/login`,Wl(n,t).toString()}function ble(e){return Wl(new URL(`/login`,window.location.href),e).toString()}var xle=`host`;function Sle(e){let t=new URL(e),n=Ul(t),r=new URL(`forge:///pair`);return r.searchParams.set(xle,t.origin),n&&r.searchParams.set(Vl,n),r.toString()}function Cle(e){return{_tag:`Value`,value:e}}function wle(e,t){return{_tag:`Record`,keys:e,value:t}}function Tle(e,t){return{_tag:`Array`,length:e,value:t}}Zt(`SourceError`);var Ele=$e(`effect/ConfigProvider`,{defaultValue:()=>kle()}),Dle={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Ole(e,t,n){let r=Object.create(Dle);return r.get=e,r.mapInput=t,r.prefix=n,r.load=r=>(t&&(r=t(r)),n&&(r=[...n,...r]),e(r)),r}function kle(e){let t=e?.env??{APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`3c1016247a3dd875ae36f6c99f417e28049ae9c7`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+3c1016247a3dd875ae36f6c99f417e28049ae9c7`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Ale(t);return Ole(e=>rt(Mle(n,t,e)))}function Ale(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e)i.children??={},i=i.children[t]??={};i.value=r}return t}var jle=/^(0|[1-9][0-9]*)$/;function Mle(e,t,n){let r=t[n.map(String).join(`_`)],i=Nle(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:Cle(r):a.every(e=>jle.test(e))?Tle(Math.max(...a.map(e=>parseInt(e,10)))+1,r):wle(new Set(a),r)}function Nle(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}var Gl=`~effect/Config`,Ple=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Fle={...Ke,...Cee,[Gl]:Gl,asEffect(){return Ct(Ele.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Ile(e){let t=Object.create(Fle);return t.parse=e,t}var Kl=Xe(function*(e,t){let n=yield*e.load(t);if(n!==void 0)switch(n._tag){case`Value`:return n.value;case`Record`:{if(n.value!==void 0)return n.value;let r={};for(let i of n.keys){let n=yield*Kl(e,[...t,i]);n!==void 0&&(r[i]=n)}return r}case`Array`:{if(n.value!==void 0)return n.value;let r=[];for(let i=0;i<n.length;i++)r.push(yield*Kl(e,[...t,i]));return r}}}),ql=Xe(function*(e,t,n){switch(e._tag){case`Objects`:{let r={};for(let i of e.propertySignatures){let e=i.name;if(typeof e==`string`){let a=yield*ql(i.type,t,[...n,e]);a!==void 0&&(r[e]=a)}}if(e.indexSignatures.length>0){let i=yield*t.load(n);if(i&&i._tag===`Record`)for(let a of e.indexSignatures){let e=Yte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*ql(a.type,t,[...n,o]);e!==void 0&&(r[o]=e)}}}return r}case`Arrays`:{let r=yield*t.load(n);if(r&&r._tag===`Value`)return r.value;let i=[];for(let r=0;r<e.elements.length;r++)i.push(yield*ql(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Kl(t,n);case`Suspend`:return yield*ql(e.thunk(),t,n);default:{let e=yield*t.load(n);return e===void 0?void 0:e._tag===`Value`||e._tag===`Record`&&e.value!==void 0||e._tag===`Array`&&e.value!==void 0?e.value:void 0}}});function Jl(e,t){let n=Gte(e),r=Ite(n),i=Zte(n.ast),a=typeof t==`string`?[t]:t??[];return Ile(e=>{let t=e.prefix?[...e.prefix,...a]:a;return ql(i,e,a).pipe(nte(e=>r(e).pipe(Ft(e=>new Ate(t.length>0?new Lte(t,e):e)))),Ft(e=>new Ple(e)))})}var Lle=(e,t,n)=>{let r=Pn(e,t),i=j.pipe(yn(Pn(j,j),Fte(n)),yn(r));return rr([r,i])},B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Yl=`10.74.0`;function Xl(){return Zl(V),V}function Zl(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.74.0`,t[Yl]=t[`10.74.0`]||{}}function Ql(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Yl]=r[`10.74.0`]||{};return i[e]||(i[e]=t())}var $l=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],Rle=`Sentry Logger `,eu={};function tu(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys(eu);r.forEach(e=>{let r=eu[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function zle(){iu().enabled=!0}function Ble(){iu().enabled=!1}function nu(){return iu().enabled}function Vle(...e){ru(`log`,...e)}function Hle(...e){ru(`warn`,...e)}function Ule(...e){ru(`error`,...e)}function ru(e,...t){B&&nu()&&tu(()=>{V.console[e](`${Rle}[${e}]:`,...t)})}function iu(){return B?Ql(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:zle,disable:Ble,isEnabled:nu,log:Vle,warn:Hle,error:Ule},au=50,ou=/\(error: (.*)\)/,su=/captureMessage|captureException/;function cu(...e){let t=e.sort((e,t)=>e[0]-t[0]).map(e=>e[1]);return(e,n=0,r=0)=>{let i=[],a=e.split(`
3
3
  `);for(let e=n;e<a.length;e++){let n=a[e];n.length>1024&&(n=n.slice(0,1024));let o=ou.test(n)?n.replace(ou,`$1`):n;if(!o.includes(`Error: `)){for(let e of t){let t=e(o);if(t){i.push(t);break}}if(i.length>=au+r)break}}return Gle(i.slice(r))}}function Wle(e){return Array.isArray(e)?cu(...e):e}function Gle(e){if(!e.length)return[];let t=Array.from(e);return/sentryWrapped/.test(lu(t).function||``)&&t.pop(),t.reverse(),su.test(lu(t).function||``)&&(t.pop(),su.test(lu(t).function||``)&&t.pop()),t.slice(0,au).map(e=>({...e,filename:e.filename||lu(t).filename,function:e.function||`?`}))}function lu(e){return e[e.length-1]||{}}var uu=`<anonymous>`;function du(e){try{return!e||typeof e!=`function`?uu:e.name||uu}catch{return uu}}function fu(e){let t=e.exception;if(t){let e=[];try{return t.values.forEach(t=>{t.stacktrace.frames&&e.push(...t.stacktrace.frames)}),e}catch{return}}}function Kle(e){let t=e?.startsWith(`file://`)?e.slice(7):e;return t?.match(/\/[A-Z]:/)&&(t=t.slice(1)),t}var pu={},mu={};function hu(e,t){return pu[e]=pu[e]||[],pu[e].push(t),()=>{let n=pu[e];if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}function gu(e,t){if(!mu[e]){mu[e]=!0;try{t()}catch(t){B&&H.error(`Error while instrumenting ${e}`,t)}}}function _u(e,t){let n=e&&pu[e];if(n)for(let r of n)try{r(t)}catch(t){B&&H.error(`Error while triggering instrumentation handler.
4
4
  Type: ${e}
5
5
  Name: ${du(r)}
@@ -1002,7 +1002,7 @@ or you can use record.mirror to access the mirror instance during recording.`,dV
1002
1002
  now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
1003
1003
  or you can use record.mirror to access the mirror instance during recording.`,TU={map:{},getId(){return console.error(wU),-1},getNode(){return console.error(wU),null},removeNodeFromMap(){console.error(wU)},has(){return console.error(wU),!1},reset(){console.error(wU)}};typeof window<`u`&&window.Proxy&&window.Reflect&&(TU=new Proxy(TU,{get(e,t,n){return t===`map`&&console.error(wU),Reflect.get(e,t,n)}}));function EU(e,t,n,r,i=window){let a=i.Object.getOwnPropertyDescriptor(e,t);return i.Object.defineProperty(e,t,r?n:{set(e){MU(()=>{n.set.call(this,e)},0),a&&a.set&&a.set.call(this,e)}}),()=>EU(e,t,a||{},!0)}function DU(e,t,n){try{if(!(t in e))return()=>{};let r=e[t],i=n(r);return typeof i==`function`&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=i,()=>{e[t]=r}}catch{return()=>{}}}Date.now().toString();function lGe(e){if(!e)return null;try{return e.nodeType===e.ELEMENT_NODE?e:e.parentElement}catch{return null}}function OU(e,t,n,r,i){if(!e)return!1;let a=lGe(e);if(!a)return!1;let o=CU(t,n);if(!i){let e=r&&a.matches(r);return o(a)&&!e}let s=SU(a,o),c=-1;return s<0?!1:(r&&(c=SU(a,CU(null,r))),s>-1&&c<0||s<c)}var kU={};function AU(e){let t=kU[e];if(t)return t;let n=window.document,r=window[e];if(n&&typeof n.createElement==`function`)try{let t=n.createElement(`iframe`);t.hidden=!0,n.head.appendChild(t);let i=t.contentWindow;i&&i[e]&&(r=i[e]),n.head.removeChild(t)}catch{}return kU[e]=r.bind(window)}function jU(...e){return AU(`requestAnimationFrame`)(...e)}function MU(...e){return AU(`setTimeout`)(...e)}var NU=(e=>(e[e[`2D`]=0]=`2D`,e[e.WebGL=1]=`WebGL`,e[e.WebGL2=2]=`WebGL2`,e))(NU||{}),PU;function uGe(e){PU=e}for(var FU=e=>PU?((...t)=>{try{return e(...t)}catch(e){if(PU&&PU(e)===!0)return()=>{};throw e}}):e,IU=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,dGe=typeof Uint8Array>`u`?[]:new Uint8Array(256),LU=0;LU<IU.length;LU++)dGe[IU.charCodeAt(LU)]=LU;var fGe=function(e){var t=new Uint8Array(e),n,r=t.length,i=``;for(n=0;n<r;n+=3)i+=IU[t[n]>>2],i+=IU[(t[n]&3)<<4|t[n+1]>>4],i+=IU[(t[n+1]&15)<<2|t[n+2]>>6],i+=IU[t[n+2]&63];return r%3==2?i=i.substring(0,i.length-1)+`=`:r%3==1&&(i=i.substring(0,i.length-2)+`==`),i},RU=new Map;function pGe(e,t){let n=RU.get(e);return n||(n=new Map,RU.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}var zU=(e,t,n)=>{if(!e||!(HU(e,t)||typeof e==`object`))return;let r=e.constructor.name,i=pGe(n,r),a=i.indexOf(e);return a===-1&&(a=i.length,i.push(e)),a};function BU(e,t,n){if(e instanceof Array)return e.map(e=>BU(e,t,n));if(e===null)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer)return{rr_type:e.constructor.name,base64:fGe(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[BU(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement){let t=e.constructor.name,{src:n}=e;return{rr_type:t,src:n}}return e instanceof HTMLCanvasElement?{rr_type:`HTMLImageElement`,src:e.toDataURL()}:e instanceof ImageData?{rr_type:e.constructor.name,args:[BU(e.data,t,n),e.width,e.height]}:HU(e,t)||typeof e==`object`?{rr_type:e.constructor.name,index:zU(e,t,n)}:e}var VU=(e,t,n)=>e.map(e=>BU(e,t,n)),HU=(e,t)=>!![`WebGLActiveInfo`,`WebGLBuffer`,`WebGLFramebuffer`,`WebGLProgram`,`WebGLRenderbuffer`,`WebGLShader`,`WebGLShaderPrecisionFormat`,`WebGLTexture`,`WebGLUniformLocation`,`WebGLVertexArrayObject`,`WebGLVertexArrayObjectOES`].filter(e=>typeof t[e]==`function`).find(n=>e instanceof t[n]);function mGe(e,t,n,r,i){let a=[],o=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(let s of o)try{if(typeof t.CanvasRenderingContext2D.prototype[s]!=`function`)continue;let o=DU(t.CanvasRenderingContext2D.prototype,s,function(a){return function(...o){return OU(this.canvas,n,r,i,!0)||MU(()=>{let n=VU(o,t,this);e(this.canvas,{type:NU[`2D`],property:s,args:n})},0),a.apply(this,o)}});a.push(o)}catch{let n=EU(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:NU[`2D`],property:s,args:[t],setter:!0})}});a.push(n)}return()=>{a.forEach(e=>e())}}function hGe(e){return e===`experimental-webgl`?`webgl`:e}function UU(e,t,n,r,i){let a=[];try{let o=DU(e.HTMLCanvasElement.prototype,`getContext`,function(e){return function(a,...o){if(!OU(this,t,n,r,!0)){let e=hGe(a);if(`__context`in this||(this.__context=e),i&&[`webgl`,`webgl2`].includes(e))if(o[0]&&typeof o[0]==`object`){let e=o[0];e.preserveDrawingBuffer||=!0}else o.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[a,...o])}});a.push(o)}catch{console.error(`failed to patch HTMLCanvasElement.prototype.getContext`)}return()=>{a.forEach(e=>e())}}function WU(e,t,n,r,i,a,o,s){let c=[],l=Object.getOwnPropertyNames(e);for(let o of l)if(![`isContextLost`,`canvas`,`drawingBufferWidth`,`drawingBufferHeight`].includes(o))try{if(typeof e[o]!=`function`)continue;let l=DU(e,o,function(e){return function(...c){let l=e.apply(this,c);if(zU(l,s,this),`tagName`in this.canvas&&!OU(this.canvas,r,i,a,!0)){let e=VU(c,s,this),r={type:t,property:o,args:e};n(this.canvas,r)}return l}});c.push(l)}catch{let r=EU(e,o,{set(e){n(this.canvas,{type:t,property:o,args:[e],setter:!0})}});c.push(r)}return c}function gGe(e,t,n,r,i,a){let o=[];return o.push(...WU(t.WebGLRenderingContext.prototype,NU.WebGL,e,n,r,i,a,t)),t.WebGL2RenderingContext!==void 0&&o.push(...WU(t.WebGL2RenderingContext.prototype,NU.WebGL2,e,n,r,i,a,t)),()=>{o.forEach(e=>e())}}var _Ge=`for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s="";for(a=0;a<r;a+=3)s+=e[n[a]>>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+"=":r%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+"-"+t;if("OffscreenCanvas"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext("2d");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return""}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext("bitmaprenderer"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:"low"});w?.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`;function vGe(){let e=new Blob([_Ge]);return URL.createObjectURL(e)}var yGe=class{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.shadowDoms=new Set,this.windowsSet=new WeakSet,this.windows=[],this.restoreHandlers=[],this.frozen=!1,this.locked=!1,this.snapshotInProgressMap=new Map,this.worker=null,this.lastSnapshotTime=0,this.processMutation=(e,t)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)};let{enableManualSnapshot:t,sampling:n=`all`,win:r,recordCanvas:i,errorHandler:a}=e;e.sampling=n,this.mutationCb=e.mutationCb,this.mirror=e.mirror,this.options=e,a&&uGe(a),(i&&typeof n==`number`||t)&&(this.worker=this.initFPSWorker()),this.addWindow(r),!t&&FU(()=>{i&&n===`all`&&(this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher()),i&&typeof n==`number`&&this.initCanvasFPSObserver()})()}reset(){this.pendingCanvasMutations.clear(),this.restoreHandlers.forEach(e=>{try{e()}catch{}}),this.restoreHandlers=[],this.windowsSet=new WeakSet,this.windows=[],this.shadowDoms=new Set,this.worker?.terminate(),this.worker=null,this.snapshotInProgressMap=new Map}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}addWindow(e){let{sampling:t=`all`,blockClass:n,blockSelector:r,unblockSelector:i,recordCanvas:a,enableManualSnapshot:o}=this.options;if(!this.windowsSet.has(e)){if(o){this.windowsSet.add(e),this.windows.push(new WeakRef(e));return}FU(()=>{if(a&&t===`all`&&this.initCanvasMutationObserver(e,n,r,i),a&&typeof t==`number`){let t=UU(e,n,r,i,!0);this.restoreHandlers.push(()=>{t()})}})(),this.windowsSet.add(e),this.windows.push(new WeakRef(e))}}addShadowRoot(e){this.shadowDoms.add(new WeakRef(e))}resetShadowRoots(){this.shadowDoms=new Set}snapshot(e,t){if(t?.skipRequestAnimationFrame){this.takeSnapshot(performance.now(),!0,e);return}jU(t=>this.takeSnapshot(t,!0,e))}initFPSWorker(){let e=new Worker(vGe());return e.onmessage=e=>{let t=e.data,{id:n}=t;if(this.snapshotInProgressMap.set(n,!1),!(`base64`in t))return;let{base64:r,type:i,width:a,height:o}=t;this.mutationCb({id:n,type:NU[`2D`],commands:[{property:`clearRect`,args:[0,0,a,o]},{property:`drawImage`,args:[{rr_type:`ImageBitmap`,args:[{rr_type:`Blob`,data:[{rr_type:`ArrayBuffer`,base64:r}],type:i}]},0,0,a,o]}]})},e}initCanvasFPSObserver(){let e;if(!this.windows.length&&!this.shadowDoms.size)return;let t=n=>{this.takeSnapshot(n,!1),e=jU(t)};e=jU(t),this.restoreHandlers.push(()=>{e&&cancelAnimationFrame(e)})}initCanvasMutationObserver(e,t,n,r){let i=UU(e,t,n,r,!1),a=mGe(this.processMutation.bind(this),e,t,n,r),o=gGe(this.processMutation.bind(this),e,t,n,r,this.mirror);this.restoreHandlers.push(()=>{i(),a(),o()})}getCanvasElements(e,t,n){let r=[],i=i=>{i.querySelectorAll(`canvas`).forEach(i=>{OU(i,e,t,n,!0)||r.push(i)})};for(let e of this.windows){let t=e.deref(),n;try{n=t&&t.document}catch{}n&&i(n)}for(let e of this.shadowDoms){let t=e.deref();t&&i(t)}return r}takeSnapshot(e,t,n){let{sampling:r,blockClass:i,blockSelector:a,unblockSelector:o,dataURLOptions:s,maxCanvasSize:c}=this.options,l=1e3/(r===`all`?2:r||2);return this.lastSnapshotTime&&e-this.lastSnapshotTime<l?!1:(this.lastSnapshotTime=e,(n?[n]:this.getCanvasElements(i,a,o)).forEach(e=>{let n=this.mirror.getId(e);if(!(!this.mirror.hasNode(e)||!e.width||!e.height||this.snapshotInProgressMap.get(n))){if(this.snapshotInProgressMap.set(n,!0),!t&&[`webgl`,`webgl2`].includes(e.__context)){let t=e.getContext(e.__context);t?.getContextAttributes()?.preserveDrawingBuffer===!1&&t.clear(t.COLOR_BUFFER_BIT)}createImageBitmap(e).then(t=>{this.worker?.postMessage({id:n,bitmap:t,width:e.width,height:e.height,dataURLOptions:s,maxCanvasSize:c},[t])}).catch(e=>{FU(()=>{throw this.snapshotInProgressMap.delete(n),e})()})}}),!0)}startPendingCanvasMutationFlusher(){jU(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){let e=t=>{this.rafStamps.latestId=t,jU(e)};jU(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{let n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),jU(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;let n=this.pendingCanvasMutations.get(e);if(!n||t===-1)return;let r=n.map(e=>{let{type:t,...n}=e;return n}),{type:i}=n[0];this.mutationCb({id:t,type:i,commands:r}),this.pendingCanvasMutations.delete(e)}};try{if(Array.from([1],e=>e*2)[0]!==2){let e=document.createElement(`iframe`);document.body.appendChild(e),Array.from=e.contentWindow?.Array.from||Array.from,document.body.removeChild(e)}}catch(e){console.debug(`Unable to override Array.from`,e)}sGe();var bGe;(function(e){e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`})(bGe||={});var GU={low:{sampling:{canvas:1},dataURLOptions:{type:`image/webp`,quality:.25}},medium:{sampling:{canvas:2},dataURLOptions:{type:`image/webp`,quality:.4}},high:{sampling:{canvas:4},dataURLOptions:{type:`image/webp`,quality:.5}}},xGe=`ReplayCanvas`,KU=1280,SGe=qM(((e={})=>{let[t,n]=e.maxCanvasSize||[],r={quality:e.quality||`medium`,enableManualSnapshot:e.enableManualSnapshot,maxCanvasSize:[t?Math.min(t,KU):KU,n?Math.min(n,KU):KU]},i,a,o=new Promise(e=>a=e);return{name:xGe,getOptions(){let{quality:e,enableManualSnapshot:t,maxCanvasSize:n}=r;return{enableManualSnapshot:t,recordCanvas:!0,getCanvasManager:e=>{let r=new yGe({...e,enableManualSnapshot:t,maxCanvasSize:n,errorHandler:e=>{try{typeof e==`object`&&(e.__rrweb__=!0)}catch{}}});return i=r,a(r),r},...GU[e]||GU.medium}},async snapshot(e,t){(i||await o).snapshot(e,t)}}}));function CGe(e){return e.split(`,`).some(e=>e.trim().startsWith(`sentry-`))}function qU(e){try{return new URL(e,Z.location.origin).href}catch{return}}function wGe(e){return e.entryType===`resource`&&`initiatorType`in e&&typeof e.nextHopProtocol==`string`&&(e.initiatorType===`fetch`||e.initiatorType===`xmlhttprequest`)}function JU(e){try{return new Headers(e)}catch{return}}var YU={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function XU(e,t){let{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:i,enableHTTPTimings:a,tracePropagationTargets:o,onRequestSpanStart:s,onRequestSpanEnd:c}={...YU,...t},l=typeof i==`function`?i:e=>!0,u=e=>EGe(e,o),d={},f=e.getOptions().propagateTraceparent;n&&_I(t=>{let n=ZNe(t,l,u,d,{propagateTraceparent:f,onRequestSpanEnd:c});if(n){let r=qU(t.fetchData.url),i=r?BN(r).host:void 0,o=r?HN(r):void 0;n.setAttributes({"http.url":o,"url.full":o,"server.address":i}),a&&ZU(n,e),s?.(n,{headers:t.headers})}}),r&&Bz(t=>{let n=DGe(t,l,u,d,f,c);n&&(a&&ZU(n,e),s?.(n,{headers:JU(t.xhr.__sentry_xhr_v3__?.request_headers)}))})}var TGe=300;function ZU(e,t){let{url:n}=JA(e).data;if(!n||typeof n!=`string`)return;let r=()=>void setTimeout(i);if(Rj(t)){let t=e.end.bind(e);e.end=e=>{let n=e??Lk(),a=!1,o=()=>{a||(a=!0,setTimeout(i),t(n),clearTimeout(s))};r=o;let s=setTimeout(o,TGe)}}let i=ez(`resource`,({entries:t})=>{t.forEach(t=>{wGe(t)&&t.name.endsWith(n)&&(e.setAttributes(_z(t)),r())})})}function EGe(e,t){let n=CI();if(n){let r,i;try{r=new URL(e,n),i=new URL(n).origin}catch{return!1}let a=r.origin===i;return t?Dk(r.toString(),t)||a&&Dk(r.pathname,t):a}{let n=!!e.match(/^\/(?!\/)/);return t?Dk(e,t):n}}function DGe(e,t,n,r,i,a){let o=e.xhr,s=o?.[zz];if(!o||o.__sentry_own_request__||!s)return;let{url:c,method:l}=s,u=mj()&&t(c);if(e.endTimestamp){let t=o.__sentry_xhr_span_id__;if(!t)return;let n=r[t];n&&(u&&s.status_code!==void 0&&(SA(n,s.status_code),n.end(),a?.(n,{headers:JU(Wz(o)),error:e.error})),delete r[t]);return}let d=qU(c),f=BN(d||c),p=d?HN(d):void 0,m=HN(VN(c)),h=X(),g=!!uj(),_=g||!!h&&Rj(h),v=u&&_?qj({name:`${l} ${m}`,attributes:{url:HN(c),type:`xhr`,"http.method":l,"http.url":p,"url.full":p,"server.address":f?.host,[mA]:`auto.http.browser`,[pA]:`http.client`,...f?.search&&{"http.query":f?.search},...f?.hash&&{"http.fragment":f?.hash}}}):new vj,y=iM(v)&&g?void 0:v;return u&&!_&&h?.recordDroppedEvent(`no_parent_span`,`span`),o.__sentry_xhr_span_id__=v.spanContext().spanId,r[o.__sentry_xhr_span_id__]=v,n(c)&&OGe(o,mj()&&_?y:void 0,i),h&&h.emit(`beforeOutgoingRequestSpan`,v,e),v}function OGe(e,t,n){let{"sentry-trace":r,baggage:i,traceparent:a}=KN({span:t,propagateTraceparent:n});r&&kGe(e,r,i,a)}function kGe(e,t,n,r){let i=e.__sentry_xhr_v3__?.request_headers;if(!(i?.[`sentry-trace`]||!e.setRequestHeader))try{if(e.setRequestHeader(`sentry-trace`,t),r&&!i?.traceparent&&e.setRequestHeader(`traceparent`,r),n){let t=i?.baggage;(!t||!CGe(t))&&e.setRequestHeader(`baggage`,n)}}catch{}}var QU=new WeakMap,$U=new WeakMap,AGe=9e4,jGe=[`text/event-stream`,`application/x-ndjson`,`application/stream+json`],eW=qM(()=>({name:`FetchStreamPerformance`,setup(){yIe(e=>{if(e.response){let t=QU.get(e.response);if(t&&e.endTimestamp){t.end(e.endTimestamp);let n=$U.get(e.response);n&&clearTimeout(n)}}}),_I(e=>{if(e.endTimestamp&&e.response){let t=e.response.headers?.get(`content-type`)||``;if(e.response.headers?.get(`content-length`)||!jGe.some(e=>t.startsWith(e)))return;let n=e.fetchData?.url||``,r=e.fetchData?.method||`GET`,i=RN(n),a=qj({name:`${r} ${n.startsWith(`data:`)?HN(n):i?zN(i):n}`,startTime:e.endTimestamp,attributes:{url:HN(n),"http.method":r,type:`fetch`,[pA]:`http.client.stream`,[mA]:`auto.http.browser.stream`}});QU.set(e.response,a);let o=setTimeout(()=>{a.isRecording()&&a.end()},AGe);$U.set(e.response,o)}})}})),MGe=`WebVitals`,tW=qM((e={})=>{let t=new Set(e.ignore??[]);return{name:MGe,setup(n){let r=Rj(n),{enableStandaloneClsSpans:i,enableStandaloneLcpSpans:a}=e._experiments??{},o=r||t.has(`cls`)?void 0:i||!1,s=r||t.has(`lcp`)?void 0:a||!1,c=ize({recordClsStandaloneSpans:o,recordLcpStandaloneSpans:s,client:n}),l=new WeakSet;n.on(`afterStartPageLoadSpan`,e=>{l.add(e)}),n.on(`spanEnd`,e=>{l.delete(e)&&(c(),pze(e,{recordClsOnPageloadSpan:o===!1,recordLcpOnPageloadSpan:s===!1,spanStreamingEnabled:r}))}),r?(t.has(`lcp`)||Mze(n),t.has(`cls`)||Pze(n),t.has(`inp`)||Ize()):t.has(`inp`)||Dze()},afterAllSetup(){t.has(`inp`)||jze()}}});function NGe(){Z.document?Z.document.addEventListener(`visibilitychange`,()=>{let e=uj();if(!e)return;let t=cj(e);if(Z.document.hidden&&t){let e=`cancelled`,{op:n,status:r}=JA(t);Q&&Y.log(`[Tracing] Transaction: ${e} -> since tab moved to the background, op: ${n}`),r||t.setStatus({code:2,message:e}),t.setAttribute(`sentry.cancellation_reason`,`document.hidden`),t.end()}}):Q&&Y.warn(`[Tracing] Could not set up background tab detection due to lack of global document`)}var nW=`sentry_previous_trace`,PGe=`sentry.previous_trace`;function FGe(e,{linkPreviousTrace:t,consistentTraceSampling:n}){let r=t===`session-storage`,i=r?RGe():void 0;e.on(`spanStart`,e=>{if(cj(e)!==e)return;let t=oA().getPropagationContext();i=IGe(i,e,t),r&&LGe(i)});let a=!0;n&&e.on(`beforeSampling`,e=>{if(!i)return;let t=oA(),n=t.getPropagationContext();if(a&&n.parentSpanId){a=!1;return}t.setPropagationContext({...n,dsc:{...n.dsc,sample_rate:String(i.sampleRate),sampled:String(rW(i.spanContext))},sampleRand:i.sampleRand}),e.parentSampled=rW(i.spanContext),e.parentSampleRate=i.sampleRate,e.spanAttributes={...e.spanAttributes,[Vke]:i.sampleRate}})}function IGe(e,t,n){let r=JA(t);function i(){try{let e=Number(r.data?.[`sentry.sample_rate`]??n.dsc?.sample_rate);return Number.isNaN(e)?0:e}catch{return 0}}let a={spanContext:t.spanContext(),startTimestamp:r.start_timestamp,sampleRate:i(),sampleRand:n.sampleRand};if(!e)return a;let o=e.spanContext;return o.traceId===r.trace_id?e:(Date.now()/1e3-e.startTimestamp<=3600&&(Q&&Y.log(`Adding previous_trace \`${JSON.stringify(o)}\` link to span \`${JSON.stringify({op:r.op,...t.spanContext()})}\``),t.addLink({context:o,attributes:{[Xke]:`previous_trace`}}),t.setAttribute(PGe,`${o.traceId}-${o.spanId}-${+!!rW(o)}`)),a)}function LGe(e){try{Z.sessionStorage.setItem(nW,JSON.stringify(e))}catch(e){Q&&Y.warn(`Could not store previous trace in sessionStorage`,e)}}function RGe(){try{let e=Z.sessionStorage?.getItem(nW);return JSON.parse(e)}catch{return}}function rW(e){return e.traceFlags===1}var zGe=`BrowserTracing`,BGe=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function iW(){let e=Z.navigator;return e?.userAgent?BGe.test(e.userAgent):!1}var VGe={...aM,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:`in-memory`,consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...YU},aW=((e={})=>{`enableElementTiming`in e&&CO(()=>{console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.")});let t={name:void 0,source:void 0},n=Z.document,{enableInp:r,enableLongTask:i,enableLongAnimationFrame:a,_experiments:{enableInteractions:o,enableStandaloneClsSpans:s,enableStandaloneLcpSpans:c},beforeStartSpan:l,idleTimeout:u,finalTimeout:d,childSpanTimeout:f,markBackgroundSpan:p,traceFetch:m,traceXHR:h,trackFetchStreamPerformance:g,shouldCreateSpanForRequest:_,enableHTTPTimings:v,ignoreResourceSpans:y,ignorePerformanceApiSpans:b,instrumentPageLoad:x,instrumentNavigation:S,detectRedirects:C,linkPreviousTrace:w,consistentTraceSampling:T,enableReportPageLoaded:E,onRequestSpanStart:D,onRequestSpanEnd:ee}={...VGe,...e},te=iW(),ne,O;function k(e,r,i=!0,a){let o=r.op===`pageload`,s=r.name,c=l?l(r):r,p=RN(a||CI()),m={...p?.pathname&&{"url.path":p.pathname},...p&&!LN(p)&&{"url.full":p.href},...c.attributes};if(s!==c.name&&(m[dA]=`custom`),c.attributes=m,!i){let e=Ik();qj({...c,startTime:e}).end(e);return}t.name=c.name,t.source=m[dA];let h=oM(c,{idleTimeout:u,finalTimeout:d,childSpanTimeout:f,disableAutoFinish:o,beforeSpanEnd:t=>{fze(t,{ignoreResourceSpans:y,ignorePerformanceApiSpans:b,spanStreamingEnabled:Rj(e)}),fW(e,void 0);let n=oA(),r=n.getPropagationContext();n.setPropagationContext({...r,traceId:h.spanContext().traceId,sampled:ej(h),dsc:wj(t)}),o&&(O=void 0)},trimIdleSpanEndTimestamp:!E});o&&E&&(O=h),fW(e,h);function g(){n&&[`interactive`,`complete`].includes(n.readyState)&&(e.emit(`idleSpanEnableAutoFinish`,h),n.removeEventListener(`readystatechange`,g))}o&&!E&&n&&(n.addEventListener(`readystatechange`,g),g())}return{name:zGe,setup(e){if(te){Q&&Y.log(`[Tracing] Skipping browserTracingIntegration setup for bot user agent.`);return}if(pj(),a&&J.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes(`long-animation-frame`)?oze():i&&aze(),o&&sze(),C&&n){let e=()=>{ne=Lk()};addEventListener(`click`,e,{capture:!0}),addEventListener(`keydown`,e,{capture:!0,passive:!0})}function t(){let t=dW(e);t&&!JA(t).timestamp&&(Q&&Y.log(`[Tracing] Finishing current active span with op: ${JA(t).op}`),t.setAttribute(hA,`cancelled`),t.end())}e.on(`startNavigationSpan`,(n,r)=>{if(X()!==e)return;if(r?.isRedirect){Q&&Y.warn(`[Tracing] Detected redirect, navigation span will not be the root span, but a child span.`),k(e,{op:`navigation.redirect`,...n},!1,r.url);return}ne=void 0,t(),sA().setPropagationContext({traceId:Hk(),sampleRand:Math.random(),propagationSpanId:mj()?void 0:Uk()});let i=oA();i.setPropagationContext({traceId:Hk(),sampleRand:Math.random(),propagationSpanId:mj()?void 0:Uk()}),i.setSDKProcessingMetadata({normalizedRequest:void 0}),k(e,{op:`navigation`,...n,parentSpan:null,forceTransaction:!0},!0,r?.url)}),e.on(`startPageLoadSpan`,(n,r={})=>{if(X()!==e)return;t();let i=zA(r.sentryTrace||cW(`sentry-trace`)||lW(`sentry-trace`),r.baggage||cW(`baggage`)||lW(`baggage`)),a=oA();a.setPropagationContext(i),mj()||(a.getPropagationContext().propagationSpanId=Uk()),a.setSDKProcessingMetadata({normalizedRequest:sR()}),k(e,{op:`pageload`,...n})}),e.on(`endPageloadSpan`,()=>{E&&O&&(O.setAttribute(hA,`reportPageLoaded`),O.end())})},afterAllSetup(e){if(te)return;e.addIntegration&&!e.getIntegrationByName?.(`WebVitals`)&&e.addIntegration(tW({ignore:r?[]:[`inp`],_experiments:{enableStandaloneClsSpans:s,enableStandaloneLcpSpans:c}}));let n=CI();if(w!==`off`&&FGe(e,{linkPreviousTrace:w,consistentTraceSampling:T}),Z.location){if(x){let t=zk();oW(e,{name:Z.location.pathname,startTime:t?t/1e3:void 0,attributes:{[dA]:`url`,[mA]:`auto.pageload.browser`}})}S&&Fz(({to:t,from:r})=>{if(r===void 0&&n?.indexOf(t)!==-1){n=void 0;return}n=void 0;let i=RN(t),a=dW(e),o=a&&C&&UGe(a,ne);sW(e,{name:i?.pathname||Z.location.pathname,attributes:{[dA]:`url`,[mA]:`auto.navigation.browser`}},{url:t,isRedirect:o})})}p&&NGe(),o&&HGe(e,u,d,f,t),XU(e,{traceFetch:m,traceXHR:h,tracePropagationTargets:e.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:_,enableHTTPTimings:v,onRequestSpanStart:D,onRequestSpanEnd:ee}),g&&e.addIntegration(eW())}}});function oW(e,t,n){e.emit(`startPageLoadSpan`,t,n),oA().setTransactionName(t.name);let r=dW(e);return r&&e.emit(`afterStartPageLoadSpan`,r),r}function sW(e,t,n){let{url:r,isRedirect:i}=n||{};e.emit(`beforeStartNavigationSpan`,t,{isRedirect:i,url:r}),e.emit(`startNavigationSpan`,t,{isRedirect:i,url:r});let a=oA();return a.setTransactionName(t.name),r&&!i&&a.setSDKProcessingMetadata({normalizedRequest:{...sR(),url:r}}),dW(e)}function cW(e){return(Z.document?.querySelector(`meta[name=${e}]`))?.getAttribute(`content`)||void 0}function lW(e){return(Z.performance?.getEntriesByType?.(`navigation`)[0])?.serverTiming?.find(t=>t.name===e)?.description}function HGe(e,t,n,r,i){let a=Z.document,o;a&&addEventListener(`click`,()=>{let a=`ui.action.click`,s=dW(e);if(s){let e=JA(s).op;if([`navigation`,`pageload`].includes(e)){Q&&Y.warn(`[Tracing] Did not create ${a} span because a pageload or navigation span is in progress.`);return}}if(o&&=(o.setAttribute(hA,`interactionInterrupted`),o.end(),void 0),!i.name){Q&&Y.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`);return}o=oM({name:i.name,op:a,attributes:{[dA]:i.source||`url`}},{idleTimeout:t,finalTimeout:n,childSpanTimeout:r})},{capture:!0})}var uW=`_sentry_idleSpan`;function dW(e){return e[uW]}function fW(e,t){sk(e,uW,t)}var pW=1.5;function UGe(e,t){let n=JA(e),r=Ik();return!(r-n.start_timestamp>pW||t&&r-t<=pW)}function WGe(e=X()){e?.emit(`endPageloadSpan`)}function GGe(e){let t=uj();if(t===e)return;let n=oA();e.end=new Proxy(e.end,{apply(e,r,i){return qk(n,t),Reflect.apply(e,r,i)}}),qk(n,e)}var KGe=qM(()=>({name:`SpanStreaming`,beforeSetup(e){let t=e.getOptions();t.traceLifecycle||=(Q&&Y.log('[SpanStreaming] setting `traceLifecycle` to "stream"'),`stream`)},setup(e){let t=`SpanStreaming integration requires`,n=`Falling back to static trace lifecycle.`,r=e.getOptions();if(!Rj(e)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} \`traceLifecycle\` to be set to "stream"! ${n}`);return}let i=r.beforeSendSpan;if(i&&!Tj(i)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} a beforeSendSpan callback using \`withStreamedSpan\`! ${n}`);return}let a=new hIe(e);e.on(`afterSpanEnd`,t=>{ej(t)&&a.add(dje(t,e))}),e.on(`afterSegmentSpanEnd`,e=>{let t=e.spanContext().traceId;setTimeout(()=>{a.flush(t)},500)})}})),mW=1e6,qGe=`window`in J&&J.window===J&&typeof importScripts>`u`,hW=`0`,gW=qGe?`main`:`worker`,_W=Z.navigator,vW=``,yW=``,bW=``,xW=_W?.userAgent||``,SW=``,JGe=_W?.language||_W?.languages?.[0]||``;function YGe(e){return typeof e==`object`&&!!e&&`getHighEntropyValues`in e}var CW=_W?.userAgentData;YGe(CW)&&CW.getHighEntropyValues([`architecture`,`model`,`platform`,`platformVersion`,`fullVersionList`]).then(e=>{if(vW=e.platform||``,bW=e.architecture||``,SW=e.model||``,yW=e.platformVersion||``,e.fullVersionList?.length){let t=e.fullVersionList[e.fullVersionList.length-1];xW=`${t.brand} ${t.version}`}}).catch(e=>void 0);function XGe(e){return!(`thread_metadata`in e)}function ZGe(e){return XGe(e)?rKe(e):e}function QGe(e){let t=e.contexts?.trace?.trace_id;return typeof t==`string`&&t.length!==32&&Q&&Y.log(`[Profiling] Invalid traceId: ${t} on profiled event`),typeof t==`string`?t:``}function $Ge(e,t,n,r){if(r.type!==`transaction`)throw TypeError(`Profiling events may only be attached to transactions, this should never occur.`);if(n==null)throw TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${n} instead.`);let i=QGe(r),a=ZGe(n),o=t||(typeof r.start_timestamp==`number`?r.start_timestamp*1e3:Lk()*1e3),s=typeof r.timestamp==`number`?r.timestamp*1e3:Lk()*1e3;return{event_id:e,timestamp:new Date(o).toISOString(),platform:`javascript`,version:`1`,release:r.release||``,environment:r.environment||`production`,runtime:{name:`javascript`,version:Z.navigator.userAgent},os:{name:vW,version:yW,build_number:xW},device:{locale:JGe,model:SW,manufacturer:xW,architecture:bW,is_emulator:!1},debug_meta:{images:TW(n.resources)},profile:a,transactions:[{name:r.transaction||``,id:r.event_id||kk(),trace_id:i,active_thread_id:hW,relative_start_ns:`0`,relative_end_ns:((s-o)*1e6).toFixed(0)}]}}function eKe(e,t,n){if(e==null)throw TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${e} instead.`);let r=nKe(e),i=t.getOptions(),a=t.getSdkMetadata?.()?.sdk;return{chunk_id:kk(),client_sdk:{name:a?.name??`sentry.javascript.browser`,version:a?.version??`0.0.0`},profiler_id:n||kk(),platform:`javascript`,version:`2`,release:i.release??``,environment:i.environment??`production`,debug_meta:{images:TW(e.resources)},profile:r}}function tKe(e){try{if(!e||typeof e!=`object`)return{reason:`chunk is not an object`};let t=e=>typeof e==`string`&&/^[a-f0-9]{32}$/.test(e);if(!t(e.profiler_id))return{reason:`missing or invalid profiler_id`};if(!t(e.chunk_id))return{reason:`missing or invalid chunk_id`};if(!e.client_sdk)return{reason:`missing client_sdk metadata`};let n=e.profile;return n?!Array.isArray(n.frames)||!n.frames.length?{reason:`profile has no frames`}:!Array.isArray(n.stacks)||!n.stacks.length?{reason:`profile has no stacks`}:!Array.isArray(n.samples)||!n.samples.length?{reason:`profile has no samples`}:{valid:!0}:{reason:`missing profile data`}}catch(e){return{reason:`unknown validation error: ${e}`}}}function nKe(e){let t=[];for(let n=0;n<e.frames.length;n++){let r=e.frames[n];r&&(t[n]={function:r.name,abs_path:typeof r.resourceId==`number`?e.resources[r.resourceId]:void 0,lineno:r.line,colno:r.column})}let n=[];for(let t=0;t<e.stacks.length;t++){let r=e.stacks[t];if(!r)continue;let i=[],a=r;for(;a;)i.push(a.frameId),a=a.parentId===void 0?void 0:e.stacks[a.parentId];n[t]=i}let r=zk(),i=typeof performance.timeOrigin==`number`?performance.timeOrigin:r||0,a=i-(r||i),o=[];for(let t=0;t<e.samples.length;t++){let n=e.samples[t];if(!n)continue;let r=(i+(n.timestamp-a))/1e3;o[t]={stack_id:n.stackId??0,thread_id:hW,timestamp:r}}return{frames:t,stacks:n,samples:o,thread_metadata:{[hW]:{name:gW}}}}function wW(e){return JA(e).op===`pageload`}function rKe(e){let t,n=0,r={samples:[],stacks:[],frames:[],thread_metadata:{[hW]:{name:gW}}},i=e.samples[0];if(!i)return r;let a=i.timestamp,o=zk(),s=typeof performance.timeOrigin==`number`?performance.timeOrigin:o||0,c=s-(o||s);return e.samples.forEach((i,o)=>{if(i.stackId===void 0){t===void 0&&(t=n,r.stacks[t]=[],n++),r.samples[o]={elapsed_since_start_ns:((i.timestamp+c-a)*mW).toFixed(0),stack_id:t,thread_id:hW};return}let s=e.stacks[i.stackId],l=[];for(;s;){l.push(s.frameId);let t=e.frames[s.frameId];t&&r.frames[s.frameId]===void 0&&(r.frames[s.frameId]={function:t.name,abs_path:typeof t.resourceId==`number`?e.resources[t.resourceId]:void 0,lineno:t.line,colno:t.column}),s=s.parentId===void 0?void 0:e.stacks[s.parentId]}let u={elapsed_since_start_ns:((i.timestamp+c-a)*mW).toFixed(0),stack_id:n,thread_id:hW};r.stacks[n]=l,r.samples[o]=u,n++}),r}function iKe(e,t){if(!t.length)return e;for(let n of t)e[1].push([{type:`profile`},n]);return e}function aKe(e){let t=[];return Oj(e,(e,n)=>{if(n===`transaction`)for(let n=1;n<e.length;n++)e[n]?.contexts?.profile?.profile_id&&t.push(e[n])}),t}function TW(e){let t=X()?.getOptions()?.stackParser;return t?_je(t,e):[]}function EW(e){return typeof e!=`number`&&typeof e!=`boolean`||typeof e==`number`&&isNaN(e)?(Q&&Y.warn(`[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(e)} of type ${JSON.stringify(typeof e)}.`),!1):e===!0||e===!1?!0:e<0||e>1?(Q&&Y.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${e}.`),!1):!0}function oKe(e){return e.samples.length<2?(Q&&Y.log(`[Profiling] Discarding profile because it contains less than 2 samples`),!1):e.frames.length?!0:(Q&&Y.log(`[Profiling] Discarding profile because it contains no frames`),!1)}var DW=!1,OW=3e4;function sKe(e){return typeof e==`function`}function kW(){let e=Z.Profiler;if(!sKe(e)){Q&&Y.log(`[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.`);return}let t=Math.floor(OW/10);try{return new e({sampleInterval:10,maxBufferSize:t})}catch{Q&&(Y.log(`[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header.`),Y.log(`[Profiling] Disabling profiling for current user session.`)),DW=!0}}function AW(e){if(DW)return Q&&Y.log(`[Profiling] Profiling has been disabled for the duration of the current user session.`),!1;if(!e.isRecording())return Q&&Y.log(`[Profiling] Discarding profile because root span was not sampled.`),!1;let t=X()?.getOptions();if(!t)return Q&&Y.log(`[Profiling] Profiling disabled, no options found.`),!1;let n=t.profilesSampleRate;return EW(n)?n?n===!0||Math.random()<n||(Q&&Y.log(`[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(n)})`),!1):(Q&&Y.log(`[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0`),!1):(Q&&Y.warn(`[Profiling] Discarding profile because of invalid sample rate.`),!1)}function cKe(e){if(DW)return Q&&Y.log(`[Profiling] Profiling has been disabled for the duration of the current user session as the JS Profiler could not be started.`),!1;if(e.profileLifecycle!==`trace`&&e.profileLifecycle!==`manual`)return Q&&Y.warn("[Profiling] Session not sampled. Invalid `profileLifecycle` option."),!1;let t=e.profileSessionSampleRate;return EW(t)?t?Math.random()<=t:(Q&&Y.log(`[Profiling] Discarding profile because profileSessionSampleRate is not defined or set to 0`),!1):(Q&&Y.warn(`[Profiling] Discarding profile because of invalid profileSessionSampleRate.`),!1)}function jW(e){return e.profilesSampleRate!==void 0}function lKe(e,t,n,r){return oKe(n)?$Ge(e,t,n,r):null}var MW=new Map;function uKe(){return MW.size}function dKe(e){let t=MW.get(e);return t&&MW.delete(e),t}function fKe(e,t){if(MW.set(e,t),MW.size>30){let e=MW.keys().next().value;e!==void 0&&MW.delete(e)}}var NW=new WeakSet;function PW(e){e.setAttribute(`thread.id`,hW),e.setAttribute(`thread.name`,gW)}function FW(e){let t;wW(e)&&(t=Lk()*1e3);let n=kW();if(!n)return;Q&&Y.log(`[Profiling] started profiling span: ${JA(e).description}`);let r=kk(),i=null;oA().setContext(`profile`,{profile_id:r,start_timestamp:t}),NW.add(e),PW(e);async function a(){if(e&&n){if(i){Q&&Y.log(`[Profiling] profile for:`,JA(e).description,`already exists, returning early`);return}return n.stop().then(t=>{if(o&&=(Z.clearTimeout(o),void 0),Q&&Y.log(`[Profiling] stopped profiling of span: ${JA(e).description}`),!t){Q&&Y.log(`[Profiling] profiler returned null profile for: ${JA(e).description}`,`this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started`);return}i=t,fKe(r,t)}).catch(e=>{Q&&Y.log(`[Profiling] error while stopping profiler:`,e)})}}let o=Z.setTimeout(()=>{Q&&Y.log(`[Profiling] max profile duration elapsed, stopping profiling for:`,JA(e).description),a()},OW),s=e.end.bind(e);function c(){return e?(a().then(()=>{s()},()=>{s()}),e):s()}e.end=c}var pKe=6e4,mKe=3e5,hKe=class{constructor(){this._client=void 0,this._profiler=void 0,this._chunkTimer=void 0,this._profilerId=void 0,this._isRunning=!1,this._sessionSampled=!1,this._lifecycleMode=void 0,this._activeRootSpanIds=new Set,this._rootSpanTimeouts=new Map}initialize(e){let t=e.getOptions().profileLifecycle,n=cKe(e.getOptions());Q&&Y.log(`[Profiling] Initializing profiler (lifecycle='${t}').`),n||Q&&Y.log(`[Profiling] Session not sampled. Skipping lifecycle profiler initialization.`),this._profilerId=kk(),this._client=e,this._sessionSampled=n,this._lifecycleMode=t,t===`trace`&&this._setupTraceLifecycleListeners(e),e.on(`spanStart`,e=>{this._isRunning&&PW(e)})}start(){if(this._lifecycleMode===`trace`){Q&&Y.warn('[Profiling] `profileLifecycle` is set to "trace". Calls to `uiProfiler.start()` are ignored in trace mode.');return}if(this._isRunning){Q&&Y.warn("[Profiling] Profile session is already running, `uiProfiler.start()` is a no-op.");return}if(!this._sessionSampled){Q&&Y.warn("[Profiling] Session is not sampled, `uiProfiler.start()` is a no-op.");return}this._beginProfiling()}stop(){if(this._lifecycleMode===`trace`){Q&&Y.warn('[Profiling] `profileLifecycle` is set to "trace". Calls to `uiProfiler.stop()` are ignored in trace mode.');return}if(!this._isRunning){Q&&Y.warn("[Profiling] Profiler is not running, `uiProfiler.stop()` is a no-op.");return}this._endProfiling()}notifyRootSpanActive(e){if(this._lifecycleMode!==`trace`||!this._sessionSampled)return;let t=e.spanContext().spanId;if(!t||this._activeRootSpanIds.has(t))return;this._registerTraceRootSpan(t);let n=this._activeRootSpanIds.size;n===1&&(Q&&Y.log(`[Profiling] Detected already active root span during setup. Active root spans now:`,n),this._beginProfiling()),this._isRunning&&PW(e)}_beginProfiling(){if(!this._isRunning){if(this._isRunning=!0,Q&&Y.log(`[Profiling] Started profiling with profiler ID:`,this._profilerId),cA().setContext(`profile`,{profiler_id:this._profilerId}),this._startProfilerInstance(),!this._profiler){Q&&Y.log(`[Profiling] Failed to start JS Profiler; stopping.`),this._resetProfilerInfo();return}this._startPeriodicChunking()}}_endProfiling(){this._isRunning&&(this._isRunning=!1,this._chunkTimer&&=(clearTimeout(this._chunkTimer),void 0),this._clearAllRootSpanTimeouts(),this._collectCurrentChunk().catch(e=>{Q&&Y.error("[Profiling] Failed to collect current profile chunk on `stop()`:",e)}),this._lifecycleMode===`manual`&&cA().setContext(`profile`,{}))}_setupTraceLifecycleListeners(e){e.on(`spanStart`,e=>{if(!this._sessionSampled){Q&&Y.log(`[Profiling] Span not profiled because of negative sampling decision for user session.`);return}if(e!==cj(e))return;if(!e.isRecording()){Q&&Y.log(`[Profiling] Discarding profile because root span was not sampled.`);return}let t=e.spanContext().spanId;if(!t||this._activeRootSpanIds.has(t))return;this._registerTraceRootSpan(t);let n=this._activeRootSpanIds.size;n===1&&(Q&&Y.log(`[Profiling] Root span ${t} started. Profiling active while there are active root spans (count=${n}).`),this._beginProfiling())}),e.on(`spanEnd`,e=>{if(!this._sessionSampled)return;let t=e.spanContext().spanId;if(!t||!this._activeRootSpanIds.has(t))return;this._activeRootSpanIds.delete(t);let n=this._activeRootSpanIds.size;Q&&Y.log(`[Profiling] Root span with ID ${t} ended. Will continue profiling for as long as there are active root spans (currently: ${n}).`),n===0&&(this._collectCurrentChunk().catch(e=>{Q&&Y.error("[Profiling] Failed to collect current profile chunk on last `spanEnd`:",e)}),this._endProfiling())})}_resetProfilerInfo(){this._isRunning=!1,cA().setContext(`profile`,{})}_clearAllRootSpanTimeouts(){this._rootSpanTimeouts.forEach(e=>clearTimeout(e)),this._rootSpanTimeouts.clear()}_registerTraceRootSpan(e){this._activeRootSpanIds.add(e);let t=setTimeout(()=>this._onRootSpanTimeout(e),mKe);this._rootSpanTimeouts.set(e,t)}_startProfilerInstance(){if(this._profiler?.stopped===!1)return;let e=kW();if(!e){Q&&Y.log(`[Profiling] Failed to start JS Profiler.`);return}this._profiler=e}_startPeriodicChunking(){this._isRunning&&(this._chunkTimer=setTimeout(()=>{if(this._collectCurrentChunk().catch(e=>{Q&&Y.error(`[Profiling] Failed to collect current profile chunk during periodic chunking:`,e)}),this._isRunning){if(this._startProfilerInstance(),!this._profiler){this._resetProfilerInfo();return}this._startPeriodicChunking()}},pKe))}_onRootSpanTimeout(e){this._rootSpanTimeouts.has(e)&&(this._rootSpanTimeouts.delete(e),this._activeRootSpanIds.has(e)&&(Q&&Y.log(`[Profiling] Reached 5-minute timeout for root span ${e}. You likely started a manual root span that never called \`.end()\`.`),this._activeRootSpanIds.delete(e),this._activeRootSpanIds.size===0&&this._endProfiling()))}async _collectCurrentChunk(){let e=this._profiler;if(this._profiler=void 0,e)try{let t=eKe(await e.stop(),this._client,this._profilerId),n=tKe(t);if(`reason`in n){Q&&Y.log(`[Profiling] Discarding invalid profile chunk (this is probably a bug in the SDK):`,n.reason);return}this._sendProfileChunk(t),Q&&Y.log(`[Profiling] Collected browser profile chunk.`)}catch(e){Q&&Y.log(`[Profiling] Error while stopping JS Profiler for chunk:`,e)}}_sendProfileChunk(e){let t=this._client,n=Nj(t.getSdkMetadata?.()),r=t.getDsn(),i=t.getOptions().tunnel,a=Ej({event_id:kk(),sent_at:new Date().toISOString(),...n&&{sdk:n},...!!i&&r&&{dsn:NA(r)}},[[{type:`profile_chunk`,platform:`javascript`},e]]);t.sendEnvelope(a).then(null,e=>{Q&&Y.error(`Error while sending profile chunk envelope:`,e)})}},gKe=`BrowserProfiling`,_Ke=qM((()=>({name:gKe,setup(e){let t=e.getOptions(),n=new hKe;if(!jW(t)&&!t.profileLifecycle&&(t.profileLifecycle=`manual`),jW(t)&&!t.profilesSampleRate){Q&&Y.log(`[Profiling] Profiling disabled, no profiling options found.`);return}let r=uj(),i=r&&cj(r);if(jW(t)&&t.profileSessionSampleRate!==void 0&&Q&&Y.warn("[Profiling] Both legacy profiling (`profilesSampleRate`) and UI profiling settings are defined. `profileSessionSampleRate` has no effect when legacy profiling is enabled."),jW(t))i&&wW(i)&&AW(i)&&FW(i),e.on(`spanStart`,e=>{let t=cj(e);e===t?AW(e)&&FW(e):NW.has(t)&&PW(e)}),e.on(`beforeEnvelope`,e=>{if(!uKe())return;let t=aKe(e);if(!t.length)return;let n=[];for(let e of t){let t=e?.contexts,r=t?.profile?.profile_id,i=t?.profile?.start_timestamp;if(typeof r!=`string`){Q&&Y.log(`[Profiling] cannot find profile for a span without a profile context`);continue}if(!r){Q&&Y.log(`[Profiling] cannot find profile for a span without a profile context`);continue}t?.profile&&delete t.profile;let a=dKe(r);if(!a){Q&&Y.log(`[Profiling] Could not retrieve profile for span: ${r}`);continue}let o=lKe(r,i,a,e);o&&n.push(o)}iKe(e,n)});else{let r=t.profileLifecycle;if(e.on(`startUIProfiler`,()=>n.start()),e.on(`stopUIProfiler`,()=>n.stop()),r===`manual`)n.initialize(e);else if(r===`trace`){if(!mj(t)){Q&&Y.warn("[Profiling] `profileLifecycle` is 'trace' but tracing is disabled. Set a `tracesSampleRate` or `tracesSampler` to enable span tracing.");return}n.initialize(e),i&&n.notifyRootSpanActive(i),Z.setTimeout(()=>{let e=uj(),t=e&&cj(e);t&&n.notifyRootSpanActive(t)},0)}}}}))),vKe=`SpotlightBrowser`,yKe=[{op:`ui.interaction.click`,name:`#sentry-spotlight`}],bKe=((e={})=>{let t=e.sidecarUrl||`http://localhost:8969/stream`;return{name:vKe,setup:()=>{Q&&Y.log(`Using Sidecar URL`,t)},beforeSetup(e){let t=e.getOptions();t.ignoreSpans=[...t.ignoreSpans||[],...yKe]},afterAllSetup:e=>{xKe(e,t)}}});function xKe(e,t){let n=Lz(`fetch`),r=0;e.on(`beforeEnvelope`,e=>{if(r>3){Y.warn(`[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:`,r);return}n(t,{method:`POST`,body:Aj(e),headers:{"Content-Type":`application/x-sentry-envelope`},mode:`cors`}).then(e=>{e.status>=200&&e.status<400&&(r=0)},e=>{r++,Y.error(`Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/`,e)})})}var SKe=qM(bKe),CKe=qM(()=>({name:`LaunchDarkly`,processEvent(e,t,n){return EP(e)}}));function wKe(){return{name:`sentry-flag-auditor`,type:`flag-used`,synchronous:!0,method:(e,t,n)=>{DP(e,t.value),OP(e,t.value)}}}var TKe=qM(()=>({name:`OpenFeature`,processEvent(e,t,n){return EP(e)}})),EKe=class{after(e,t){DP(t.flagKey,t.value),OP(t.flagKey,t.value)}error(e,t,n){DP(e.flagKey,e.defaultValue),OP(e.flagKey,e.defaultValue)}},DKe=qM(({featureFlagClientClass:e})=>({name:`Unleash`,setupOnce(){let t=e.prototype;ok(t,`isEnabled`,OKe)},processEvent(e,t,n){return EP(e)}}));function OKe(e){return function(...t){let n=t[0],r=e.apply(this,t);return typeof n==`string`&&typeof r==`boolean`?(DP(n,r),OP(n,r)):Q&&Y.error(`[Feature Flags] UnleashClient.isEnabled does not match expected signature. arg0: ${n} (${typeof n}), result: ${r} (${typeof r})`),r}}var kKe=(({growthbookClass:e})=>JNe({growthbookClass:e})),AKe=qM(({featureFlagClient:e})=>({name:`Statsig`,setup(t){e.on(`gate_evaluation`,e=>{DP(e.gate.name,e.gate.value),OP(e.gate.name,e.gate.value)})},processEvent(e,t,n){return EP(e)}})),jKe=`WebWorker`,MKe=qM(({worker:e})=>({name:jKe,setupOnce:()=>{(Array.isArray(e)?e:[e]).forEach(e=>IW(e))},addWorker:e=>IW(e)}));function IW(e){e.addEventListener(`message`,e=>{if(FKe(e.data)){if(e.stopImmediatePropagation(),e.data._sentryDebugIds&&(Q&&Y.log(`Sentry debugId web worker message received`,e.data),Z._sentryDebugIds={...e.data._sentryDebugIds,...Z._sentryDebugIds}),e.data._sentryModuleMetadata&&(Q&&Y.log(`Sentry module metadata web worker message received`,e.data),Z._sentryModuleMetadata={...e.data._sentryModuleMetadata,...Z._sentryModuleMetadata}),e.data._sentryWasmImages){Q&&Y.log(`Sentry WASM images web worker message received`,e.data);let t=Z._sentryWasmImages||[],n=e.data._sentryWasmImages.filter(e=>ek(e)&&typeof e.code_file==`string`&&!t.some(t=>t.code_file===e.code_file));Z._sentryWasmImages=[...t,...n]}e.data._sentryWorkerError&&(Q&&Y.log(`Sentry worker rejection message received`,e.data._sentryWorkerError),NKe(e.data._sentryWorkerError))}})}function NKe(e){let t=X();if(!t)return;let n=t.getOptions().stackParser,r=t.getOptions().attachStacktrace,i=e.reason,a=$O(i)?nB(i):gR(n,i,void 0,r,!0);a.level=`error`,e.filename&&(a.contexts={...a.contexts,worker:{filename:e.filename}}),jM(a,{originalException:i,mechanism:{handled:!1,type:`auto.browser.web_worker.onunhandledrejection`}}),Q&&Y.log(`Captured worker unhandled rejection`,i)}function PKe({self:e}){e.postMessage({_sentryMessage:!0,_sentryDebugIds:e._sentryDebugIds??void 0,_sentryModuleMetadata:e._sentryModuleMetadata??void 0}),e.addEventListener(`unhandledrejection`,t=>{let n={reason:tB(t),filename:e.location?.href};e.postMessage({_sentryMessage:!0,_sentryWorkerError:n}),Q&&Y.log(`[Sentry Worker] Forwarding unhandled rejection to parent`,n)}),Q&&Y.log(`[Sentry Worker] Registered worker with unhandled rejection handling`)}function FKe(e){if(!ek(e)||e._sentryMessage!==!0)return!1;let t=`_sentryDebugIds`in e,n=`_sentryModuleMetadata`in e,r=`_sentryWorkerError`in e,i=`_sentryWasmImages`in e;return!(!t&&!n&&!r&&!i||t&&!(ek(e._sentryDebugIds)||e._sentryDebugIds===void 0)||n&&!(ek(e._sentryModuleMetadata)||e._sentryModuleMetadata===void 0)||r&&!ek(e._sentryWorkerError)||i&&(!Array.isArray(e._sentryWasmImages)||!e._sentryWasmImages.every(e=>ek(e)&&typeof e.code_file==`string`)))}var IKe=50,[,LKe]=Kz,[,RKe]=EIe(),LW=(e,t=0)=>{let n=[];for(let r of e.split(`
1004
1004
  `).slice(t)){let e=LKe(r),t=RKe(r);if(e&&t?.in_app!==!1?n.push(e):t&&(t.module===void 0&&delete t.module,n.push(t)),n.length>=IKe)break}return jO(n)},zKe=qM(e=>{let t=e?.threshold??1e3,n=e?.pollInterval||t/2;return{name:`EventLoopBlockRenderer`,setup(r){let i={pollInterval:n,anrThreshold:t,captureStackTrace:!0,...e},a=EI(r);a.sendStatus({status:document.visibilityState,config:i}),setInterval(()=>{a.sendStatus({status:`alive`,config:i})},i.pollInterval)}}});function RW(){let e=cA().getScopeData(),t=sA().getScopeData(),n=oA().getScopeData();return fM(e,t),fM(e,n),e.eventProcessors=[],e}function BKe(e){sA().addScopeListener(t=>{e(RW(),t)}),oA().addScopeListener(t=>{e(RW(),t)}),cA().addScopeListener(t=>{e(RW(),t)})}var zW=qM(()=>({name:`ScopeToMain`,setup(e){let t=EI(e);BKe((e,n)=>{t.sendScope(JSON.stringify(vk(e,20,2e3))),n.clearBreadcrumbs(),n.clearAttachments()})}}));function BW(e){let t;return mN(e,async e=>(t||=EI(),t.sendEnvelope(e.body),{statusCode:200}))}function VW(e){return[...cB(e).filter(e=>e.name!==`BrowserSession`&&e.name!==`CultureContext`),zW()]}function HW(e={},t=HBe){if(window?.__SENTRY__RENDERER_INIT__){Y.warn(`The browser SDK has already been initialized.
1005
- If init has been called in the preload and contextIsolation is disabled, is not required to call init in the renderer`);return}window.__SENTRY__RENDERER_INIT__=!0,e.sendClientReports=!1,e.defaultIntegrations===void 0&&(e.defaultIntegrations=VW(e)),e.stackParser===void 0&&(e.stackParser=LW),e.ipcNamespace===void 0&&(e.ipcNamespace=`sentry-ipc`),e.dsn===void 0&&(e.dsn=`https://12345@dummy.dsn/12345`),e.transport===void 0&&(e.transport=BW),delete e.initialScope,t(e)}var UW=e({BrowserClient:()=>vR,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>TMe,OpenFeatureIntegrationHook:()=>EKe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>pA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>mA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>fA,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>dA,Scope:()=>Yk,addBreadcrumb:()=>qN,addEventProcessor:()=>IM,addIntegration:()=>KM,bindScopeToEmitter:()=>$Ae,breadcrumbsIntegration:()=>Yz,browserApiErrorsIntegration:()=>Xz,browserProfilingIntegration:()=>_Ke,browserSessionIntegration:()=>Qz,browserTracingIntegration:()=>aW,buildLaunchDarklyFlagUsedHandler:()=>wKe,captureConsoleIntegration:()=>eNe,captureEvent:()=>jM,captureException:()=>kM,captureFeedback:()=>MP,captureMessage:()=>AM,captureSession:()=>BM,chromeStackLineParser:()=>Kz,consoleLoggingIntegration:()=>oPe,contextLinesIntegration:()=>sVe,continueTrace:()=>BAe,createConsolaReporter:()=>lPe,createLangChainCallbackHandler:()=>oI,createTransport:()=>mN,createUserFeedbackEnvelope:()=>dBe,dedupeIntegration:()=>pP,defaultRequestInstrumentationOptions:()=>YU,defaultStackParser:()=>LW,elementTimingIntegration:()=>Eze,endSession:()=>RM,eventFiltersIntegration:()=>XN,eventFromException:()=>mR,eventFromMessage:()=>hR,eventLoopBlockIntegration:()=>zKe,exceptionFromError:()=>uR,extraErrorDataIntegration:()=>sNe,featureFlagsIntegration:()=>qNe,feedbackAsyncIntegration:()=>lRe,feedbackIntegration:()=>lR,feedbackSyncIntegration:()=>lR,fetchStreamPerformanceIntegration:()=>eW,forceLoad:()=>UBe,functionToStringIntegration:()=>YN,getAbsoluteUrl:()=>Xze,getActiveSpan:()=>uj,getClient:()=>X,getCurrentScope:()=>oA,getDefaultIntegrations:()=>VW,getFeedback:()=>gLe,getGlobalScope:()=>cA,getIsolationScope:()=>sA,getReplay:()=>rGe,getRootSpan:()=>cj,getSpanDescendants:()=>sj,getSpanStatusFromHttpCode:()=>xA,getTraceData:()=>KN,globalHandlersIntegration:()=>eB,graphqlClientIntegration:()=>hVe,growthbookIntegration:()=>kKe,httpClientIntegration:()=>YBe,httpContextIntegration:()=>aB,inboundFiltersIntegration:()=>ZN,init:()=>HW,instrumentAnthropicAiClient:()=>TFe,instrumentCreateReactAgent:()=>lIe,instrumentGoogleGenAIClient:()=>LFe,instrumentLangChainEmbeddings:()=>QFe,instrumentLangGraph:()=>uIe,instrumentOpenAiClient:()=>oFe,instrumentOutgoingRequests:()=>XU,instrumentSupabaseClient:()=>DNe,isBotUserAgent:()=>iW,isEnabled:()=>FM,isInitialized:()=>Fje,lastEventId:()=>PM,launchDarklyIntegration:()=>CKe,linkedErrorsIntegration:()=>oB,logger:()=>MIe,makeRendererTransport:()=>BW,metrics:()=>zIe,moduleMetadataIntegration:()=>ZMe,normalizeStringifyValue:()=>sB,onLoad:()=>WBe,openFeatureIntegration:()=>TKe,parameterize:()=>GN,registerSpanErrorInstrumentation:()=>pj,registerWebWorker:()=>PKe,replayCanvasIntegration:()=>SGe,replayIntegration:()=>yU,reportPageLoaded:()=>WGe,reportingObserverIntegration:()=>qBe,rewriteFramesIntegration:()=>hNe,scopeToMainIntegration:()=>zW,sendFeedback:()=>BI,setActiveSpanInBrowser:()=>GGe,setAttribute:()=>Nje,setAttributes:()=>Mje,setContext:()=>MM,setConversationId:()=>Pje,setCurrentClient:()=>NN,setExtra:()=>kje,setExtras:()=>Oje,setHttpStatus:()=>SA,setMeasurement:()=>Fj,setTag:()=>jje,setTags:()=>Aje,setUser:()=>NM,showReportDialog:()=>lB,spanStreamingIntegration:()=>KGe,spanToBaggageHeader:()=>SAe,spanToJSON:()=>JA,spanToTraceHeader:()=>UA,spotlightBrowserIntegration:()=>SKe,startBrowserTracingNavigationSpan:()=>sW,startBrowserTracingPageLoadSpan:()=>oW,startInactiveSpan:()=>qj,startNewTrace:()=>Xj,startSession:()=>LM,startSpan:()=>Gj,startSpanManual:()=>Kj,statsigIntegration:()=>AKe,supabaseIntegration:()=>ANe,suppressTracing:()=>VAe,thirdPartyErrorFilterIntegration:()=>zNe,uiProfiler:()=>tBe,unleashIntegration:()=>DKe,updateSpanName:()=>_Ae,viewHierarchyIntegration:()=>gVe,webVitalsIntegration:()=>tW,webWorkerIntegration:()=>MKe,withActiveSpan:()=>Jj,withIsolationScope:()=>Bke,withScope:()=>lA,withStreamedSpan:()=>CAe,zodErrorsIntegration:()=>RNe}),VKe=100,HKe=5,UKe=[`ResizeObserver loop completed with undelivered notifications.`,`ResizeObserver loop limit exceeded`,`AbortError`,`The user aborted a request.`,`Network request failed`,`NetworkError when attempting to fetch resource.`,`Failed to fetch`,`ChunkLoadError`,`Loading chunk`,`Loading CSS chunk`,`Non-Error promise rejection captured with value: Object Not Found Matching Id`];function WW(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function WKe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),WW(e.extra),WW(e.tags)}function GKe(e){let t=KW(e.version)??`0.0.0`,n=KW(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function GW(e,t){for(let n of t){let t=KW(e[n]);if(t)return t}}function KKe(e){return qW(e.enabled)??e.defaultEnabled??!1}function qKe(e){let t=KW(e.dsn);return!t||KKe(e)===!1?null:{dsn:t,environment:KW(e.environment)??KW(e.defaultEnvironment)??`production`,release:KW(e.release)??KW(e.defaultRelease)??void 0,debug:qW(e.debug)??e.defaultDebug??!1,tracesSampleRate:YW(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:JW(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:JW(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:JW(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:VKe,normalizeDepth:HKe,tags:JKe(e)}}function JKe(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=KW(r);e&&(t[n]=e)}return t}function KW(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function qW(e){if(typeof e==`boolean`)return e;let t=KW(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function JW(e,t){if(t!==void 0||e!==void 0)return YW(e,t??0)}function YW(e,t){let n=YKe(e);return n===null||n<0||n>1?t:n}function YKe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=KW(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}function XKe(e){let t=(0,ol.c)(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=Yt(pl,`bg-background text-foreground`),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=Yt(dl,`pl-1 md:pl-2.5`),t[1]=r):r=t[1];let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Mr.jsx)(hl,{}),t[2]=i):i=t[2];let a;t[3]===e.onGoToNewChat?a=t[4]:(a=(0,Mr.jsx)(`div`,{className:r,children:(0,Mr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:e.onGoToNewChat,className:`${fl} hover:bg-accent/70`,children:i})}),t[3]=e.onGoToNewChat,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Mr.jsx)(`div`,{}),t[5]=o):o=t[5];let s;t[6]===a?s=t[7]:(s=(0,Mr.jsxs)(`header`,{className:ul,children:[a,o]}),t[6]=a,t[7]=s);let c;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Mr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Mr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Mr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Mr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Mr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:ZKe,type:`button`,children:`Reload app`})]})}),t[8]=c):c=t[8];let l;return t[9]===s?l=t[10]:(l=(0,Mr.jsxs)(`div`,{className:n,children:[s,c]}),t[9]=s,t[10]=l),l}function ZKe(){return window.location.reload()}var QKe=[/\bDeepSeek\b/i,/\bKimi\b/i,/\bMoonshot\b/i,/\bdeepseek[-._a-z0-9]*\b/i,/\bkimi[-._a-z0-9]*\b/i,/\bmoonshot[-._a-z0-9]*\b/i,/\bAPEX_API_KEY\b/,/\bDEEPSEEK_API_KEY\b/,/\bKIMI_API_KEY\b/,/\bOPENAI_API_KEY\b/,/\bANTHROPIC_API_KEY\b/,/\bCURSOR_API_KEY\b/,/\bOPENCODE_API_KEY\b/,/\bforge_proxy_[A-Za-z0-9._-]+\b/,/\bProviderValidationError\b/,/\/forge-server\/node_modules\//,/https?:\/\/[^\s'"<>)]*\/api\/provider-egress\/[^\s'"<>)]*/i,/https?:\/\/[^\s'"<>)]*(?:apex|deepseek|moonshot|kimi)[^\s'"<>)]*/i],$Ke=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function XW(e){if(!e)return!1;let t=e.toLowerCase();return/\b(rate[\s-]?limit|too\s+many\s+requests|usage[ _-]limit|usage_limit_reached|quota|insufficient_quota)\b/.test(t)||/\b429\b/.test(t)}function eqe(e){return/\bbound to provider account\b/.test(e)&&/\bcannot use provider account\b/.test(e)?`Forge could not switch this conversation to the selected AI account. Retry the account switch.`:/\bforge_runtime_repairing\b/.test(e)||/\bthis turn was interrupted because the environment is being repaired\b/.test(e)?`This turn was interrupted because the environment is being repaired. Retry after the repair finishes.`:/\bforge_runtime_stopped\b/.test(e)||/\bthis turn was interrupted because the environment was stopped\b/.test(e)?`This turn was interrupted because the environment was stopped. Start the environment and retry.`:null}function tqe(e){if(!e)return null;let t=e.toLowerCase(),n=eqe(t);return n===null?/\bforge_provider_model_not_allowed\b/.test(t)||/\bnot\s+scoped\s+to\s+the\s+requested\s+model\b/.test(t)?`The workspace AI credential does not cover the model this turn asked for. Retry, or pick that model for the thread.`:/\bmodel\b[\s\S]*\b(not\s+(found|available|supported)|does\s+not\s+exist|unsupported|invalid|unknown)\b/.test(t)||/\b(unsupported|unknown|invalid)\b[\s\S]*\bmodel\b/.test(t)||/\b(model_not_found|invalid_model|model_not_supported)\b/.test(t)?`The selected model isn't available right now. Pick a different model and retry.`:XW(t)?`The AI service is rate-limited or out of quota. Wait a moment and retry.`:/\b(unauthorized|forbidden|authentication\s+(failed|error|required)|invalid\s+api\s+key|expired\s+(token|credential))\b/.test(t)||/\b40[13]\b/.test(t)?`Workspace AI authentication failed. Reconnect the workspace and retry.`:/\b(timed?\s*out|timeout|overloaded|service\s+unavailable)\b/.test(t)||/\b50[234]\b/.test(t)?`The AI service is temporarily overloaded. Retry in a moment.`:null:n}function nqe(e){return e?QKe.some(t=>t.test(e)):!1}function ZW(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:nqe(n)?tqe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var rqe=[/\bSocketCloseError\b/i,/\bSocketOpenError\b/i,/\bSocketReadError\b/i,/\bRpcClientDefect:\s*Unknown socket error\b/i,/Unable to connect to the Forge server WebSocket\./i,/\bping timeout\b/i];function QW(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&rqe.some(e=>e.test(t))}function $W(e){return QW(e)?null:ZW(e,{fallback:$Ke})}var iqe=[/^Transport disposed$/,/WebSocket RPC request timed out after \d+ms\./],aqe=`Lost the connection to this Environment. Your message was not sent.`;function oqe(e){return e instanceof Error?QW(e.message)||iqe.some(t=>t.test(e.message.trim()))?aqe:e.message:`Failed to send message.`}var eG=`forge-web`,tG=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],nG=[`VITE_SENTRY_RELEASE`],sqe=[`VITE_SENTRY_DSN`],cqe=[`VITE_SENTRY_DEBUG`],lqe=[`VITE_SENTRY_ENABLED`],uqe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],dqe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],fqe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],pqe=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],mqe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],rG=!1,iG={autoInject:!1,colorScheme:`system`,formTitle:`Report a Bug`,themeLight:{accentBackground:`oklch(0.52 0.19 48)`,accentForeground:`#ffffff`,background:`#ffffff`,boxShadow:`0 24px 80px rgba(0, 0, 0, 0.18)`,foreground:`#262626`,outline:`1px solid oklch(0.52 0.19 48)`},themeDark:{accentBackground:`oklch(0.62 0.2 47)`,accentForeground:`#ffffff`,background:`#171717`,boxShadow:`0 24px 80px rgba(0, 0, 0, 0.45)`,foreground:`#f5f5f5`,outline:`1px solid oklch(0.62 0.2 47)`}};function hqe(e){let t=e.exception&&typeof e.exception==`object`&&`values`in e.exception&&Array.isArray(e.exception.values)?e.exception.values:[];return[typeof e.title==`string`?e.title:void 0,...t.flatMap(e=>{if(typeof e!=`object`||!e)return[];let t=e;return[typeof t.type==`string`?t.type:void 0,typeof t.value==`string`?t.value:void 0]})]}function gqe(e){return(e.exception&&typeof e.exception==`object`&&`values`in e.exception&&Array.isArray(e.exception.values)?e.exception.values:[]).some(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.value!=`string`||!/All fibers interrupted without error/i.test(t.value)?!1:t.stacktrace?.frames?.some(e=>{let t=typeof e.filename==`string`?e.filename:``,n=typeof e.function==`string`?e.function:``;return t.includes(`src/rpc/wsTransport.ts`)&&n===`WsTransport.request`})})}function _qe(e){return hqe(e).some(QW)||gqe(e)}function vqe(){let e=new URL(window.location.href);Nr?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function yqe(){let e=Nr?`electron-renderer`:`browser`,t={APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`56e2269e0c33f44c636004fc33f6c402fc8e59f4`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+56e2269e0c33f44c636004fc33f6c402fc8e59f4`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=GW(t,[...nG])??GKe({appName:eG,version:`0.13.4`,commitHash:GW(t,[...mqe])});return qKe({appName:eG,runtime:e,defaultEnvironment:GW(t,[...tG])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:GW(t,[...lqe]),dsn:GW(t,[...sqe]),environment:GW(t,[...tG]),release:GW(t,[...nG]),debug:GW(t,[...cqe]),tracesSampleRate:GW(t,[...uqe]),profilesSampleRate:GW(t,[...dqe]),replaysSessionSampleRate:GW(t,[...fqe]),replaysOnErrorSampleRate:GW(t,[...pqe]),tags:{platform:Nr?`desktop`:`web`}})}function aG(e){return WKe(e),_qe(e)?null:e}function bqe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function oG(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...UKe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...bqe(e)}}function xqe(e){let t=[];e.tracesSampleRate>0&&t.push(aW()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(yU());let n=lR(iG);t.push(n);try{HW({...oG(e),beforeSend:e=>aG(e),integrations:t})}catch{return null}return rG=!0,UW}function Sqe(e){let t=[];e.tracesSampleRate>0&&t.push(cE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(ST());let n=ab(iG);t.push(n);try{HE({...oG(e),beforeSend:e=>aG(e),integrations:t})}catch{return null}return rG=!0,gO}function sG(){if(rG)return Nr?UW:gO;let e=yqe();return e?Nr?xqe(e):Sqe(e):null}function cG(e){if(sG()){if(Nr){NM(e);return}wm(e)}}function lG(e,t,n){if(!sG())return;let r=Cqe(e);if(Nr){lA(e=>{t&&e.setTags(t);let i=kM(r);n?.showReportDialog&&lB({eventId:i})});return}Vd(e=>{t&&e.setTags(t);let i=bm(r);n?.showReportDialog&&dS({eventId:i})})}function Cqe(e){if(e instanceof Error)return e;if(typeof e==`string`&&e.trim().length>0)return Error(e);try{return Error(JSON.stringify(e))}catch{return Error(`Unknown non-Error exception`)}}var wqe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){lG(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Mr.jsx)(XKe,{onGoToNewChat:vqe}):this.props.children}},uG=!1,dG=!1,fG=null,pG=null,mG=null,hG=!1,gG=new Set;function Tqe(e){if(uG||dG)return;if(!e.publicKey||!e.host){dG=!0;return}if(fG)return;if(typeof window>`u`||typeof location>`u`){dG=!0;return}let t=e.publicKey,n=e.host;fG=N(async()=>{let{default:e}=await import(`./module-CPO4cjSm.js`);return{default:e}},[]).then(({default:e})=>{pG=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{uG=!0,mG&&_G(mG),vG(),gG.forEach(e=>e())}})}).catch(()=>{dG=!0,pG=null})}function _G(e){if(mG=e,!uG||!pG)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),pG.identify(e.cmmdUserId,t)}function Eqe(e){return!uG||!pG?!1:pG.isFeatureEnabled(e)===!0}function vG(){!pG||hG||(hG=!0,pG.onFeatureFlags(()=>{gG.forEach(e=>e())}))}function Dqe(e){return gG.add(e),uG&&pG&&(vG(),e()),()=>{gG.delete(e)}}var yG=`/api/cmmd/auth-runtime`;function Oqe(e){return P({method:`POST`,path:yG},e)}function kqe(e){return P({method:`GET`,path:yG},e)}function Aqe(e){return P({method:`DELETE`,path:yG},e)}function jqe(e){return P({method:`POST`,path:`${yG}/connect`},e)}function Mqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing`,...t?.organizationId===void 0?{}:{query:{orgId:t.organizationId}}},e)}function Nqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:t.timeZone}},e)}var bG=`/api/cmmd/providers/codex/credential`,xG=`/api/cmmd/providers/claude/credential`;function Pqe(e){return P({method:`GET`,path:bG},e)}function Fqe(e){return P({method:`DELETE`,path:bG},e)}function Iqe(e){return P({method:`GET`,path:xG},e)}function Lqe(e){return P({method:`DELETE`,path:xG},e)}function Rqe(e,t){return P({method:`DELETE`,path:`/api/cmmd/providers/accounts/${encodeURIComponent(String(t))}`},e)}function zqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/disposition`}function Bqe(e,t,n,r,i){return P({method:`PUT`,path:zqe(t,n,r),body:i},e)}function Vqe(e){return(t,n,r,i)=>Bqe(e,t,n,r,i)}function Hqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/archive`}function Uqe(e,t,n,r,i){return P({method:`POST`,path:Hqe(t,n,r),body:i},e)}function Wqe(e){return(t,n,r,i)=>Uqe(e,t,n,r,i)}function Gqe(e){return typeof e==`object`&&!!e&&`status`in e&&e.status===409}async function Kqe(e){let t={action:e.action,...e.operationId===void 0?{}:{operationId:e.operationId},expectedRevision:e.expectedRevision,force:e.force};try{return await e.submit(t)}catch(n){if(!Gqe(n))throw n;let r=await e.refresh();return e.submit({...t,expectedRevision:r.revision})}}function qqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/forge-runtimes/${encodeURIComponent(t)}/rename`,body:{displayName:n}},e)}function Jqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/rename`,body:{displayName:n}},e)}function Yqe(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/revoke`},e)}function SG(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var Xqe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},Zqe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},CG=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function wG(e,t){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let n=e[t];if(Array.isArray(n))return n}return[]}function TG(e,t){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let n=e[t];if(Array.isArray(n))return n}return[]}function EG(e,t){let n={};return e?.organizationId&&(n.orgId=e.organizationId),t!==void 0&&(n.taskId=String(t)),Object.keys(n).length>0?n:void 0}function DG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():null}function Qqe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function OG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():typeof n==`number`&&Number.isFinite(n)?String(n):null}function kG(e){let t=`${DG(e,`firstName`)??``} ${DG(e,`lastName`)??``}`.trim()||DG(e,`username`)||DG(e,`email`)||`Unknown`;return{id:OG(e,`userId`)??OG(e,`id`)??t,name:t,email:DG(e,`email`),role:DG(e,`role`),avatarUrl:DG(e,`profileImage`)??DG(e,`avatar`)}}function $qe(e){let t=jG(e,`user`)??e;return kG({...typeof t==`object`&&t?t:{},userId:OG(e,`userId`)??OG(t,`id`),role:DG(e,`role`)})}function AG(e){let t=DG(e,`authorFirstName`)??``,n=DG(e,`authorLastName`)??``,r=DG(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:OG(e,`id`)??``,status:i,body:DG(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:DG(e,`authorProfileImage`)??null,createdAt:DG(e,`createdAt`)??``,updatedAt:DG(e,`updatedAt`)??DG(e,`createdAt`)??``,canEdit:Qqe(e,`canEdit`)??!1}}function eJe(e,t,n){let r=Array.isArray(e.data)?e.data.map(AG):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function jG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var tJe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function MG(e,t){let n=jG(e,t);if(!n)return null;for(let e of tJe){let t=DG(n,e);if(t)return t}return null}function NG(e,t){let n=jG(e,t);return n?OG(n,`id`):null}function PG(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function nJe(e){let t={...e,id:OG(e,`id`)??e.id,title:e.title??DG(e,`name`)??``},n=OG(e,`workspaceId`)??OG(e,`workspace_id`)??NG(e,`workspace`)??e.workspaceId??null;return n!==null||PG(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??DG(e,`start_date`)??null,endDate:e.endDate??DG(e,`end_date`)??null}:t}function FG(e){let t=e.ownerAvatarUrl??DG(e,`owner_avatar_url`)??DG(e,`ownerProfileImage`)??DG(e,`owner_profile_image`)??DG(e,`ownerImage`)??DG(e,`owner_image`)??DG(e,`ownerImageUrl`)??DG(e,`owner_image_url`)??DG(e,`createdByAvatarUrl`)??DG(e,`created_by_avatar_url`)??DG(e,`createdByProfileImage`)??DG(e,`created_by_profile_image`)??MG(e,`owner`)??MG(e,`createdBy`)??MG(e,`created_by`)??null,n={...e,id:OG(e,`id`)??e.id},r=OG(e,`campaignId`)??OG(e,`campaign_id`)??NG(e,`campaign`)??e.campaignId??null;(r!==null||PG(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??DG(e,`campaignTitle`)??DG(e,`campaign_title`)??DG(jG(e,`campaign`),`title`)??DG(jG(e,`campaign`),`name`)??null;(i!==null||PG(e,`campaignTitle`))&&(n.campaignTitle=i);let a=OG(e,`workspaceId`)??OG(e,`workspace_id`)??NG(e,`workspace`)??e.workspaceId??null;(a!==null||PG(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??DG(e,`workspace_name`)??DG(jG(e,`workspace`),`name`)??null;(o!==null||PG(e,`workspaceName`))&&(n.workspaceName=o);let s=DG(e,`workspaceIconUrl`)??DG(e,`workspace_icon_url`)??DG(jG(e,`workspace`),`iconUrl`)??null;(s!==null||PG(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=OG(e,`ownerId`)??OG(e,`owner_id`)??NG(e,`owner`)??e.ownerId??null;(c!==null||PG(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??DG(e,`owner_name`)??DG(jG(e,`owner`),`name`)??null;(l!==null||PG(e,`ownerName`))&&(n.ownerName=l),(t!==null||PG(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=OG(e,`teamId`)??OG(e,`team_id`)??NG(e,`team`)??e.teamId??null;(u!==null||PG(e,`teamId`))&&(n.teamId=u);let d=e.teamName??DG(e,`team_name`)??DG(jG(e,`team`),`name`)??null;(d!==null||PG(e,`teamName`))&&(n.teamName=d);let f=e.startDate??DG(e,`start_date`)??null;(f!==null||PG(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??DG(e,`target_end_date`)??null;return(p!==null||PG(e,`targetEndDate`))&&(n.targetEndDate=p),n}function IG(e){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let t=e;if(Array.isArray(t.items))return t.items;if(Array.isArray(t.results))return t.results}return[]}function rJe(e){return IG(e).flatMap(e=>{let t=e,n=typeof t.id==`number`?t.id:null,r=typeof t.name==`string`?t.name:null;if(n===null||r===null)return[];let i=e=>typeof t[e]==`string`?t[e]:null;return[{id:n,name:r,startDate:i(`startDate`),endDate:i(`endDate`),status:i(`status`)}]})}function iJe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function LG(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function RG(e){try{return await e}catch(e){throw e instanceof hr?e.kind===`auth`?new Xqe(e.message):new Zqe(e.message,e.status??502):e}}var zG=class e{cfg;putThreadDisposition;postThreadArchive;commentEditIdempotencyKeys=new Map;commentDeleteIdempotencyKeys=new Map;constructor(e={}){let t=e.forgeOrigin===void 0,n=e.forgeOrigin??`http://localhost:13773`;this.cfg={resolveUrl:t?ar:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??mr,...t?{resolveBearerToken:()=>pr()?.bearerToken??null}:{}},this.putThreadDisposition=Vqe(this.cfg),this.postThreadArchive=Wqe(this.cfg)}async getTask(e){return RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}`},this.cfg))}async getForgeTaskDetail(e){return P({method:`GET`,path:`/api/cmmd/tasks/${e}`},this.cfg)}async searchTasks(e){let t={q:e.q};return e.status&&(t.status=e.status),e.limit!==void 0&&(t.limit=e.limit),e.projectId&&(t.projectId=e.projectId),(await RG(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await RG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await RG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return RG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return RG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await RG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return RG(P({method:`GET`,path:`/api/cmmd/organizations/${e}/members`},this.cfg))}async getWebSocketToken(e){return P({method:`GET`,path:`/api/cmmd/ws-token`,...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async getProjectComments(e,t){let n={};return t?.organizationId&&(n.organizationId=t.organizationId),(await P({method:`GET`,path:`/api/cmmd/projects/${e}/comments`,query:n},this.cfg))?.comments??[]}async getProjectLink(e){return P({method:`GET`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd}},this.cfg)}async listProjectLinks(){return P({method:`GET`,path:`/.well-known/forge/project-links`,suppressBearerToken:!0},this.cfg)}async listProjectContextLinks(e){let t={};e.environmentId&&(t.forgeEnvironmentId=e.environmentId),e.projectId&&(t.forgeProjectId=e.projectId),e.githubRepoFullName&&(t.githubRepoFullName=e.githubRepoFullName),e.cmmdOrganizationId&&(t.cmmdOrganizationId=e.cmmdOrganizationId);let n=await P({method:`GET`,path:`/.well-known/forge/cmmd/project-links`,query:t},this.cfg),r=tn(vne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return IG(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return rJe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return IG(await P({method:`GET`,path:`/.well-known/forge/cmmd/projects`,query:{campaignId:e.campaignId}},this.cfg))}async updateTask(e,t){let n={taskId:e};return t.title!==void 0&&(n.title=t.title),t.description!==void 0&&(n.description=t.description),t.status!==void 0&&(n.status=t.status),t.priority!==void 0&&(n.priority=t.priority),t.dueDate!==void 0&&(n.dueDate=t.dueDate),t.assigneeId!==void 0&&(n.assigneeId=t.assigneeId),t.labels!==void 0&&(n.labels=t.labels),RG(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return RG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e.entityId,content:e.content}},this.cfg))}async updateComment(e,t,n){let r=`${e}:${t}:${n}`,i=this.commentEditIdempotencyKeys.get(r)??crypto.randomUUID();this.commentEditIdempotencyKeys.set(r,i);let a=await RG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${t}`,body:{content:n,idempotencyKey:i}},this.cfg));return this.commentEditIdempotencyKeys.delete(r),a}async deleteComment(e,t){let n=`${e}:${t}`,r=this.commentDeleteIdempotencyKeys.get(n)??crypto.randomUUID();this.commentDeleteIdempotencyKeys.set(n,r),await RG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${t}`,body:{idempotencyKey:r}},this.cfg)),this.commentDeleteIdempotencyKeys.delete(n)}async createProjectComment(e,t){let n=(await P({method:`POST`,path:`/api/cmmd/projects/${e}/comments`,body:{content:t.content,organizationId:t.organizationId??null}},this.cfg))?.comment;if(!n)throw new hr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of nne){let r=t[e];r!==void 0&&(n[e]=lne[e]===`nullableId`?LG(r):r)}await P({method:`PATCH`,path:`/api/cmmd/projects/${e}`,body:n},this.cfg)}async setProjectLink(e){await P({method:`POST`,path:`/.well-known/forge/project-link`,body:e},this.cfg)}async deleteProjectLink(e){await P({method:`DELETE`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd,...e.cmmdProjectId?{cmmdProjectId:e.cmmdProjectId}:{}}},this.cfg)}async createCmmdProject(e){return P({method:`POST`,path:`/.well-known/forge/cmmd/projects`,body:e},this.cfg)}async ensureGitHubProjectContext(e){return P({method:`POST`,path:`/.well-known/forge/cmmd/github-project-contexts/ensure`,body:e},this.cfg)}async createBrainDoc(e){return P({method:`POST`,path:`/api/cmmd/brain-docs`,body:e},this.cfg)}async uploadTaskAttachment(e,t){let n=new FormData;return n.append(`file`,t),RG(P({method:`POST`,path:`/api/cmmd/tasks/${e}/attachments`,form:n},this.cfg))}async archiveTask(e){await P({method:`POST`,path:`/api/cmmd/tasks/${e}/archive`},this.cfg)}async unarchiveTask(e){await P({method:`POST`,path:`/api/cmmd/tasks/${e}/unarchive`},this.cfg)}async getProfile(){return P({method:`GET`,path:`/api/cmmd/profile`},this.cfg)}async getUsageSummary(e){return P({method:`GET`,path:`/api/cmmd/usage/summary`,query:{sinceDay:e.sinceDay,untilDay:e.untilDay,timeZone:e.timeZone,...e.resolution===`hour`?{resolution:e.resolution,sinceTime:e.sinceTime,untilTime:e.untilTime}:{}}},this.cfg)}getBilling(e){return Mqe(this.cfg,e)}getBillingSeries(e){return Nqe(this.cfg,e)}async getBootstrap(){return P({method:`GET`,path:`/api/cmmd/bootstrap`},this.cfg)}async getForgeAccountPreferences(){return P({method:`GET`,path:`/api/cmmd/account/preferences`},this.cfg)}async updateForgeAccountPreferences(e){return P({method:`PATCH`,path:`/api/cmmd/account/preferences`,body:e},this.cfg)}async getOrgProviderPolicy(){return P({method:`GET`,path:`/api/cmmd/org/provider-policy`},this.cfg)}async listSavedDataViews(e){return P({method:`GET`,path:`/api/cmmd/saved-views`,query:{surface:e.surface,projectId:e.projectId}},this.cfg)}async createSavedDataView(e){return P({method:`POST`,path:`/api/cmmd/saved-views`,body:e},this.cfg)}async importSavedDataView(e){return P({method:`POST`,path:`/api/cmmd/saved-views/import`,body:e},this.cfg)}async updateSavedDataView(e,t){return P({method:`PATCH`,path:`/api/cmmd/saved-views/${encodeURIComponent(e)}`,body:t},this.cfg)}async deleteSavedDataView(e,t){return P({method:`DELETE`,path:`/api/cmmd/saved-views/${encodeURIComponent(e)}`,query:t},this.cfg)}async getDeviceRegistry(e){return P({method:`GET`,path:`/api/cmmd/devices`,...e?.projectId===void 0?{}:{query:{projectId:String(e.projectId)}},...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async registerDevice(e){return P({method:`POST`,path:`/api/cmmd/devices/register`,body:e},this.cfg)}async grantRuntimeAccess(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/access-grants`,body:t},this.cfg)}async revokeRuntimeAccess(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/access-grants/${encodeURIComponent(String(t))}/revoke`},this.cfg)}async issueRelayControlRoute(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/relay-routes`,body:t},this.cfg)}async issueRelayActionGrant(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/relay-action-grants`,body:t},this.cfg)}async getRuntimeInventory(e){let t={...e?.projectId===void 0?{}:{projectId:String(e.projectId)},...e?.allWorkspaces===!0?{allWorkspaces:`true`}:{}};return P({method:`GET`,path:`/api/cmmd/runtime-inventory`,...Object.keys(t).length>0?{query:t}:{}},this.cfg)}async getRuntimeDiagnostics(e){return P({method:`GET`,path:`/api/cmmd/runtime-diagnostics/v2/runtimes/${encodeURIComponent(e)}`},this.cfg)}async getCloudProjectLifecyclePreflight(e){return(await P({method:`GET`,path:`/api/cmmd/forge-cloud-projects/${encodeURIComponent(String(e))}/lifecycle-preflight`},this.cfg)).preflight}async replaceRuntimeInventory(e,t){return P({method:`PUT`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/inventory`,body:t},this.cfg)}static PROVIDER_ACCOUNTS_PATH=`/api/cmmd/providers/accounts`;static PROVIDER_USAGE_PATH=`/api/cmmd/providers/usage`;static PROVIDER_USAGE_REFRESH_PATH=`/api/cmmd/providers/usage/refresh`;provisionAuthRuntime(){return Oqe(this.cfg)}getAuthRuntimeState(){return kqe(this.cfg)}destroyAuthRuntime(){return Aqe(this.cfg)}connectAuthRuntime(){return jqe(this.cfg)}getUserCodexCredential(){return Pqe(this.cfg)}disconnectUserCodexCredential(){return Fqe(this.cfg)}getUserClaudeCredential(){return Iqe(this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(e){return Rqe(this.cfg,e)}async setProviderAccountDefault(t){return P({method:`PUT`,path:`${e.PROVIDER_ACCOUNTS_PATH}/default`,body:{provider:t.provider,provider_account_id:t.providerAccountId}},this.cfg)}async getProviderUsage(){return P({method:`GET`,path:e.PROVIDER_USAGE_PATH},this.cfg)}async refreshProviderUsage(t,n){return P({method:`POST`,path:e.PROVIDER_USAGE_REFRESH_PATH,body:{provider:t,providerAccountId:n}},this.cfg)}disconnectUserClaudeCredential(){return Lqe(this.cfg)}async getClaudeRuntimeReadiness(e){return P({method:`GET`,path:`/api/cmmd/providers/claude/runtime-readiness/${encodeURIComponent(e)}`},this.cfg)}async appendRuntimeThreadEvents(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/events`,body:n},this.cfg)}async getRuntimeThreadReplica(e,t){return P({method:`GET`,path:`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}`},this.cfg)}renameCloudEnvironment(e,t){return qqe(this.cfg,e,t)}renameDevice(e,t){return Jqe(this.cfg,e,t)}revokeDevice(e){return Yqe(this.cfg,e)}static SIM_PATH=`/api/cmmd/sim-host`;static simScope(e){return e?.orgId===void 0?``:`?orgId=${encodeURIComponent(String(e.orgId))}`}async listSimHosts(t){return P({method:`GET`,path:`${e.SIM_PATH}/hosts${e.simScope(t)}`},this.cfg)}async getSimLease(t){let n=new URLSearchParams({forgeEnvironmentId:t.forgeEnvironmentId,threadId:t.threadId,...t.orgId===void 0?{}:{orgId:String(t.orgId)}});return P({method:`GET`,path:`${e.SIM_PATH}/leases?${n.toString()}`},this.cfg)}async claimSimLease(t){return P({method:`POST`,path:`${e.SIM_PATH}/leases${e.simScope(t)}`,body:{hostId:t.hostId,forgeEnvironmentId:t.forgeEnvironmentId,threadId:t.threadId,ttlMs:t.ttlMs}},this.cfg)}async renewSimLease(t){return P({method:`POST`,path:`${e.SIM_PATH}/leases/${encodeURIComponent(String(t.leaseId))}/renew${e.simScope(t)}`,body:{generation:t.generation,rowVersion:t.rowVersion,ttlMs:t.ttlMs}},this.cfg)}async releaseSimLease(t){await P({method:`POST`,path:`${e.SIM_PATH}/leases/${encodeURIComponent(String(t.leaseId))}/release${e.simScope(t)}`,body:{generation:t.generation,rowVersion:t.rowVersion}},this.cfg)}async listCampaigns(e){let t={};return e?.orgId&&(t.orgId=e.orgId),e?.allWorkspaces&&(t.allWorkspaces=`true`),wG(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map(nJe)}async getCampaign(e){return P({method:`GET`,path:`/api/cmmd/campaigns/${e}`},this.cfg)}async createCampaign(e){return P({method:`POST`,path:`/api/cmmd/campaigns`,body:e},this.cfg)}async updateCampaign(e,t){return P({method:`PUT`,path:`/api/cmmd/campaigns/${e}`,body:t},this.cfg)}async deleteCampaign(e){await P({method:`DELETE`,path:`/api/cmmd/campaigns/${e}`},this.cfg)}async listProjects(e){let t={};return e?.campaignId&&(t.campaignId=e.campaignId),e?.orgId&&(t.orgId=e.orgId),e?.allWorkspaces&&(t.allWorkspaces=`true`),wG(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(FG)}async listTasks(e){let t={};return e?.projectId&&(t.projectId=e.projectId),e?.status&&(t.status=e.status),P({method:`GET`,path:`/api/cmmd/tasks`,query:t},this.cfg)}async getProject(e){return FG(await P({method:`GET`,path:`/api/cmmd/projects/${e}`},this.cfg))}async getProjectMembers(e){let t=await P({method:`GET`,path:`/api/cmmd/projects/${e}/members`},this.cfg);return Array.isArray(t)?t.map(kG):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map($qe):[]}async addProjectMember(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/members`,body:t},this.cfg)}async listProjectAgentMembers(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/agent-members`},this.cfg)}async createProjectAgentMember(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members`,body:t},this.cfg)}async renameProjectAgentMember(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/agent-members/${t}`,body:n},this.cfg)}async retireProjectAgentMember(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/${t}/retire`,body:n},this.cfg)}async updateProjectAgentMemberAvatar(e,t,n){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/agent-members/${t}/avatar`,body:n},this.cfg)}async listProjectAgentMemberInstances(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/agent-members/${t}/instances`},this.cfg)}async previewProjectAgentMemberConsolidation(e){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/consolidation/preview`},this.cfg)}async applyProjectAgentMemberConsolidation(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/consolidation/apply`,body:t},this.cfg)}async setProjectTaskAssignment(e,t,n){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/tasks/${t}/assignment`,body:n},this.cfg)}async getProjectUpdates(e,t){let n=t?.page??1,r=t?.limit??10;return eJe(await P({method:`GET`,path:`/api/cmmd/projects/${e}/updates`,query:{page:n,limit:r},unwrapEnvelope:!1},this.cfg),n,r)}async createProjectUpdate(e,t){return AG(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return AG(await P({method:`PATCH`,path:`/api/cmmd/projects/${e}/updates/${t}`,body:n},this.cfg))}async deleteProjectUpdate(e,t){await P({method:`DELETE`,path:`/api/cmmd/projects/${e}/updates/${t}`},this.cfg)}async listProjectMilestones(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/milestones`},this.cfg)}async createProjectMilestone(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/milestones`,body:t},this.cfg)}async updateProjectMilestone(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/milestones/${t}`,body:n},this.cfg)}async deleteProjectMilestone(e,t){await P({method:`DELETE`,path:`/api/cmmd/projects/${e}/milestones/${t}`},this.cfg)}async improveProjectContent(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/content/readability`,body:t},this.cfg)}async listProjectBoard(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/board`},this.cfg)}async createProjectTaskDraft(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts`,body:t},this.cfg)}async getProjectTaskDraft(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/task-drafts/${t}`},this.cfg)}async updateProjectTaskDraft(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/task-drafts/${t}`,body:n},this.cfg)}async previewProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/preview`,body:n},this.cfg)}async commitProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/commit`,body:n},this.cfg)}async discardProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/discard`,body:n},this.cfg)}async getProjectTaskWorkflow(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/task-workflow`},this.cfg)}async updateProjectTaskWorkflow(e,t){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/task-workflow`,body:t},this.cfg)}async getProjectLeadPlan(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/plan`},this.cfg)}async activateProjectLeadAutomaticStaffing(e){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/authority/activate`,body:{}},this.cfg)}async getProjectLeadReadiness(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/readiness`},this.cfg)}async getProjectLeadCapabilities(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/capabilities`},this.cfg)}async getProjectLeadSummary(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/summary`},this.cfg)}async getProjectLeadDetail(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/detail`},this.cfg)}async getProjectLeadBriefing(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/briefing`},this.cfg)}async decideProjectLeadApproval(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/approvals/${t}/decision`,body:n},this.cfg)}async listProjectLeadEvents(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/events`,...t?{query:{...t.afterEventId===void 0?{}:{afterEventId:String(t.afterEventId)},...t.latest===void 0?{}:{latest:String(t.latest)},...t.limit===void 0?{}:{limit:String(t.limit)}}}:{}},this.cfg)}async explainProjectLead(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/explain`},this.cfg)}async pauseProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/pause`,body:t},this.cfg)}async resumeProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/resume`,body:t},this.cfg)}async reserveProjectLeadTask(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/tasks/${t}/reservations`,body:n},this.cfg)}async releaseProjectLeadReservation(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/reservations/${t}/release`,body:n},this.cfg)}async reconcileProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/reconcile`,body:t},this.cfg)}async resolveProjectLeadAttention(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/attention/${t}/resolve`,body:n},this.cfg)}async listCenterBoard(e){let t={};return e?.status&&(t.status=e.status),e?.workspaceId&&(t.workspaceId=String(e.workspaceId)),e?.campaignId&&(t.campaignId=String(e.campaignId)),e?.ownerId&&(t.ownerId=String(e.ownerId)),e?.includeArchived!==void 0&&(t.includeArchived=e.includeArchived),e?.q&&(t.q=e.q),P({method:`GET`,path:`/api/cmmd/work-items/board`,query:t},this.cfg)}async listForgeAutomationPresets(){return TG(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return TG(await P({method:`GET`,path:`/api/cmmd/automations/user/rules`},this.cfg),`rules`)}async createUserForgeAutomationRule(e){return P({method:`POST`,path:`/api/cmmd/automations/user/rules`,body:e},this.cfg)}async updateUserForgeAutomationRule(e,t){return P({method:`PATCH`,path:`/api/cmmd/automations/user/rules/${e}`,body:t},this.cfg)}async listUserForgeAutomationRuns(e){return TG(await P({method:`GET`,path:`/api/cmmd/automations/user/rules/${e}/runs`},this.cfg),`runs`)}async startUserForgeAutomationRun(e,t){return P({method:`POST`,path:`/api/cmmd/automations/user/rules/${e}/runs`,body:t},this.cfg)}async listForgeAutomationRules(e,t){let n=EG(t);return TG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/projects/${e}/rules`,body:t,...r?{query:r}:{}},this.cfg)}async updateForgeAutomationRule(e,t,n,r){let i=EG(r);return P({method:`PATCH`,path:`/api/cmmd/automations/projects/${e}/rules/${t}`,body:n,...i?{query:i}:{}},this.cfg)}async listForgeAutomationRuns(e,t){let n=EG(t,t?.taskId);return TG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=EG(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=EG(r);return P({method:`POST`,path:`/api/cmmd/automations/projects/${e}/tasks/${t}/runs`,body:n,...i?{query:i}:{}},this.cfg)}async retryForgeAutomationRun(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/retry`,body:t,...r?{query:r}:{}},this.cfg)}async cancelForgeAutomationRun(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/cancel`,body:t,...r?{query:r}:{}},this.cfg)}async approveForgeAutomationEscalation(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/escalations/approve`,body:t,...r?{query:r}:{}},this.cfg)}async rejectForgeAutomationEscalation(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/escalations/reject`,body:t,...r?{query:r}:{}},this.cfg)}async createProjectBoardTask(e,t){let n={title:t.title};return t.description!==void 0&&(n.description=t.description),t.priority!==void 0&&(n.priority=t.priority),t.status!==void 0&&(n.status=t.status),t.workflowStageId!==void 0&&(n.workflowStageId=t.workflowStageId),t.assignee!==void 0&&(n.assignee=t.assignee),t.dueDate!==void 0&&(n.dueDate=t.dueDate),t.workItemType!==void 0&&(n.workItemType=t.workItemType),t.parentTaskId!==void 0&&(n.parentTaskId=t.parentTaskId),t.milestoneId!==void 0&&(n.milestoneId=t.milestoneId),t.dependsOn!==void 0&&(n.dependsOn=t.dependsOn),P({method:`POST`,path:`/api/cmmd/projects/${e}/board`,body:n},this.cfg)}async createCenterBoardTask(e){let t={title:e.title,projectId:e.projectId};return e.description!==void 0&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),e.status!==void 0&&(t.status=e.status),e.assignee!==void 0&&(t.assignee=e.assignee),e.dueDate!==void 0&&(t.dueDate=e.dueDate),e.workItemType!==void 0&&(t.workItemType=e.workItemType),e.parentTaskId!==void 0&&(t.parentTaskId=e.parentTaskId),e.milestoneId!==void 0&&(t.milestoneId=e.milestoneId),e.dependsOn!==void 0&&(t.dependsOn=e.dependsOn),P({method:`POST`,path:`/api/cmmd/work-items/board`,body:t},this.cfg)}async submitFeedback(e){let t={type:e.type,title:e.title,source:e.source};return e.description!==void 0&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),e.senderName!==void 0&&(t.senderName=e.senderName),P({method:`POST`,path:`/api/cmmd/feedback`,body:t},this.cfg)}async updateProjectBoardTask(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}`,body:n},this.cfg)}async updateCenterBoardTask(e,t){return P({method:`PATCH`,path:`/api/cmmd/work-items/board/${e}`,body:t},this.cfg)}async moveCenterBoardTask(e,t){let n={toStatus:t.toStatus};return t.beforeTaskId!==void 0&&(n.beforeTaskId=t.beforeTaskId),t.afterTaskId!==void 0&&(n.afterTaskId=t.afterTaskId),P({method:`PATCH`,path:`/api/cmmd/work-items/board/${e}/move`,body:n},this.cfg)}async moveProjectBoardTask(e,t,n){let r={toStatus:n.toStatus};return n.toStageId!==void 0&&(r.toStageId=n.toStageId),n.beforeTaskId!==void 0&&(r.beforeTaskId=n.beforeTaskId),n.afterTaskId!==void 0&&(r.afterTaskId=n.afterTaskId),P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}/move`,body:r},this.cfg)}async archiveProjectBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/archive`},this.cfg)}async unarchiveProjectBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/unarchive`},this.cfg)}async updateProjectBoardTaskStatus(e,t,n,r){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}/status`,body:{status:n,...r?{workflowStageId:r}:{}}},this.cfg)}async listTaskExecutionOptions(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/board/${t}/execution-options`},this.cfg)}async createTaskWorkSession(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/work-sessions`,body:n},this.cfg)}async listProjectWorkSessions(e,t={}){return P({method:`GET`,path:`/api/cmmd/projects/${e}/work-sessions`,query:t},this.cfg)}async getWorkSession(e){return P({method:`GET`,path:`/api/cmmd/work-sessions/${e}`},this.cfg)}async updateWorkSessionStatus(e,t){return P({method:`PATCH`,path:`/api/cmmd/work-sessions/${e}`,body:{status:t}},this.cfg)}async attachWorkSessionThread(e,t){return P({method:`POST`,path:`/api/cmmd/work-sessions/${e}/threads`,body:t},this.cfg)}async listTaskConversations(e,t={}){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/conversations`,query:SG(t)},this.cfg)}async linkTaskConversation(e,t){return P({method:`POST`,path:`/api/cmmd/tasks/${e}/conversations`,body:t},this.cfg)}async getTaskHistory(e){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/history`},this.cfg)}async upsertTaskPullRequest(e,t){return P({method:`PUT`,path:`/api/cmmd/tasks/${e}/pull-requests`,body:t},this.cfg)}postPullRequest(e,t){return P({method:`POST`,path:`/api/cmmd/pull-requests/${e}`,body:t},this.cfg)}async listPullRequests(e){return this.postPullRequest(`list`,e)}async getPullRequestListStats(e){return this.postPullRequest(`list-stats`,e)}async getPullRequestDetail(e){return this.postPullRequest(`detail`,e)}async getPullRequestActivity(e){return this.postPullRequest(`activity`,e)}async getPullRequestDiff(e){return this.postPullRequest(`diff`,e)}async getPullRequestDiffFileContents(e){return this.postPullRequest(`diff-file-contents`,e)}async getPullRequestThreadComments(e){return this.postPullRequest(`thread/comments`,e)}async getPullRequestReviewerCandidates(e){return this.postPullRequest(`reviewer-candidates`,e)}async runPullRequestAction(e){return this.postPullRequest(`action`,e)}async createPullRequestComment(e){return this.postPullRequest(`comment`,e)}async updatePullRequest(e){return this.postPullRequest(`update`,e)}async updatePullRequestComment(e){return this.postPullRequest(`comment/update`,e)}async submitPullRequestReview(e){return this.postPullRequest(`review`,e)}async replyToPullRequestThread(e){return this.postPullRequest(`thread/reply`,e)}async setPullRequestThreadResolution(e){return this.postPullRequest(`thread/resolution`,e)}async requestPullRequestReviewers(e){return this.postPullRequest(`reviewers`,e)}async setPullRequestReaction(e){return this.postPullRequest(`reaction`,e)}async getTaskConversation(e,t,n={}){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/conversations/${encodeURIComponent(t)}`,query:SG(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new CG(`createSubtask`)}async createBoardTask(e){throw new CG(`createBoardTask`)}async createProject(e){let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=r);return e.campaignId!==void 0&&e.campaignId!==null&&(t.campaignId=LG(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=LG(e.organizationId)),iJe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:LG(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=LG(t.targetCampaignId)),t.dryRun!==void 0&&(n.dryRun=t.dryRun),P({method:`POST`,path:`/api/cmmd/projects/${e}/move`,body:n},this.cfg)}async uploadBrainDoc(e,t){throw new CG(`uploadBrainDoc`)}};function BG(e){return new zG(e)}var VG=new zG({onAuthExpired:mr}),HG=class extends Zt(`BootstrapHttpError`){},UG=e=>nee(e,`BootstrapHttpError`);function WG(e){return typeof e!=`object`||!e?!1:!!(UG(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof hr&&e.kind===`auth`)}function aJe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function GG(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new HG({message:`${t} returned a non-JSON response (${aJe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function KG(e={resolveUrl:ar}){let t=pr()?.bearerToken;return t?{...e,bearerToken:t}:e}var qG=null,JG=null,YG=null,XG=new Set,ZG=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function oJe(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();cG({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),_G({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function QG(){if(typeof window>`u`||YG)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(YG=e(e=>{qG=null,JG=null,e.sessionLifecycle.status!==`ready`&&cG(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&jne().catch(e=>{lG(e,{route:`desktop-auth-session-expired`})})}))}function sJe(){return Ul(new URL(window.location.href))}function $G(){let e=new URL(window.location.href),t=vle(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function cJe(){return cK(async()=>{let e=ar(`/api/auth/session`),t=async()=>{let t=await fetch(e,lr({credentials:`include`}));if(!t.ok)throw new HG({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return GG(t,e)},n=await t();return!n.authenticated&&n.auth.sessionMethods.length===1&&n.auth.sessionMethods[0]===`proxy-asserted`&&typeof window<`u`&&!window.desktopBridge&&e.startsWith(`https://`)&&await Nne()?t():n})}async function lJe(e,t){return await e.text()||t}var eK=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function uJe(e){return cK(async()=>{let t={credential:e},n=ar(`/api/auth/bootstrap`),r=await fetch(n,lr({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new HG({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return GG(r,n)})}function tK(e){return new URL(e,window.location.origin).toString()}function nK(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function rK(){return typeof window>`u`?null:nK(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function dJe(){return typeof window>`u`?!1:Pne()===`session-expired`}function iK(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(ZG),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function aK(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(ZG);return}window.sessionStorage.setItem(ZG,JSON.stringify([...e]))}catch{}}function fJe(){let e=rK();if(!e)return;let t=new Set(iK());t.add(e),aK(t)}function pJe(e){return iK().has(e)}function oK(){let e=rK();if(!e){aK(new Set);return}let t=new Set(iK());t.delete(e),aK(t)}async function sK(){let e=tK(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?GG(t,e):null}async function mJe(e){if(typeof window>`u`)return;let t=nK(e);if(!t||dJe()||XG.has(t)||pJe(t))return;if((await sK().catch(()=>null))?.authenticated){XG.add(t);return}let n=tK(`/api/auth/bootstrap`),r=await fetch(n,{body:JSON.stringify({credential:t}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`});if(!r.ok){if(r.status===401)return;throw new HG({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await GG(r,n),XG.add(t)}async function hJe(){let e=await cJe();if(e.authenticated)return e;let t=pr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await sK().catch(()=>null);return n?.authenticated?n:e}var gJe=new Set([404,502,503,504]),_Je=15e3,vJe=500;function yJe(e){pr()?.source===`paired-bearer`&&WG(e)&&ur(`http`)}async function cK(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(yJe(e),!xJe(e))throw e;if(Date.now()-t>=_Je)throw lG(e,{route:`bootstrap-retry-exhausted`}),e;await bJe(vJe)}}function bJe(e){return new Promise(t=>{setTimeout(t,e)})}function xJe(e){return UG(e)?gJe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function SJe(e,t){return e.sessionLifecycle.status===`ready`?e.sessionLifecycle.principalId!==t.id||e.cmmd.identity?.id!==t.id?`desktop-principal-mismatch`:null:`desktop-session-required`}async function CJe(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return SJe(await t(),e)}catch(e){return lG(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function wJe(e,t){return cG(null),Mne(t),await or().catch(e=>{lG(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Fne(t)??`Forge Desktop requires CMMD authentication.`}}async function TJe(){let e=await hJe();if(e.authenticated){if(e.cmmdIdentity){let t=await CJe(e.cmmdIdentity);return t?(dr(),wJe(e,t)):(dr(),oJe(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function EJe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);JG=null,oK(),await uJe(t),qG=null,$G()}function lK(){oK(),JG=null,qG=null}async function uK(e,t,n){let r=e.trim();if(!r)throw Error(`CMMD (Command) OAuth did not return an access token.`);let i=n?.refreshToken?.trim(),a=n?.mcpToken?.trim(),o=ar(`/api/auth/bootstrap/command`),s=await fetch(o,lr({body:JSON.stringify({accessToken:r,...i?{refreshToken:i}:{},...a?{mcpToken:a}:{},...t===void 0?{}:{user:t}}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!s.ok)throw new HG({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await GG(s,o),lK()}async function DJe(){let e=ar(`/api/auth/ws-token`),t=await fetch(e,lr({credentials:`include`,method:`POST`}));if(!t.ok)throw new HG({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return GG(t,e)}async function OJe(e){let t=await DJe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function kJe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=ar(`/api/auth/pairing-token`),a=await fetch(i,lr({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await lJe(a,`Failed to create pairing credential (${a.status}).`));return GG(a,i)}async function AJe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new HG({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return jJe(await GG(t,e))}function jJe(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=MJe(e.cmmdIdentity??null);return t?{displayName:t,email:e.cmmdIdentity?.email??null,avatarUrl:e.cmmdIdentity?.avatarUrl??null,role:e.role,verified:!0,source:`cmmd-identity`}:{displayName:`CMMD identity unavailable`,email:null,avatarUrl:null,role:e.role,verified:!1,source:`fallback`}}function MJe(e){return e&&([e.firstName,e.lastName].map(e=>e?.trim()??``).filter(e=>e.length>0).join(` `)||e.username.trim()||e.email.trim())||null}async function NJe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},KG())}catch(e){throw e instanceof hr&&e.kind!==`auth`&&e.code!==null&&eK.has(e.code)?new hr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}if(!n)throw Error(`Invalid response from ${t}`);return n}async function PJe(e={}){return NJe(e.forceFresh===!0)}async function dK(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},KG())}catch(e){throw e instanceof hr&&e.kind!==`auth`&&e.code!==null&&eK.has(e.code)?new hr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function FJe(e){try{return await dK(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof hr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof hr||t instanceof Error)return dK(`/api/command/tasks/update`,e);throw t}}async function IJe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function LJe(){let e=await Promise.allSettled([or(),IJe()]);cG(null),fJe(),qG=null,JG=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function RJe(){if(QG(),JG?.status===`authenticated`)return dr(),JG;if(qG)return qG;let e=fK();return qG=e,e.then(e=>(e.status===`authenticated`&&(JG=e),e)).finally(()=>{qG===e&&(qG=null)})}async function fK(){return cr().then(e=>mJe(e)).then(()=>TJe())}async function zJe(){QG(),qG=null,JG=null;let e=await fK();return e.status===`authenticated`&&(JG=e,dr()),e}function BJe(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function VJe(e){let t=BJe(e).replace(/-/g,`+`).replace(/_/g,`/`);return`-----BEGIN PUBLIC KEY-----\n${((t+`=`.repeat((4-t.length%4)%4)).match(/.{1,64}/gu)??[]).join(`
1005
+ If init has been called in the preload and contextIsolation is disabled, is not required to call init in the renderer`);return}window.__SENTRY__RENDERER_INIT__=!0,e.sendClientReports=!1,e.defaultIntegrations===void 0&&(e.defaultIntegrations=VW(e)),e.stackParser===void 0&&(e.stackParser=LW),e.ipcNamespace===void 0&&(e.ipcNamespace=`sentry-ipc`),e.dsn===void 0&&(e.dsn=`https://12345@dummy.dsn/12345`),e.transport===void 0&&(e.transport=BW),delete e.initialScope,t(e)}var UW=e({BrowserClient:()=>vR,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>TMe,OpenFeatureIntegrationHook:()=>EKe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>pA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>mA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>fA,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>dA,Scope:()=>Yk,addBreadcrumb:()=>qN,addEventProcessor:()=>IM,addIntegration:()=>KM,bindScopeToEmitter:()=>$Ae,breadcrumbsIntegration:()=>Yz,browserApiErrorsIntegration:()=>Xz,browserProfilingIntegration:()=>_Ke,browserSessionIntegration:()=>Qz,browserTracingIntegration:()=>aW,buildLaunchDarklyFlagUsedHandler:()=>wKe,captureConsoleIntegration:()=>eNe,captureEvent:()=>jM,captureException:()=>kM,captureFeedback:()=>MP,captureMessage:()=>AM,captureSession:()=>BM,chromeStackLineParser:()=>Kz,consoleLoggingIntegration:()=>oPe,contextLinesIntegration:()=>sVe,continueTrace:()=>BAe,createConsolaReporter:()=>lPe,createLangChainCallbackHandler:()=>oI,createTransport:()=>mN,createUserFeedbackEnvelope:()=>dBe,dedupeIntegration:()=>pP,defaultRequestInstrumentationOptions:()=>YU,defaultStackParser:()=>LW,elementTimingIntegration:()=>Eze,endSession:()=>RM,eventFiltersIntegration:()=>XN,eventFromException:()=>mR,eventFromMessage:()=>hR,eventLoopBlockIntegration:()=>zKe,exceptionFromError:()=>uR,extraErrorDataIntegration:()=>sNe,featureFlagsIntegration:()=>qNe,feedbackAsyncIntegration:()=>lRe,feedbackIntegration:()=>lR,feedbackSyncIntegration:()=>lR,fetchStreamPerformanceIntegration:()=>eW,forceLoad:()=>UBe,functionToStringIntegration:()=>YN,getAbsoluteUrl:()=>Xze,getActiveSpan:()=>uj,getClient:()=>X,getCurrentScope:()=>oA,getDefaultIntegrations:()=>VW,getFeedback:()=>gLe,getGlobalScope:()=>cA,getIsolationScope:()=>sA,getReplay:()=>rGe,getRootSpan:()=>cj,getSpanDescendants:()=>sj,getSpanStatusFromHttpCode:()=>xA,getTraceData:()=>KN,globalHandlersIntegration:()=>eB,graphqlClientIntegration:()=>hVe,growthbookIntegration:()=>kKe,httpClientIntegration:()=>YBe,httpContextIntegration:()=>aB,inboundFiltersIntegration:()=>ZN,init:()=>HW,instrumentAnthropicAiClient:()=>TFe,instrumentCreateReactAgent:()=>lIe,instrumentGoogleGenAIClient:()=>LFe,instrumentLangChainEmbeddings:()=>QFe,instrumentLangGraph:()=>uIe,instrumentOpenAiClient:()=>oFe,instrumentOutgoingRequests:()=>XU,instrumentSupabaseClient:()=>DNe,isBotUserAgent:()=>iW,isEnabled:()=>FM,isInitialized:()=>Fje,lastEventId:()=>PM,launchDarklyIntegration:()=>CKe,linkedErrorsIntegration:()=>oB,logger:()=>MIe,makeRendererTransport:()=>BW,metrics:()=>zIe,moduleMetadataIntegration:()=>ZMe,normalizeStringifyValue:()=>sB,onLoad:()=>WBe,openFeatureIntegration:()=>TKe,parameterize:()=>GN,registerSpanErrorInstrumentation:()=>pj,registerWebWorker:()=>PKe,replayCanvasIntegration:()=>SGe,replayIntegration:()=>yU,reportPageLoaded:()=>WGe,reportingObserverIntegration:()=>qBe,rewriteFramesIntegration:()=>hNe,scopeToMainIntegration:()=>zW,sendFeedback:()=>BI,setActiveSpanInBrowser:()=>GGe,setAttribute:()=>Nje,setAttributes:()=>Mje,setContext:()=>MM,setConversationId:()=>Pje,setCurrentClient:()=>NN,setExtra:()=>kje,setExtras:()=>Oje,setHttpStatus:()=>SA,setMeasurement:()=>Fj,setTag:()=>jje,setTags:()=>Aje,setUser:()=>NM,showReportDialog:()=>lB,spanStreamingIntegration:()=>KGe,spanToBaggageHeader:()=>SAe,spanToJSON:()=>JA,spanToTraceHeader:()=>UA,spotlightBrowserIntegration:()=>SKe,startBrowserTracingNavigationSpan:()=>sW,startBrowserTracingPageLoadSpan:()=>oW,startInactiveSpan:()=>qj,startNewTrace:()=>Xj,startSession:()=>LM,startSpan:()=>Gj,startSpanManual:()=>Kj,statsigIntegration:()=>AKe,supabaseIntegration:()=>ANe,suppressTracing:()=>VAe,thirdPartyErrorFilterIntegration:()=>zNe,uiProfiler:()=>tBe,unleashIntegration:()=>DKe,updateSpanName:()=>_Ae,viewHierarchyIntegration:()=>gVe,webVitalsIntegration:()=>tW,webWorkerIntegration:()=>MKe,withActiveSpan:()=>Jj,withIsolationScope:()=>Bke,withScope:()=>lA,withStreamedSpan:()=>CAe,zodErrorsIntegration:()=>RNe}),VKe=100,HKe=5,UKe=[`ResizeObserver loop completed with undelivered notifications.`,`ResizeObserver loop limit exceeded`,`AbortError`,`The user aborted a request.`,`Network request failed`,`NetworkError when attempting to fetch resource.`,`Failed to fetch`,`ChunkLoadError`,`Loading chunk`,`Loading CSS chunk`,`Non-Error promise rejection captured with value: Object Not Found Matching Id`];function WW(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function WKe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),WW(e.extra),WW(e.tags)}function GKe(e){let t=KW(e.version)??`0.0.0`,n=KW(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function GW(e,t){for(let n of t){let t=KW(e[n]);if(t)return t}}function KKe(e){return qW(e.enabled)??e.defaultEnabled??!1}function qKe(e){let t=KW(e.dsn);return!t||KKe(e)===!1?null:{dsn:t,environment:KW(e.environment)??KW(e.defaultEnvironment)??`production`,release:KW(e.release)??KW(e.defaultRelease)??void 0,debug:qW(e.debug)??e.defaultDebug??!1,tracesSampleRate:YW(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:JW(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:JW(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:JW(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:VKe,normalizeDepth:HKe,tags:JKe(e)}}function JKe(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=KW(r);e&&(t[n]=e)}return t}function KW(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function qW(e){if(typeof e==`boolean`)return e;let t=KW(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function JW(e,t){if(t!==void 0||e!==void 0)return YW(e,t??0)}function YW(e,t){let n=YKe(e);return n===null||n<0||n>1?t:n}function YKe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=KW(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}function XKe(e){let t=(0,ol.c)(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=Yt(pl,`bg-background text-foreground`),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=Yt(dl,`pl-1 md:pl-2.5`),t[1]=r):r=t[1];let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Mr.jsx)(hl,{}),t[2]=i):i=t[2];let a;t[3]===e.onGoToNewChat?a=t[4]:(a=(0,Mr.jsx)(`div`,{className:r,children:(0,Mr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:e.onGoToNewChat,className:`${fl} hover:bg-accent/70`,children:i})}),t[3]=e.onGoToNewChat,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Mr.jsx)(`div`,{}),t[5]=o):o=t[5];let s;t[6]===a?s=t[7]:(s=(0,Mr.jsxs)(`header`,{className:ul,children:[a,o]}),t[6]=a,t[7]=s);let c;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Mr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Mr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Mr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Mr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Mr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:ZKe,type:`button`,children:`Reload app`})]})}),t[8]=c):c=t[8];let l;return t[9]===s?l=t[10]:(l=(0,Mr.jsxs)(`div`,{className:n,children:[s,c]}),t[9]=s,t[10]=l),l}function ZKe(){return window.location.reload()}var QKe=[/\bDeepSeek\b/i,/\bKimi\b/i,/\bMoonshot\b/i,/\bdeepseek[-._a-z0-9]*\b/i,/\bkimi[-._a-z0-9]*\b/i,/\bmoonshot[-._a-z0-9]*\b/i,/\bAPEX_API_KEY\b/,/\bDEEPSEEK_API_KEY\b/,/\bKIMI_API_KEY\b/,/\bOPENAI_API_KEY\b/,/\bANTHROPIC_API_KEY\b/,/\bCURSOR_API_KEY\b/,/\bOPENCODE_API_KEY\b/,/\bforge_proxy_[A-Za-z0-9._-]+\b/,/\bProviderValidationError\b/,/\/forge-server\/node_modules\//,/https?:\/\/[^\s'"<>)]*\/api\/provider-egress\/[^\s'"<>)]*/i,/https?:\/\/[^\s'"<>)]*(?:apex|deepseek|moonshot|kimi)[^\s'"<>)]*/i],$Ke=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function XW(e){if(!e)return!1;let t=e.toLowerCase();return/\b(rate[\s-]?limit|too\s+many\s+requests|usage[ _-]limit|usage_limit_reached|quota|insufficient_quota)\b/.test(t)||/\b429\b/.test(t)}function eqe(e){return/\bbound to provider account\b/.test(e)&&/\bcannot use provider account\b/.test(e)?`Forge could not switch this conversation to the selected AI account. Retry the account switch.`:/\bforge_runtime_repairing\b/.test(e)||/\bthis turn was interrupted because the environment is being repaired\b/.test(e)?`This turn was interrupted because the environment is being repaired. Retry after the repair finishes.`:/\bforge_runtime_stopped\b/.test(e)||/\bthis turn was interrupted because the environment was stopped\b/.test(e)?`This turn was interrupted because the environment was stopped. Start the environment and retry.`:null}function tqe(e){if(!e)return null;let t=e.toLowerCase(),n=eqe(t);return n===null?/\bforge_provider_model_not_allowed\b/.test(t)||/\bnot\s+scoped\s+to\s+the\s+requested\s+model\b/.test(t)?`The workspace AI credential does not cover the model this turn asked for. Retry, or pick that model for the thread.`:/\bmodel\b[\s\S]*\b(not\s+(found|available|supported)|does\s+not\s+exist|unsupported|invalid|unknown)\b/.test(t)||/\b(unsupported|unknown|invalid)\b[\s\S]*\bmodel\b/.test(t)||/\b(model_not_found|invalid_model|model_not_supported)\b/.test(t)?`The selected model isn't available right now. Pick a different model and retry.`:XW(t)?`The AI service is rate-limited or out of quota. Wait a moment and retry.`:/\b(unauthorized|forbidden|authentication\s+(failed|error|required)|invalid\s+api\s+key|expired\s+(token|credential))\b/.test(t)||/\b40[13]\b/.test(t)?`Workspace AI authentication failed. Reconnect the workspace and retry.`:/\b(timed?\s*out|timeout|overloaded|service\s+unavailable)\b/.test(t)||/\b50[234]\b/.test(t)?`The AI service is temporarily overloaded. Retry in a moment.`:null:n}function nqe(e){return e?QKe.some(t=>t.test(e)):!1}function ZW(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:nqe(n)?tqe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var rqe=[/\bSocketCloseError\b/i,/\bSocketOpenError\b/i,/\bSocketReadError\b/i,/\bRpcClientDefect:\s*Unknown socket error\b/i,/Unable to connect to the Forge server WebSocket\./i,/\bping timeout\b/i];function QW(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&rqe.some(e=>e.test(t))}function $W(e){return QW(e)?null:ZW(e,{fallback:$Ke})}var iqe=[/^Transport disposed$/,/WebSocket RPC request timed out after \d+ms\./],aqe=`Lost the connection to this Environment. Your message was not sent.`;function oqe(e){return e instanceof Error?QW(e.message)||iqe.some(t=>t.test(e.message.trim()))?aqe:e.message:`Failed to send message.`}var eG=`forge-web`,tG=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],nG=[`VITE_SENTRY_RELEASE`],sqe=[`VITE_SENTRY_DSN`],cqe=[`VITE_SENTRY_DEBUG`],lqe=[`VITE_SENTRY_ENABLED`],uqe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],dqe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],fqe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],pqe=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],mqe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],rG=!1,iG={autoInject:!1,colorScheme:`system`,formTitle:`Report a Bug`,themeLight:{accentBackground:`oklch(0.52 0.19 48)`,accentForeground:`#ffffff`,background:`#ffffff`,boxShadow:`0 24px 80px rgba(0, 0, 0, 0.18)`,foreground:`#262626`,outline:`1px solid oklch(0.52 0.19 48)`},themeDark:{accentBackground:`oklch(0.62 0.2 47)`,accentForeground:`#ffffff`,background:`#171717`,boxShadow:`0 24px 80px rgba(0, 0, 0, 0.45)`,foreground:`#f5f5f5`,outline:`1px solid oklch(0.62 0.2 47)`}};function hqe(e){let t=e.exception&&typeof e.exception==`object`&&`values`in e.exception&&Array.isArray(e.exception.values)?e.exception.values:[];return[typeof e.title==`string`?e.title:void 0,...t.flatMap(e=>{if(typeof e!=`object`||!e)return[];let t=e;return[typeof t.type==`string`?t.type:void 0,typeof t.value==`string`?t.value:void 0]})]}function gqe(e){return(e.exception&&typeof e.exception==`object`&&`values`in e.exception&&Array.isArray(e.exception.values)?e.exception.values:[]).some(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.value!=`string`||!/All fibers interrupted without error/i.test(t.value)?!1:t.stacktrace?.frames?.some(e=>{let t=typeof e.filename==`string`?e.filename:``,n=typeof e.function==`string`?e.function:``;return t.includes(`src/rpc/wsTransport.ts`)&&n===`WsTransport.request`})})}function _qe(e){return hqe(e).some(QW)||gqe(e)}function vqe(){let e=new URL(window.location.href);Nr?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function yqe(){let e=Nr?`electron-renderer`:`browser`,t={APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`3c1016247a3dd875ae36f6c99f417e28049ae9c7`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+3c1016247a3dd875ae36f6c99f417e28049ae9c7`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=GW(t,[...nG])??GKe({appName:eG,version:`0.13.4`,commitHash:GW(t,[...mqe])});return qKe({appName:eG,runtime:e,defaultEnvironment:GW(t,[...tG])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:GW(t,[...lqe]),dsn:GW(t,[...sqe]),environment:GW(t,[...tG]),release:GW(t,[...nG]),debug:GW(t,[...cqe]),tracesSampleRate:GW(t,[...uqe]),profilesSampleRate:GW(t,[...dqe]),replaysSessionSampleRate:GW(t,[...fqe]),replaysOnErrorSampleRate:GW(t,[...pqe]),tags:{platform:Nr?`desktop`:`web`}})}function aG(e){return WKe(e),_qe(e)?null:e}function bqe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function oG(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...UKe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...bqe(e)}}function xqe(e){let t=[];e.tracesSampleRate>0&&t.push(aW()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(yU());let n=lR(iG);t.push(n);try{HW({...oG(e),beforeSend:e=>aG(e),integrations:t})}catch{return null}return rG=!0,UW}function Sqe(e){let t=[];e.tracesSampleRate>0&&t.push(cE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(ST());let n=ab(iG);t.push(n);try{HE({...oG(e),beforeSend:e=>aG(e),integrations:t})}catch{return null}return rG=!0,gO}function sG(){if(rG)return Nr?UW:gO;let e=yqe();return e?Nr?xqe(e):Sqe(e):null}function cG(e){if(sG()){if(Nr){NM(e);return}wm(e)}}function lG(e,t,n){if(!sG())return;let r=Cqe(e);if(Nr){lA(e=>{t&&e.setTags(t);let i=kM(r);n?.showReportDialog&&lB({eventId:i})});return}Vd(e=>{t&&e.setTags(t);let i=bm(r);n?.showReportDialog&&dS({eventId:i})})}function Cqe(e){if(e instanceof Error)return e;if(typeof e==`string`&&e.trim().length>0)return Error(e);try{return Error(JSON.stringify(e))}catch{return Error(`Unknown non-Error exception`)}}var wqe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){lG(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Mr.jsx)(XKe,{onGoToNewChat:vqe}):this.props.children}},uG=!1,dG=!1,fG=null,pG=null,mG=null,hG=!1,gG=new Set;function Tqe(e){if(uG||dG)return;if(!e.publicKey||!e.host){dG=!0;return}if(fG)return;if(typeof window>`u`||typeof location>`u`){dG=!0;return}let t=e.publicKey,n=e.host;fG=N(async()=>{let{default:e}=await import(`./module-CPO4cjSm.js`);return{default:e}},[]).then(({default:e})=>{pG=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{uG=!0,mG&&_G(mG),vG(),gG.forEach(e=>e())}})}).catch(()=>{dG=!0,pG=null})}function _G(e){if(mG=e,!uG||!pG)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),pG.identify(e.cmmdUserId,t)}function Eqe(e){return!uG||!pG?!1:pG.isFeatureEnabled(e)===!0}function vG(){!pG||hG||(hG=!0,pG.onFeatureFlags(()=>{gG.forEach(e=>e())}))}function Dqe(e){return gG.add(e),uG&&pG&&(vG(),e()),()=>{gG.delete(e)}}var yG=`/api/cmmd/auth-runtime`;function Oqe(e){return P({method:`POST`,path:yG},e)}function kqe(e){return P({method:`GET`,path:yG},e)}function Aqe(e){return P({method:`DELETE`,path:yG},e)}function jqe(e){return P({method:`POST`,path:`${yG}/connect`},e)}function Mqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing`,...t?.organizationId===void 0?{}:{query:{orgId:t.organizationId}}},e)}function Nqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:t.timeZone}},e)}var bG=`/api/cmmd/providers/codex/credential`,xG=`/api/cmmd/providers/claude/credential`;function Pqe(e){return P({method:`GET`,path:bG},e)}function Fqe(e){return P({method:`DELETE`,path:bG},e)}function Iqe(e){return P({method:`GET`,path:xG},e)}function Lqe(e){return P({method:`DELETE`,path:xG},e)}function Rqe(e,t){return P({method:`DELETE`,path:`/api/cmmd/providers/accounts/${encodeURIComponent(String(t))}`},e)}function zqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/disposition`}function Bqe(e,t,n,r,i){return P({method:`PUT`,path:zqe(t,n,r),body:i},e)}function Vqe(e){return(t,n,r,i)=>Bqe(e,t,n,r,i)}function Hqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/archive`}function Uqe(e,t,n,r,i){return P({method:`POST`,path:Hqe(t,n,r),body:i},e)}function Wqe(e){return(t,n,r,i)=>Uqe(e,t,n,r,i)}function Gqe(e){return typeof e==`object`&&!!e&&`status`in e&&e.status===409}async function Kqe(e){let t={action:e.action,...e.operationId===void 0?{}:{operationId:e.operationId},expectedRevision:e.expectedRevision,force:e.force};try{return await e.submit(t)}catch(n){if(!Gqe(n))throw n;let r=await e.refresh();return e.submit({...t,expectedRevision:r.revision})}}function qqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/forge-runtimes/${encodeURIComponent(t)}/rename`,body:{displayName:n}},e)}function Jqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/rename`,body:{displayName:n}},e)}function Yqe(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/revoke`},e)}function SG(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var Xqe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},Zqe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},CG=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function wG(e,t){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let n=e[t];if(Array.isArray(n))return n}return[]}function TG(e,t){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let n=e[t];if(Array.isArray(n))return n}return[]}function EG(e,t){let n={};return e?.organizationId&&(n.orgId=e.organizationId),t!==void 0&&(n.taskId=String(t)),Object.keys(n).length>0?n:void 0}function DG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():null}function Qqe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function OG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():typeof n==`number`&&Number.isFinite(n)?String(n):null}function kG(e){let t=`${DG(e,`firstName`)??``} ${DG(e,`lastName`)??``}`.trim()||DG(e,`username`)||DG(e,`email`)||`Unknown`;return{id:OG(e,`userId`)??OG(e,`id`)??t,name:t,email:DG(e,`email`),role:DG(e,`role`),avatarUrl:DG(e,`profileImage`)??DG(e,`avatar`)}}function $qe(e){let t=jG(e,`user`)??e;return kG({...typeof t==`object`&&t?t:{},userId:OG(e,`userId`)??OG(t,`id`),role:DG(e,`role`)})}function AG(e){let t=DG(e,`authorFirstName`)??``,n=DG(e,`authorLastName`)??``,r=DG(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:OG(e,`id`)??``,status:i,body:DG(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:DG(e,`authorProfileImage`)??null,createdAt:DG(e,`createdAt`)??``,updatedAt:DG(e,`updatedAt`)??DG(e,`createdAt`)??``,canEdit:Qqe(e,`canEdit`)??!1}}function eJe(e,t,n){let r=Array.isArray(e.data)?e.data.map(AG):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function jG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var tJe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function MG(e,t){let n=jG(e,t);if(!n)return null;for(let e of tJe){let t=DG(n,e);if(t)return t}return null}function NG(e,t){let n=jG(e,t);return n?OG(n,`id`):null}function PG(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function nJe(e){let t={...e,id:OG(e,`id`)??e.id,title:e.title??DG(e,`name`)??``},n=OG(e,`workspaceId`)??OG(e,`workspace_id`)??NG(e,`workspace`)??e.workspaceId??null;return n!==null||PG(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??DG(e,`start_date`)??null,endDate:e.endDate??DG(e,`end_date`)??null}:t}function FG(e){let t=e.ownerAvatarUrl??DG(e,`owner_avatar_url`)??DG(e,`ownerProfileImage`)??DG(e,`owner_profile_image`)??DG(e,`ownerImage`)??DG(e,`owner_image`)??DG(e,`ownerImageUrl`)??DG(e,`owner_image_url`)??DG(e,`createdByAvatarUrl`)??DG(e,`created_by_avatar_url`)??DG(e,`createdByProfileImage`)??DG(e,`created_by_profile_image`)??MG(e,`owner`)??MG(e,`createdBy`)??MG(e,`created_by`)??null,n={...e,id:OG(e,`id`)??e.id},r=OG(e,`campaignId`)??OG(e,`campaign_id`)??NG(e,`campaign`)??e.campaignId??null;(r!==null||PG(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??DG(e,`campaignTitle`)??DG(e,`campaign_title`)??DG(jG(e,`campaign`),`title`)??DG(jG(e,`campaign`),`name`)??null;(i!==null||PG(e,`campaignTitle`))&&(n.campaignTitle=i);let a=OG(e,`workspaceId`)??OG(e,`workspace_id`)??NG(e,`workspace`)??e.workspaceId??null;(a!==null||PG(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??DG(e,`workspace_name`)??DG(jG(e,`workspace`),`name`)??null;(o!==null||PG(e,`workspaceName`))&&(n.workspaceName=o);let s=DG(e,`workspaceIconUrl`)??DG(e,`workspace_icon_url`)??DG(jG(e,`workspace`),`iconUrl`)??null;(s!==null||PG(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=OG(e,`ownerId`)??OG(e,`owner_id`)??NG(e,`owner`)??e.ownerId??null;(c!==null||PG(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??DG(e,`owner_name`)??DG(jG(e,`owner`),`name`)??null;(l!==null||PG(e,`ownerName`))&&(n.ownerName=l),(t!==null||PG(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=OG(e,`teamId`)??OG(e,`team_id`)??NG(e,`team`)??e.teamId??null;(u!==null||PG(e,`teamId`))&&(n.teamId=u);let d=e.teamName??DG(e,`team_name`)??DG(jG(e,`team`),`name`)??null;(d!==null||PG(e,`teamName`))&&(n.teamName=d);let f=e.startDate??DG(e,`start_date`)??null;(f!==null||PG(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??DG(e,`target_end_date`)??null;return(p!==null||PG(e,`targetEndDate`))&&(n.targetEndDate=p),n}function IG(e){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let t=e;if(Array.isArray(t.items))return t.items;if(Array.isArray(t.results))return t.results}return[]}function rJe(e){return IG(e).flatMap(e=>{let t=e,n=typeof t.id==`number`?t.id:null,r=typeof t.name==`string`?t.name:null;if(n===null||r===null)return[];let i=e=>typeof t[e]==`string`?t[e]:null;return[{id:n,name:r,startDate:i(`startDate`),endDate:i(`endDate`),status:i(`status`)}]})}function iJe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function LG(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function RG(e){try{return await e}catch(e){throw e instanceof hr?e.kind===`auth`?new Xqe(e.message):new Zqe(e.message,e.status??502):e}}var zG=class e{cfg;putThreadDisposition;postThreadArchive;commentEditIdempotencyKeys=new Map;commentDeleteIdempotencyKeys=new Map;constructor(e={}){let t=e.forgeOrigin===void 0,n=e.forgeOrigin??`http://localhost:13773`;this.cfg={resolveUrl:t?ar:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??mr,...t?{resolveBearerToken:()=>pr()?.bearerToken??null}:{}},this.putThreadDisposition=Vqe(this.cfg),this.postThreadArchive=Wqe(this.cfg)}async getTask(e){return RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}`},this.cfg))}async getForgeTaskDetail(e){return P({method:`GET`,path:`/api/cmmd/tasks/${e}`},this.cfg)}async searchTasks(e){let t={q:e.q};return e.status&&(t.status=e.status),e.limit!==void 0&&(t.limit=e.limit),e.projectId&&(t.projectId=e.projectId),(await RG(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await RG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await RG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return RG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return RG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return RG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await RG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return RG(P({method:`GET`,path:`/api/cmmd/organizations/${e}/members`},this.cfg))}async getWebSocketToken(e){return P({method:`GET`,path:`/api/cmmd/ws-token`,...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async getProjectComments(e,t){let n={};return t?.organizationId&&(n.organizationId=t.organizationId),(await P({method:`GET`,path:`/api/cmmd/projects/${e}/comments`,query:n},this.cfg))?.comments??[]}async getProjectLink(e){return P({method:`GET`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd}},this.cfg)}async listProjectLinks(){return P({method:`GET`,path:`/.well-known/forge/project-links`,suppressBearerToken:!0},this.cfg)}async listProjectContextLinks(e){let t={};e.environmentId&&(t.forgeEnvironmentId=e.environmentId),e.projectId&&(t.forgeProjectId=e.projectId),e.githubRepoFullName&&(t.githubRepoFullName=e.githubRepoFullName),e.cmmdOrganizationId&&(t.cmmdOrganizationId=e.cmmdOrganizationId);let n=await P({method:`GET`,path:`/.well-known/forge/cmmd/project-links`,query:t},this.cfg),r=tn(vne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return IG(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return rJe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return IG(await P({method:`GET`,path:`/.well-known/forge/cmmd/projects`,query:{campaignId:e.campaignId}},this.cfg))}async updateTask(e,t){let n={taskId:e};return t.title!==void 0&&(n.title=t.title),t.description!==void 0&&(n.description=t.description),t.status!==void 0&&(n.status=t.status),t.priority!==void 0&&(n.priority=t.priority),t.dueDate!==void 0&&(n.dueDate=t.dueDate),t.assigneeId!==void 0&&(n.assigneeId=t.assigneeId),t.labels!==void 0&&(n.labels=t.labels),RG(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return RG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e.entityId,content:e.content}},this.cfg))}async updateComment(e,t,n){let r=`${e}:${t}:${n}`,i=this.commentEditIdempotencyKeys.get(r)??crypto.randomUUID();this.commentEditIdempotencyKeys.set(r,i);let a=await RG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${t}`,body:{content:n,idempotencyKey:i}},this.cfg));return this.commentEditIdempotencyKeys.delete(r),a}async deleteComment(e,t){let n=`${e}:${t}`,r=this.commentDeleteIdempotencyKeys.get(n)??crypto.randomUUID();this.commentDeleteIdempotencyKeys.set(n,r),await RG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${t}`,body:{idempotencyKey:r}},this.cfg)),this.commentDeleteIdempotencyKeys.delete(n)}async createProjectComment(e,t){let n=(await P({method:`POST`,path:`/api/cmmd/projects/${e}/comments`,body:{content:t.content,organizationId:t.organizationId??null}},this.cfg))?.comment;if(!n)throw new hr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of nne){let r=t[e];r!==void 0&&(n[e]=lne[e]===`nullableId`?LG(r):r)}await P({method:`PATCH`,path:`/api/cmmd/projects/${e}`,body:n},this.cfg)}async setProjectLink(e){await P({method:`POST`,path:`/.well-known/forge/project-link`,body:e},this.cfg)}async deleteProjectLink(e){await P({method:`DELETE`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd,...e.cmmdProjectId?{cmmdProjectId:e.cmmdProjectId}:{}}},this.cfg)}async createCmmdProject(e){return P({method:`POST`,path:`/.well-known/forge/cmmd/projects`,body:e},this.cfg)}async ensureGitHubProjectContext(e){return P({method:`POST`,path:`/.well-known/forge/cmmd/github-project-contexts/ensure`,body:e},this.cfg)}async createBrainDoc(e){return P({method:`POST`,path:`/api/cmmd/brain-docs`,body:e},this.cfg)}async uploadTaskAttachment(e,t){let n=new FormData;return n.append(`file`,t),RG(P({method:`POST`,path:`/api/cmmd/tasks/${e}/attachments`,form:n},this.cfg))}async archiveTask(e){await P({method:`POST`,path:`/api/cmmd/tasks/${e}/archive`},this.cfg)}async unarchiveTask(e){await P({method:`POST`,path:`/api/cmmd/tasks/${e}/unarchive`},this.cfg)}async getProfile(){return P({method:`GET`,path:`/api/cmmd/profile`},this.cfg)}async getUsageSummary(e){return P({method:`GET`,path:`/api/cmmd/usage/summary`,query:{sinceDay:e.sinceDay,untilDay:e.untilDay,timeZone:e.timeZone,...e.resolution===`hour`?{resolution:e.resolution,sinceTime:e.sinceTime,untilTime:e.untilTime}:{}}},this.cfg)}getBilling(e){return Mqe(this.cfg,e)}getBillingSeries(e){return Nqe(this.cfg,e)}async getBootstrap(){return P({method:`GET`,path:`/api/cmmd/bootstrap`},this.cfg)}async getForgeAccountPreferences(){return P({method:`GET`,path:`/api/cmmd/account/preferences`},this.cfg)}async updateForgeAccountPreferences(e){return P({method:`PATCH`,path:`/api/cmmd/account/preferences`,body:e},this.cfg)}async getOrgProviderPolicy(){return P({method:`GET`,path:`/api/cmmd/org/provider-policy`},this.cfg)}async listSavedDataViews(e){return P({method:`GET`,path:`/api/cmmd/saved-views`,query:{surface:e.surface,projectId:e.projectId}},this.cfg)}async createSavedDataView(e){return P({method:`POST`,path:`/api/cmmd/saved-views`,body:e},this.cfg)}async importSavedDataView(e){return P({method:`POST`,path:`/api/cmmd/saved-views/import`,body:e},this.cfg)}async updateSavedDataView(e,t){return P({method:`PATCH`,path:`/api/cmmd/saved-views/${encodeURIComponent(e)}`,body:t},this.cfg)}async deleteSavedDataView(e,t){return P({method:`DELETE`,path:`/api/cmmd/saved-views/${encodeURIComponent(e)}`,query:t},this.cfg)}async getDeviceRegistry(e){return P({method:`GET`,path:`/api/cmmd/devices`,...e?.projectId===void 0?{}:{query:{projectId:String(e.projectId)}},...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async registerDevice(e){return P({method:`POST`,path:`/api/cmmd/devices/register`,body:e},this.cfg)}async grantRuntimeAccess(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/access-grants`,body:t},this.cfg)}async revokeRuntimeAccess(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/access-grants/${encodeURIComponent(String(t))}/revoke`},this.cfg)}async issueRelayControlRoute(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/relay-routes`,body:t},this.cfg)}async issueRelayActionGrant(e,t){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/relay-action-grants`,body:t},this.cfg)}async getRuntimeInventory(e){let t={...e?.projectId===void 0?{}:{projectId:String(e.projectId)},...e?.allWorkspaces===!0?{allWorkspaces:`true`}:{}};return P({method:`GET`,path:`/api/cmmd/runtime-inventory`,...Object.keys(t).length>0?{query:t}:{}},this.cfg)}async getRuntimeDiagnostics(e){return P({method:`GET`,path:`/api/cmmd/runtime-diagnostics/v2/runtimes/${encodeURIComponent(e)}`},this.cfg)}async getCloudProjectLifecyclePreflight(e){return(await P({method:`GET`,path:`/api/cmmd/forge-cloud-projects/${encodeURIComponent(String(e))}/lifecycle-preflight`},this.cfg)).preflight}async replaceRuntimeInventory(e,t){return P({method:`PUT`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/inventory`,body:t},this.cfg)}static PROVIDER_ACCOUNTS_PATH=`/api/cmmd/providers/accounts`;static PROVIDER_USAGE_PATH=`/api/cmmd/providers/usage`;static PROVIDER_USAGE_REFRESH_PATH=`/api/cmmd/providers/usage/refresh`;provisionAuthRuntime(){return Oqe(this.cfg)}getAuthRuntimeState(){return kqe(this.cfg)}destroyAuthRuntime(){return Aqe(this.cfg)}connectAuthRuntime(){return jqe(this.cfg)}getUserCodexCredential(){return Pqe(this.cfg)}disconnectUserCodexCredential(){return Fqe(this.cfg)}getUserClaudeCredential(){return Iqe(this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(e){return Rqe(this.cfg,e)}async setProviderAccountDefault(t){return P({method:`PUT`,path:`${e.PROVIDER_ACCOUNTS_PATH}/default`,body:{provider:t.provider,provider_account_id:t.providerAccountId}},this.cfg)}async getProviderUsage(){return P({method:`GET`,path:e.PROVIDER_USAGE_PATH},this.cfg)}async refreshProviderUsage(t,n){return P({method:`POST`,path:e.PROVIDER_USAGE_REFRESH_PATH,body:{provider:t,providerAccountId:n}},this.cfg)}disconnectUserClaudeCredential(){return Lqe(this.cfg)}async getClaudeRuntimeReadiness(e){return P({method:`GET`,path:`/api/cmmd/providers/claude/runtime-readiness/${encodeURIComponent(e)}`},this.cfg)}async appendRuntimeThreadEvents(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/runtimes/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/events`,body:n},this.cfg)}async getRuntimeThreadReplica(e,t){return P({method:`GET`,path:`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}`},this.cfg)}renameCloudEnvironment(e,t){return qqe(this.cfg,e,t)}renameDevice(e,t){return Jqe(this.cfg,e,t)}revokeDevice(e){return Yqe(this.cfg,e)}static SIM_PATH=`/api/cmmd/sim-host`;static simScope(e){return e?.orgId===void 0?``:`?orgId=${encodeURIComponent(String(e.orgId))}`}async listSimHosts(t){return P({method:`GET`,path:`${e.SIM_PATH}/hosts${e.simScope(t)}`},this.cfg)}async getSimLease(t){let n=new URLSearchParams({forgeEnvironmentId:t.forgeEnvironmentId,threadId:t.threadId,...t.orgId===void 0?{}:{orgId:String(t.orgId)}});return P({method:`GET`,path:`${e.SIM_PATH}/leases?${n.toString()}`},this.cfg)}async claimSimLease(t){return P({method:`POST`,path:`${e.SIM_PATH}/leases${e.simScope(t)}`,body:{hostId:t.hostId,forgeEnvironmentId:t.forgeEnvironmentId,threadId:t.threadId,ttlMs:t.ttlMs}},this.cfg)}async renewSimLease(t){return P({method:`POST`,path:`${e.SIM_PATH}/leases/${encodeURIComponent(String(t.leaseId))}/renew${e.simScope(t)}`,body:{generation:t.generation,rowVersion:t.rowVersion,ttlMs:t.ttlMs}},this.cfg)}async releaseSimLease(t){await P({method:`POST`,path:`${e.SIM_PATH}/leases/${encodeURIComponent(String(t.leaseId))}/release${e.simScope(t)}`,body:{generation:t.generation,rowVersion:t.rowVersion}},this.cfg)}async listCampaigns(e){let t={};return e?.orgId&&(t.orgId=e.orgId),e?.allWorkspaces&&(t.allWorkspaces=`true`),wG(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map(nJe)}async getCampaign(e){return P({method:`GET`,path:`/api/cmmd/campaigns/${e}`},this.cfg)}async createCampaign(e){return P({method:`POST`,path:`/api/cmmd/campaigns`,body:e},this.cfg)}async updateCampaign(e,t){return P({method:`PUT`,path:`/api/cmmd/campaigns/${e}`,body:t},this.cfg)}async deleteCampaign(e){await P({method:`DELETE`,path:`/api/cmmd/campaigns/${e}`},this.cfg)}async listProjects(e){let t={};return e?.campaignId&&(t.campaignId=e.campaignId),e?.orgId&&(t.orgId=e.orgId),e?.allWorkspaces&&(t.allWorkspaces=`true`),wG(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(FG)}async listTasks(e){let t={};return e?.projectId&&(t.projectId=e.projectId),e?.status&&(t.status=e.status),P({method:`GET`,path:`/api/cmmd/tasks`,query:t},this.cfg)}async getProject(e){return FG(await P({method:`GET`,path:`/api/cmmd/projects/${e}`},this.cfg))}async getProjectMembers(e){let t=await P({method:`GET`,path:`/api/cmmd/projects/${e}/members`},this.cfg);return Array.isArray(t)?t.map(kG):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map($qe):[]}async addProjectMember(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/members`,body:t},this.cfg)}async listProjectAgentMembers(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/agent-members`},this.cfg)}async createProjectAgentMember(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members`,body:t},this.cfg)}async renameProjectAgentMember(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/agent-members/${t}`,body:n},this.cfg)}async retireProjectAgentMember(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/${t}/retire`,body:n},this.cfg)}async updateProjectAgentMemberAvatar(e,t,n){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/agent-members/${t}/avatar`,body:n},this.cfg)}async listProjectAgentMemberInstances(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/agent-members/${t}/instances`},this.cfg)}async previewProjectAgentMemberConsolidation(e){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/consolidation/preview`},this.cfg)}async applyProjectAgentMemberConsolidation(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/agent-members/consolidation/apply`,body:t},this.cfg)}async setProjectTaskAssignment(e,t,n){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/tasks/${t}/assignment`,body:n},this.cfg)}async getProjectUpdates(e,t){let n=t?.page??1,r=t?.limit??10;return eJe(await P({method:`GET`,path:`/api/cmmd/projects/${e}/updates`,query:{page:n,limit:r},unwrapEnvelope:!1},this.cfg),n,r)}async createProjectUpdate(e,t){return AG(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return AG(await P({method:`PATCH`,path:`/api/cmmd/projects/${e}/updates/${t}`,body:n},this.cfg))}async deleteProjectUpdate(e,t){await P({method:`DELETE`,path:`/api/cmmd/projects/${e}/updates/${t}`},this.cfg)}async listProjectMilestones(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/milestones`},this.cfg)}async createProjectMilestone(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/milestones`,body:t},this.cfg)}async updateProjectMilestone(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/milestones/${t}`,body:n},this.cfg)}async deleteProjectMilestone(e,t){await P({method:`DELETE`,path:`/api/cmmd/projects/${e}/milestones/${t}`},this.cfg)}async improveProjectContent(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/content/readability`,body:t},this.cfg)}async listProjectBoard(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/board`},this.cfg)}async createProjectTaskDraft(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts`,body:t},this.cfg)}async getProjectTaskDraft(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/task-drafts/${t}`},this.cfg)}async updateProjectTaskDraft(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/task-drafts/${t}`,body:n},this.cfg)}async previewProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/preview`,body:n},this.cfg)}async commitProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/commit`,body:n},this.cfg)}async discardProjectTaskDraft(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/task-drafts/${t}/discard`,body:n},this.cfg)}async getProjectTaskWorkflow(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/task-workflow`},this.cfg)}async updateProjectTaskWorkflow(e,t){return P({method:`PUT`,path:`/api/cmmd/projects/${e}/task-workflow`,body:t},this.cfg)}async getProjectLeadPlan(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/plan`},this.cfg)}async activateProjectLeadAutomaticStaffing(e){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/authority/activate`,body:{}},this.cfg)}async getProjectLeadReadiness(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/readiness`},this.cfg)}async getProjectLeadCapabilities(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/capabilities`},this.cfg)}async getProjectLeadSummary(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/summary`},this.cfg)}async getProjectLeadDetail(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/detail`},this.cfg)}async getProjectLeadBriefing(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/briefing`},this.cfg)}async decideProjectLeadApproval(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/approvals/${t}/decision`,body:n},this.cfg)}async listProjectLeadEvents(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/events`,...t?{query:{...t.afterEventId===void 0?{}:{afterEventId:String(t.afterEventId)},...t.latest===void 0?{}:{latest:String(t.latest)},...t.limit===void 0?{}:{limit:String(t.limit)}}}:{}},this.cfg)}async explainProjectLead(e){return P({method:`GET`,path:`/api/cmmd/projects/${e}/project-lead/explain`},this.cfg)}async pauseProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/pause`,body:t},this.cfg)}async resumeProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/resume`,body:t},this.cfg)}async reserveProjectLeadTask(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/tasks/${t}/reservations`,body:n},this.cfg)}async releaseProjectLeadReservation(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/reservations/${t}/release`,body:n},this.cfg)}async reconcileProjectLead(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/reconcile`,body:t},this.cfg)}async resolveProjectLeadAttention(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/project-lead/attention/${t}/resolve`,body:n},this.cfg)}async listCenterBoard(e){let t={};return e?.status&&(t.status=e.status),e?.workspaceId&&(t.workspaceId=String(e.workspaceId)),e?.campaignId&&(t.campaignId=String(e.campaignId)),e?.ownerId&&(t.ownerId=String(e.ownerId)),e?.includeArchived!==void 0&&(t.includeArchived=e.includeArchived),e?.q&&(t.q=e.q),P({method:`GET`,path:`/api/cmmd/work-items/board`,query:t},this.cfg)}async listForgeAutomationPresets(){return TG(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return TG(await P({method:`GET`,path:`/api/cmmd/automations/user/rules`},this.cfg),`rules`)}async createUserForgeAutomationRule(e){return P({method:`POST`,path:`/api/cmmd/automations/user/rules`,body:e},this.cfg)}async updateUserForgeAutomationRule(e,t){return P({method:`PATCH`,path:`/api/cmmd/automations/user/rules/${e}`,body:t},this.cfg)}async listUserForgeAutomationRuns(e){return TG(await P({method:`GET`,path:`/api/cmmd/automations/user/rules/${e}/runs`},this.cfg),`runs`)}async startUserForgeAutomationRun(e,t){return P({method:`POST`,path:`/api/cmmd/automations/user/rules/${e}/runs`,body:t},this.cfg)}async listForgeAutomationRules(e,t){let n=EG(t);return TG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/projects/${e}/rules`,body:t,...r?{query:r}:{}},this.cfg)}async updateForgeAutomationRule(e,t,n,r){let i=EG(r);return P({method:`PATCH`,path:`/api/cmmd/automations/projects/${e}/rules/${t}`,body:n,...i?{query:i}:{}},this.cfg)}async listForgeAutomationRuns(e,t){let n=EG(t,t?.taskId);return TG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=EG(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=EG(r);return P({method:`POST`,path:`/api/cmmd/automations/projects/${e}/tasks/${t}/runs`,body:n,...i?{query:i}:{}},this.cfg)}async retryForgeAutomationRun(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/retry`,body:t,...r?{query:r}:{}},this.cfg)}async cancelForgeAutomationRun(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/cancel`,body:t,...r?{query:r}:{}},this.cfg)}async approveForgeAutomationEscalation(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/escalations/approve`,body:t,...r?{query:r}:{}},this.cfg)}async rejectForgeAutomationEscalation(e,t,n){let r=EG(n);return P({method:`POST`,path:`/api/cmmd/automations/runs/${e}/escalations/reject`,body:t,...r?{query:r}:{}},this.cfg)}async createProjectBoardTask(e,t){let n={title:t.title};return t.description!==void 0&&(n.description=t.description),t.priority!==void 0&&(n.priority=t.priority),t.status!==void 0&&(n.status=t.status),t.workflowStageId!==void 0&&(n.workflowStageId=t.workflowStageId),t.assignee!==void 0&&(n.assignee=t.assignee),t.dueDate!==void 0&&(n.dueDate=t.dueDate),t.workItemType!==void 0&&(n.workItemType=t.workItemType),t.parentTaskId!==void 0&&(n.parentTaskId=t.parentTaskId),t.milestoneId!==void 0&&(n.milestoneId=t.milestoneId),t.dependsOn!==void 0&&(n.dependsOn=t.dependsOn),P({method:`POST`,path:`/api/cmmd/projects/${e}/board`,body:n},this.cfg)}async createCenterBoardTask(e){let t={title:e.title,projectId:e.projectId};return e.description!==void 0&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),e.status!==void 0&&(t.status=e.status),e.assignee!==void 0&&(t.assignee=e.assignee),e.dueDate!==void 0&&(t.dueDate=e.dueDate),e.workItemType!==void 0&&(t.workItemType=e.workItemType),e.parentTaskId!==void 0&&(t.parentTaskId=e.parentTaskId),e.milestoneId!==void 0&&(t.milestoneId=e.milestoneId),e.dependsOn!==void 0&&(t.dependsOn=e.dependsOn),P({method:`POST`,path:`/api/cmmd/work-items/board`,body:t},this.cfg)}async submitFeedback(e){let t={type:e.type,title:e.title,source:e.source};return e.description!==void 0&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),e.senderName!==void 0&&(t.senderName=e.senderName),P({method:`POST`,path:`/api/cmmd/feedback`,body:t},this.cfg)}async updateProjectBoardTask(e,t,n){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}`,body:n},this.cfg)}async updateCenterBoardTask(e,t){return P({method:`PATCH`,path:`/api/cmmd/work-items/board/${e}`,body:t},this.cfg)}async moveCenterBoardTask(e,t){let n={toStatus:t.toStatus};return t.beforeTaskId!==void 0&&(n.beforeTaskId=t.beforeTaskId),t.afterTaskId!==void 0&&(n.afterTaskId=t.afterTaskId),P({method:`PATCH`,path:`/api/cmmd/work-items/board/${e}/move`,body:n},this.cfg)}async moveProjectBoardTask(e,t,n){let r={toStatus:n.toStatus};return n.toStageId!==void 0&&(r.toStageId=n.toStageId),n.beforeTaskId!==void 0&&(r.beforeTaskId=n.beforeTaskId),n.afterTaskId!==void 0&&(r.afterTaskId=n.afterTaskId),P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}/move`,body:r},this.cfg)}async archiveProjectBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/archive`},this.cfg)}async unarchiveProjectBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/unarchive`},this.cfg)}async updateProjectBoardTaskStatus(e,t,n,r){return P({method:`PATCH`,path:`/api/cmmd/projects/${e}/board/${t}/status`,body:{status:n,...r?{workflowStageId:r}:{}}},this.cfg)}async listTaskExecutionOptions(e,t){return P({method:`GET`,path:`/api/cmmd/projects/${e}/board/${t}/execution-options`},this.cfg)}async createTaskWorkSession(e,t,n){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/work-sessions`,body:n},this.cfg)}async listProjectWorkSessions(e,t={}){return P({method:`GET`,path:`/api/cmmd/projects/${e}/work-sessions`,query:t},this.cfg)}async getWorkSession(e){return P({method:`GET`,path:`/api/cmmd/work-sessions/${e}`},this.cfg)}async updateWorkSessionStatus(e,t){return P({method:`PATCH`,path:`/api/cmmd/work-sessions/${e}`,body:{status:t}},this.cfg)}async attachWorkSessionThread(e,t){return P({method:`POST`,path:`/api/cmmd/work-sessions/${e}/threads`,body:t},this.cfg)}async listTaskConversations(e,t={}){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/conversations`,query:SG(t)},this.cfg)}async linkTaskConversation(e,t){return P({method:`POST`,path:`/api/cmmd/tasks/${e}/conversations`,body:t},this.cfg)}async getTaskHistory(e){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/history`},this.cfg)}async upsertTaskPullRequest(e,t){return P({method:`PUT`,path:`/api/cmmd/tasks/${e}/pull-requests`,body:t},this.cfg)}postPullRequest(e,t){return P({method:`POST`,path:`/api/cmmd/pull-requests/${e}`,body:t},this.cfg)}async listPullRequests(e){return this.postPullRequest(`list`,e)}async getPullRequestListStats(e){return this.postPullRequest(`list-stats`,e)}async getPullRequestDetail(e){return this.postPullRequest(`detail`,e)}async getPullRequestActivity(e){return this.postPullRequest(`activity`,e)}async getPullRequestDiff(e){return this.postPullRequest(`diff`,e)}async getPullRequestDiffFileContents(e){return this.postPullRequest(`diff-file-contents`,e)}async getPullRequestThreadComments(e){return this.postPullRequest(`thread/comments`,e)}async getPullRequestReviewerCandidates(e){return this.postPullRequest(`reviewer-candidates`,e)}async runPullRequestAction(e){return this.postPullRequest(`action`,e)}async createPullRequestComment(e){return this.postPullRequest(`comment`,e)}async updatePullRequest(e){return this.postPullRequest(`update`,e)}async updatePullRequestComment(e){return this.postPullRequest(`comment/update`,e)}async submitPullRequestReview(e){return this.postPullRequest(`review`,e)}async replyToPullRequestThread(e){return this.postPullRequest(`thread/reply`,e)}async setPullRequestThreadResolution(e){return this.postPullRequest(`thread/resolution`,e)}async requestPullRequestReviewers(e){return this.postPullRequest(`reviewers`,e)}async setPullRequestReaction(e){return this.postPullRequest(`reaction`,e)}async getTaskConversation(e,t,n={}){return P({method:`GET`,path:`/api/cmmd/tasks/${e}/conversations/${encodeURIComponent(t)}`,query:SG(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new CG(`createSubtask`)}async createBoardTask(e){throw new CG(`createBoardTask`)}async createProject(e){let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=r);return e.campaignId!==void 0&&e.campaignId!==null&&(t.campaignId=LG(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=LG(e.organizationId)),iJe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:LG(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=LG(t.targetCampaignId)),t.dryRun!==void 0&&(n.dryRun=t.dryRun),P({method:`POST`,path:`/api/cmmd/projects/${e}/move`,body:n},this.cfg)}async uploadBrainDoc(e,t){throw new CG(`uploadBrainDoc`)}};function BG(e){return new zG(e)}var VG=new zG({onAuthExpired:mr}),HG=class extends Zt(`BootstrapHttpError`){},UG=e=>nee(e,`BootstrapHttpError`);function WG(e){return typeof e!=`object`||!e?!1:!!(UG(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof hr&&e.kind===`auth`)}function aJe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function GG(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new HG({message:`${t} returned a non-JSON response (${aJe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function KG(e={resolveUrl:ar}){let t=pr()?.bearerToken;return t?{...e,bearerToken:t}:e}var qG=null,JG=null,YG=null,XG=new Set,ZG=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function oJe(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();cG({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),_G({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function QG(){if(typeof window>`u`||YG)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(YG=e(e=>{qG=null,JG=null,e.sessionLifecycle.status!==`ready`&&cG(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&jne().catch(e=>{lG(e,{route:`desktop-auth-session-expired`})})}))}function sJe(){return Ul(new URL(window.location.href))}function $G(){let e=new URL(window.location.href),t=vle(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function cJe(){return cK(async()=>{let e=ar(`/api/auth/session`),t=async()=>{let t=await fetch(e,lr({credentials:`include`}));if(!t.ok)throw new HG({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return GG(t,e)},n=await t();return!n.authenticated&&n.auth.sessionMethods.length===1&&n.auth.sessionMethods[0]===`proxy-asserted`&&typeof window<`u`&&!window.desktopBridge&&e.startsWith(`https://`)&&await Nne()?t():n})}async function lJe(e,t){return await e.text()||t}var eK=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function uJe(e){return cK(async()=>{let t={credential:e},n=ar(`/api/auth/bootstrap`),r=await fetch(n,lr({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new HG({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return GG(r,n)})}function tK(e){return new URL(e,window.location.origin).toString()}function nK(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function rK(){return typeof window>`u`?null:nK(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function dJe(){return typeof window>`u`?!1:Pne()===`session-expired`}function iK(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(ZG),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function aK(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(ZG);return}window.sessionStorage.setItem(ZG,JSON.stringify([...e]))}catch{}}function fJe(){let e=rK();if(!e)return;let t=new Set(iK());t.add(e),aK(t)}function pJe(e){return iK().has(e)}function oK(){let e=rK();if(!e){aK(new Set);return}let t=new Set(iK());t.delete(e),aK(t)}async function sK(){let e=tK(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?GG(t,e):null}async function mJe(e){if(typeof window>`u`)return;let t=nK(e);if(!t||dJe()||XG.has(t)||pJe(t))return;if((await sK().catch(()=>null))?.authenticated){XG.add(t);return}let n=tK(`/api/auth/bootstrap`),r=await fetch(n,{body:JSON.stringify({credential:t}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`});if(!r.ok){if(r.status===401)return;throw new HG({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await GG(r,n),XG.add(t)}async function hJe(){let e=await cJe();if(e.authenticated)return e;let t=pr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await sK().catch(()=>null);return n?.authenticated?n:e}var gJe=new Set([404,502,503,504]),_Je=15e3,vJe=500;function yJe(e){pr()?.source===`paired-bearer`&&WG(e)&&ur(`http`)}async function cK(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(yJe(e),!xJe(e))throw e;if(Date.now()-t>=_Je)throw lG(e,{route:`bootstrap-retry-exhausted`}),e;await bJe(vJe)}}function bJe(e){return new Promise(t=>{setTimeout(t,e)})}function xJe(e){return UG(e)?gJe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function SJe(e,t){return e.sessionLifecycle.status===`ready`?e.sessionLifecycle.principalId!==t.id||e.cmmd.identity?.id!==t.id?`desktop-principal-mismatch`:null:`desktop-session-required`}async function CJe(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return SJe(await t(),e)}catch(e){return lG(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function wJe(e,t){return cG(null),Mne(t),await or().catch(e=>{lG(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Fne(t)??`Forge Desktop requires CMMD authentication.`}}async function TJe(){let e=await hJe();if(e.authenticated){if(e.cmmdIdentity){let t=await CJe(e.cmmdIdentity);return t?(dr(),wJe(e,t)):(dr(),oJe(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function EJe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);JG=null,oK(),await uJe(t),qG=null,$G()}function lK(){oK(),JG=null,qG=null}async function uK(e,t,n){let r=e.trim();if(!r)throw Error(`CMMD (Command) OAuth did not return an access token.`);let i=n?.refreshToken?.trim(),a=n?.mcpToken?.trim(),o=ar(`/api/auth/bootstrap/command`),s=await fetch(o,lr({body:JSON.stringify({accessToken:r,...i?{refreshToken:i}:{},...a?{mcpToken:a}:{},...t===void 0?{}:{user:t}}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!s.ok)throw new HG({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await GG(s,o),lK()}async function DJe(){let e=ar(`/api/auth/ws-token`),t=await fetch(e,lr({credentials:`include`,method:`POST`}));if(!t.ok)throw new HG({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return GG(t,e)}async function OJe(e){let t=await DJe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function kJe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=ar(`/api/auth/pairing-token`),a=await fetch(i,lr({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await lJe(a,`Failed to create pairing credential (${a.status}).`));return GG(a,i)}async function AJe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new HG({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return jJe(await GG(t,e))}function jJe(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=MJe(e.cmmdIdentity??null);return t?{displayName:t,email:e.cmmdIdentity?.email??null,avatarUrl:e.cmmdIdentity?.avatarUrl??null,role:e.role,verified:!0,source:`cmmd-identity`}:{displayName:`CMMD identity unavailable`,email:null,avatarUrl:null,role:e.role,verified:!1,source:`fallback`}}function MJe(e){return e&&([e.firstName,e.lastName].map(e=>e?.trim()??``).filter(e=>e.length>0).join(` `)||e.username.trim()||e.email.trim())||null}async function NJe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},KG())}catch(e){throw e instanceof hr&&e.kind!==`auth`&&e.code!==null&&eK.has(e.code)?new hr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}if(!n)throw Error(`Invalid response from ${t}`);return n}async function PJe(e={}){return NJe(e.forceFresh===!0)}async function dK(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},KG())}catch(e){throw e instanceof hr&&e.kind!==`auth`&&e.code!==null&&eK.has(e.code)?new hr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function FJe(e){try{return await dK(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof hr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof hr||t instanceof Error)return dK(`/api/command/tasks/update`,e);throw t}}async function IJe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function LJe(){let e=await Promise.allSettled([or(),IJe()]);cG(null),fJe(),qG=null,JG=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function RJe(){if(QG(),JG?.status===`authenticated`)return dr(),JG;if(qG)return qG;let e=fK();return qG=e,e.then(e=>(e.status===`authenticated`&&(JG=e),e)).finally(()=>{qG===e&&(qG=null)})}async function fK(){return cr().then(e=>mJe(e)).then(()=>TJe())}async function zJe(){QG(),qG=null,JG=null;let e=await fK();return e.status===`authenticated`&&(JG=e,dr()),e}function BJe(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function VJe(e){let t=BJe(e).replace(/-/g,`+`).replace(/_/g,`/`);return`-----BEGIN PUBLIC KEY-----\n${((t+`=`.repeat((4-t.length%4)%4)).match(/.{1,64}/gu)??[]).join(`
1006
1006
  `)}\n-----END PUBLIC KEY-----\n`}function pK(e){return{publicKeyPem:VJe(e.publicKeySpkiDer),async sign(t){let n=await crypto.subtle.sign(`Ed25519`,e.privateKey,new TextEncoder().encode(t));return new Uint8Array(n)}}}var HJe=`cmmd-session-pop`,mK=`keys`,hK=`device-key`;function UJe(){return!1}var gK=class extends Error{constructor(e){super(`CMMD session key storage is unavailable (${e}). Session binding is enabled, so login cannot continue without a bound key: allow site data and IndexedDB for this origin, then retry.`),this.name=`CmmdSessionPopKeyStorageError`}};function WJe(e){return e===void 0?typeof indexedDB>`u`?null:indexedDB:e}function _K(e){return new Promise((t,n)=>{e.addEventListener(`success`,()=>t(e.result),{once:!0}),e.addEventListener(`error`,()=>n(e.error),{once:!0})})}function GJe(e){return new Promise((t,n)=>{e.addEventListener(`complete`,()=>t(),{once:!0}),e.addEventListener(`abort`,()=>n(e.error??new DOMException(`The transaction aborted.`,`AbortError`)),{once:!0}),e.addEventListener(`error`,()=>n(e.error??new DOMException(`The transaction failed.`,`UnknownError`)),{once:!0})})}function KJe(e){return new Promise((t,n)=>{let r=e.open(HJe,1);r.addEventListener(`upgradeneeded`,()=>{r.result.objectStoreNames.contains(mK)||r.result.createObjectStore(mK)}),r.addEventListener(`success`,()=>t(r.result),{once:!0}),r.addEventListener(`error`,()=>n(r.error),{once:!0})})}function vK(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.privateKey instanceof CryptoKey&&t.publicKeySpkiDer instanceof Uint8Array}async function qJe(e){let t=await _K(e.transaction(mK,`readonly`).objectStore(mK).get(hK));return vK(t)?{privateKey:t.privateKey,publicKeySpkiDer:t.publicKeySpkiDer}:null}async function JJe(e,t){let n=e.transaction(mK,`readwrite`),r=n.objectStore(mK),i=GJe(n);i.catch(()=>void 0);let a=await _K(r.get(hK));return vK(a)?{privateKey:a.privateKey,publicKeySpkiDer:a.publicKeySpkiDer}:(await _K(r.add(t,hK)),await i,t)}var yK=null;async function YJe(e={}){return UJe()?(yK??=XJe(e).finally(()=>{yK=null}),yK):null}async function XJe(e){let t=WJe(e.indexedDB),n=e.subtle??crypto.subtle;if(!t)throw new gK(`IndexedDB is not available in this context`);let r;try{r=await KJe(t)}catch{throw new gK(`the key database could not be opened`)}try{let e=await qJe(r);if(e)return pK({privateKey:e.privateKey,publicKeySpkiDer:e.publicKeySpkiDer});let t=await n.generateKey({name:`Ed25519`},!1,[`sign`]),i={privateKey:t.privateKey,publicKeySpkiDer:new Uint8Array(await n.exportKey(`spki`,t.publicKey))};return pK(await JJe(r,i))}catch(e){throw e instanceof gK?e:new gK(`the session key could not be generated or persisted`)}}function bK(e={}){return YJe(e).then(e=>e?.publicKeyPem??null)}async function ZJe(e,t={}){let n=e.email.trim();if(!n||!e.password)throw Error(`Enter your CMMD email and password.`);let r=await(t.resolvePopPublicKey??bK)(),i=ar(`/api/auth/cmmd-password/token`),a=await fetch(i,lr({body:JSON.stringify({email:n,password:e.password,...r?{pop_public_key:r}:{}}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw new HG({message:await a.text()||`CMMD login failed (${a.status}).`,status:a.status});let o=await GG(a,i);if(o.authenticated===!0)return lK(),{serverEstablishedSession:!0};if(typeof o.access_token!=`string`||o.access_token.trim().length===0)throw Error(`CMMD login did not return an access token.`);return await uK(o.access_token,o.user,{refreshToken:typeof o.refresh_token==`string`?o.refresh_token:void 0,mcpToken:typeof o.mcp_token==`string`?o.mcp_token:void 0}),{serverEstablishedSession:!1}}var QJe=`/.well-known/forge/environment`,xK=Jt()(e=>({descriptor:null,setDescriptor:t=>e({descriptor:t}),reset:()=>e({descriptor:null})})),SK=null;function $Je(e){let t=CK();return t?tae(jo({id:t.environmentId,label:t.label,source:e.source,target:e.target}),t):null}async function eYe(){return cK(async()=>{await cr();let e=pr()?.bearerToken,t=ar(QJe),n=e?await fetch(t,{headers:{Authorization:`Bearer ${e}`}}):await fetch(t);if(!n.ok)throw new HG({message:`Failed to load server environment descriptor (${n.status}).`,status:n.status});let r=await GG(n,t);return wK(r),r})}function CK(){return xK.getState().descriptor}function tYe(){return xK(nYe)}function nYe(e){return e.descriptor?.environmentId??null}function rYe(){return xK(iYe)}function iYe(e){return e.descriptor}function aYe(){return xK(oYe)}function oYe(e){return e.descriptor?.deviceRuntimeId??null}function sYe(){return CK()?.deviceRuntimeId??null}function cYe(){return xK(lYe)}function lYe(e){return sae(e.descriptor)}function uYe(){return xK(dYe)}function dYe(e){return cae(e.descriptor)}function wK(e){xK.getState().setDescriptor(e)}function fYe(e,t){return t?.primaryMode!==`cloud`||e.environmentId===t.environmentId}function TK(){let e=pr();return e?$Je({source:e.source,target:e.target}):null}function pYe(){return mYe()}async function mYe(){let e=await cr(),t=CK();if(t&&fYe(t,e))return Promise.resolve(t);if(t&&wK(null),SK)return SK;let n=eYe();return SK=n,n.finally(()=>{SK===n&&(SK=null)})}var EK=class e{#e;constructor(e){this.#e=e}static namedByCatalog(t){return new e(t.projectId)}get registrationProjectId(){return this.#e}asConfirmationIdentity(){return{registrationProjectId:this.#e}}};function DK(e){return{match:t=>t.present({target:e})}}function OK(){return{match:e=>e.provablyAbsent()}}function hYe(e){return{match:t=>t.unprovable(e)}}var gYe=class e{#e;#t;capacity;constructor(e,t,n){this.#e=e,this.#t=t,this.capacity=n}static fromValidatedBody(t,n,r){return new e(t,n,r)}listRowsForDisplay(){return this.#e}listEnvironmentsForDisplay(){return this.#t}locate(e){if(e.registrationProjectId!==void 0){let t=this.#e.find(t=>t.projectId===e.registrationProjectId);return t===void 0?OK():DK(EK.namedByCatalog(t))}if(e.runtimeId!==void 0||e.cmmdEnvironmentId!==void 0){let t=this.#e.find(t=>t.runtime!=null&&(e.runtimeId!==void 0&&t.runtime.runtimeId===e.runtimeId||e.cmmdEnvironmentId!==void 0&&t.runtime.environmentId===e.cmmdEnvironmentId));if(t)return DK(EK.namedByCatalog(t))}if(this.#e.length===0)return OK();let t=e.runtimeId??e.cmmdEnvironmentId;return hYe(t===void 0?`no identity this catalog can be matched on`:`the catalog holds ${String(this.#e.length)} row(s) that ${t} cannot be ruled out against`)}};function kK(e){let t=e,n=t&&typeof t==`object`&&`data`in t&&t.data?t.data:t,r=n?.projects;if(!Array.isArray(r))throw Error("Forge Cloud returned a project catalog this version cannot read (no `projects` list).");let i=n?.environments;if(!Array.isArray(i))throw Error("Forge Cloud returned an Environment catalog this version cannot read (invalid `environments` list).");if(!r.every(_Ye))throw Error(`Forge Cloud returned a project catalog this version cannot read (invalid project entry).`);if(!i.every(vYe))throw Error(`Forge Cloud returned an Environment catalog this version cannot read (invalid Environment entry).`);return gYe.fromValidatedBody(r,i,n?.capacity??null)}function _Ye(e){return!jK(e)||typeof e.organizationId!=`number`||typeof e.projectId!=`number`?!1:e.runtime===void 0||e.runtime===null||AK(e.runtime)}function vYe(e){return jK(e)&&typeof e.organizationId==`number`&&typeof e.userId==`number`&&AK(e.runtime)}function AK(e){return jK(e)&&typeof e.runtimeId==`string`&&typeof e.status==`string`}function jK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yYe(e,t){let n=new URL(e);return n.pathname=t,n.search=``,n.hash=``,n.toString()}function MK(e){return e.accessToken??e.resolveAccessToken?.()}function NK(e,t,n=t=>yYe(e.cmmdHttpBaseUrl,t)){return P({method:t.method,path:t.path,...t.body===void 0?{}:{body:t.body},...t.signal===void 0?{}:{signal:t.signal}},{resolveUrl:n,resolveBearerToken:()=>MK(e)})}function bYe(e,t){return NK(e,{method:`GET`,path:`/api/forge/context/cloud-projects/${encodeURIComponent(String(t.projectId))}/removal-preview`,...t.signal===void 0?{}:{signal:t.signal}},e.cloudProjectRemovalPreviewUrl?()=>e.cloudProjectRemovalPreviewUrl(t.projectId):void 0).then(e=>e.preview)}function xYe(e,t){return NK(e,{method:`POST`,path:`/api/forge/context/cloud-projects/${encodeURIComponent(String(t.projectId))}/removal`,body:{idempotencyKey:t.idempotencyKey,deletePlanningProject:t.deletePlanningProject,...t.deleteCheckoutFiles===void 0?{}:{deleteCheckoutFiles:t.deleteCheckoutFiles},...t.previewToken===void 0?{}:{previewToken:t.previewToken},...t.forceDirty===void 0?{}:{forceDirty:t.forceDirty}},...t.signal===void 0?{}:{signal:t.signal}},e.cloudProjectRemovalUrl?()=>e.cloudProjectRemovalUrl(t.projectId):void 0).then(e=>e.operation)}function PK(e,t=``){return`/api/forge/context/runtimes/${encodeURIComponent(e)}${t}`}async function SYe(e){if(e.ok)return;let{CmmdApiError:t}=await N(async()=>{let{CmmdApiError:e}=await import(`./transport-CgH8pQK3.js`).then(e=>e.r);return{CmmdApiError:e}},__vite__mapDeps([2,1]));if(e.status===401||e.status===403){let n=null;try{let t=await e.json();n=typeof t?.code==`string`?t.code:null}catch{}throw new t({kind:`auth`,message:`CMMD authentication required. Sign in again to continue.`,status:e.status,code:n})}throw new t({kind:e.status>=500?`server`:`client`,message:`forge-cloud-projects proxy error (${e.status})`,status:e.status})}var FK=class{config;constructor(e){this.config=e}async ensureRuntime(e){return(await NK(this.config,{method:`POST`,path:`/api/forge/context/runtimes/ensure`,body:{...e.projectId===void 0?{}:{projectId:e.projectId},...e.organizationId===void 0?{}:{organizationId:e.organizationId},...e.githubRepoFullName===void 0?{}:{githubRepoFullName:e.githubRepoFullName},...e.workspaceRoot===void 0?{}:{workspaceRoot:e.workspaceRoot}},...e.signal===void 0?{}:{signal:e.signal}},this.config.ensureUrl?()=>this.config.ensureUrl:void 0)).runtime}async connectRuntime(e){return NK(this.config,{method:`POST`,path:PK(e.runtimeId,`/connect`),...e.organizationId===void 0?{}:{body:{organizationId:e.organizationId}},...e.signal===void 0?{}:{signal:e.signal}})}async getRuntime(e){return(await NK(this.config,{method:`GET`,path:PK(e.runtimeId),...e.signal===void 0?{}:{signal:e.signal}})).runtime}async destroyRuntime(e){return(await NK(this.config,{method:`POST`,path:PK(e.runtimeId,`/destroy`),body:{purgeVolume:e.purgeVolume??!1,...e.force===!0?{force:!0}:{},...e.reason===void 0?{}:{reason:e.reason},...e.organizationId===void 0?{}:{organizationId:e.organizationId}},...e.signal===void 0?{}:{signal:e.signal}},this.config.destroyUrl?()=>this.config.destroyUrl(e.runtimeId):void 0)).runtime}async runRuntimeLifecycleAction(e){return(await NK(this.config,{method:`POST`,path:PK(e.runtimeId,`/${e.action}`),body:e.organizationId===void 0?{}:{organizationId:e.organizationId},...e.signal===void 0?{}:{signal:e.signal}},this.config.lifecycleUrl?()=>this.config.lifecycleUrl(e.runtimeId,e.action):void 0)).runtime}async updateRuntimeCommit(e){return(await NK(this.config,{method:`POST`,path:PK(e.runtimeId,`/update-commit`),body:e.organizationId===void 0?{}:{organizationId:e.organizationId},...e.signal===void 0?{}:{signal:e.signal}},this.config.updateCommitUrl?()=>this.config.updateCommitUrl(e.runtimeId):void 0)).operation}async getRuntimeCommitUpdateOperation(e){return(await NK(this.config,{method:`GET`,path:PK(e.runtimeId,`/update-commit/${encodeURIComponent(String(e.operationId))}`),...e.signal===void 0?{}:{signal:e.signal}},this.config.updateCommitOperationUrl?()=>this.config.updateCommitOperationUrl(e.runtimeId,e.operationId):void 0)).operation}async listCloudProjects(e){if(this.config.listUrl){let t=MK(this.config),n=await fetch(this.config.listUrl,{method:`GET`,headers:{Accept:`application/json`,...t?{Authorization:`Bearer ${t}`}:{}},credentials:t?`omit`:`include`,cache:`no-store`,...e?.signal===void 0?{}:{signal:e.signal}});return await SYe(n),kK(await n.json())}return kK(await NK(this.config,{method:`GET`,path:`/api/forge/context/cloud-projects`,...e?.signal===void 0?{}:{signal:e.signal}}))}async previewCloudProjectRemoval(e){return bYe(this.config,e)}async requestCloudProjectRemoval(e){return xYe(this.config,e)}async getCloudProjectRemoval(e){return(await NK(this.config,{method:`GET`,path:`/api/forge/context/cloud-projects/removals/${encodeURIComponent(e.operationId)}`,...e.signal===void 0?{}:{signal:e.signal}},this.config.cloudProjectRemovalReceiptUrl?()=>this.config.cloudProjectRemovalReceiptUrl(e.operationId):void 0)).operation}},IK=`/api/attachments/upload/`;function CYe(e){if(!e.relativeUrl.startsWith(IK))throw Error(`Attachment upload URL did not use the expected upload route.`);let t=e.relativeUrl.slice(24);if(!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t))throw Error(`Attachment upload URL did not contain a valid signed token.`);if(e.relativeUrl.includes(`?`)||e.relativeUrl.includes(`#`))throw Error(`Attachment upload URL must not include a query or fragment.`);let n=new URL(e.httpBaseUrl),r=n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname,i=`${r}${IK}`,a=new URL(`${r}${e.relativeUrl}`,n);if(a.origin!==n.origin||!a.pathname.startsWith(i))throw Error(`Attachment upload URL resolved outside the selected environment.`);return a.toString()}var LK=!1,RK=null;function zK(e){return Object.values(e)}function BK(e){return e.map(e=>Sn(e))}function VK(e){try{Ll(BK(zK(e))).catch(e=>{console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)})}catch(e){console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)}}function wYe(e){let t=HK.getState().byId,n=Object.fromEntries(e.map(e=>[e.environmentId,e]));HK.setState({byId:{...n,...t}})}async function TYe(){if(LK)return;if(RK)return RK;let e=(async()=>{try{wYe(await Il())}catch(e){console.error(`[SAVED_ENVIRONMENTS] hydrate failed`,e)}finally{LK=!0,HK.setState({hydrated:!0})}})().finally(()=>{RK===e&&(RK=null)});return RK=e,RK}var HK=Jt()(e=>({byId:{},hydrated:LK,upsert:t=>e(e=>{let n={...e.byId,[t.environmentId]:t};return VK(n),{byId:n}}),remove:t=>e(e=>{let{[t]:n,...r}=e.byId;return VK(r),{byId:r}}),markConnected:(t,n)=>e(e=>{let r=e.byId[t];if(!r)return e;let i={...e.byId,[t]:{...r,lastConnectedAt:n}};return VK(i),{byId:i}}),reset:()=>{VK({}),e({byId:{}})}}));function UK(){return LK}function WK(){return UK()?Promise.resolve():TYe()}function GK(){return Object.values(HK.getState().byId).toSorted((e,t)=>e.label.localeCompare(t.label))}function EYe(){return GK().filter(e=>e.lastAuthenticatedPullRequestCapability===!0)}function KK(e){return HK.getState().byId[e]??null}function qK(e){let t=TK();return t?.environmentId===e?eae(t):KK(e)?.httpBaseUrl??null}function JK(e){let t=qK(e.environmentId)??(typeof window<`u`?window.location.origin:null);if(!t)throw Error(`Unable to resolve HTTP base URL for environment ${e.environmentId}.`);let n=new URL(t);return n.pathname=`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${e.pathname.startsWith(`/`)?e.pathname:`/${e.pathname}`}`,e.searchParams&&(n.search=new URLSearchParams(e.searchParams).toString()),n.toString()}function YK(e){if(!qK(e))throw Error(`Unable to resolve HTTP base URL for environment ${e}.`)}function DYe(e){return YK(e.environmentId),CYe({httpBaseUrl:qK(e.environmentId),relativeUrl:e.relativeUrl})}async function XK(e){await Ll(BK(zK({...HK.getState().byId,[e.environmentId]:e})))}async function OYe(e,t){let{[e]:n,...r}=HK.getState().byId,i={...r,[t.environmentId]:t};await Ll(BK(zK(i))),HK.setState({byId:i})}async function ZK(e){return Rl(e)}async function kYe(e,t){return zl(e,t)}async function QK(e){await Bl(e)}var AYe=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function $K(e){let t=e?.trim();return t&&t.length>0?t:null}function jYe(e){return $K(e)??`Project`}function MYe(e,t=`safe`){let n=$K(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function eq(e,t=`Something went wrong. Try again.`){let n=ZW(e instanceof Error?e.message:typeof e==`string`?e:String(e),{fallback:t});return!n||AYe.some(e=>e.test(n))?t:n}function NYe(e,t){return e.reasoningEffortLevels.some(e=>e.value===t)}function tq(e){return e.reasoningEffortLevels.find(e=>e.isDefault)?.value??null}function nq(e,t){let n=tq(e),r=typeof t==`string`?t.trim():null;return r&&!e.promptInjectedEffortLevels.includes(r)&&NYe(e,r)?r:n??void 0}function rq(e,t){return e.contextWindowOptions.some(e=>e.value===t)}function iq(e){return e.contextWindowOptions.find(e=>e.isDefault)?.value??null}function PYe(e,t){let n=iq(e);return t&&rq(e,t)?t:n??void 0}function FYe(e,t){let n=nq(e,t?.reasoningEffort),r=e.supportsFastMode?t?.fastMode:void 0,i={...n?{reasoningEffort:n}:{},...r===void 0?{}:{fastMode:r}};return Object.keys(i).length>0?i:void 0}function IYe(e,t){let n=nq(e,t?.effort),r=e.supportsThinkingToggle?t?.thinking:void 0,i=e.supportsFastMode?t?.fastMode:void 0,a=PYe(e,t?.contextWindow),o={...r===void 0?{}:{thinking:r},...n?{effort:n}:{},...i===void 0?{}:{fastMode:i},...a===void 0?{}:{contextWindow:a}};return Object.keys(o).length>0?o:void 0}function aq(e){return typeof e==`string`&&/\bultrathink\b/i.test(e)}function oq(e,t=`codex`){if(typeof e!=`string`)return null;let n=e.trim();if(!n)return null;let r=Cne[t],i=Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return typeof i==`string`?i:n}function sq(e,t,n){if(typeof t!=`string`)return null;let r=t.trim();if(!r)return null;let i=n.find(e=>e.slug===r);if(i)return i.slug;let a=n.find(e=>e.name.toLowerCase()===r.toLowerCase());if(a)return a.slug;let o=oq(r,e),s=n.find(e=>e.slug===o);return s?s.slug:null}var LYe=[`codex`,`claudeAgent`];function cq(e,t){return LYe.filter(e=>e!==t).some(t=>Nte(t,e)!==void 0)}function RYe(e,t){let n=oq(e,t);return!n||cq(n,t)?En[t]:n}function lq(e,t){return RYe(t,e)}function zYe(e){return typeof e==`string`&&e.trim()||null}function BYe(e,t){let n=e.trim();return!n||t!==`ultrathink`||n.startsWith(`Ultrathink:`)?n:`Ultrathink:\n${n}`}function uq(e,t){return{id:e.id,environmentId:t,name:e.title,cwd:e.workspaceRoot,repositoryIdentity:e.repositoryIdentity??null,availability:e.availability,defaultThreadEnvMode:e.defaultThreadEnvMode??null,cmmdRegistration:e.cmmdRegistration??null,defaultModelSelection:e.defaultModelSelection?dq(e.defaultModelSelection):null,createdAt:e.createdAt,updatedAt:e.updatedAt,scripts:fq(e.scripts)}}function dq(e){return{...e,model:lq(e.provider,e.model)}}function fq(e){return e.map(e=>({...e}))}function VYe(e,t){return{...e,...t.title===void 0?{}:{name:t.title},...t.workspaceRoot===void 0?{}:{cwd:t.workspaceRoot},...t.repositoryIdentity===void 0?{}:{repositoryIdentity:t.repositoryIdentity??null},...t.defaultThreadEnvMode===void 0?{}:{defaultThreadEnvMode:t.defaultThreadEnvMode},...t.cmmdRegistration===void 0?{}:{cmmdRegistration:t.cmmdRegistration},...t.defaultModelSelection===void 0?{}:{defaultModelSelection:t.defaultModelSelection?dq(t.defaultModelSelection):null},...t.scripts===void 0?{}:{scripts:fq(t.scripts)},updatedAt:t.updatedAt}}function pq(e){let t=$W(e.lastError);return{provider:UYe(e.providerName),status:HYe(e.status),orchestrationStatus:e.status,activeTurnId:e.activeTurnId??void 0,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{lastError:t}:{}}}function mq(e,t){let n=t.attachments?.map(t=>{let n=JK({environmentId:e,pathname:WYe(t.id)});return t.type===`image`?{...t,previewUrl:n}:{...t,downloadUrl:n}});return{id:t.id,role:t.role,text:t.text,turnId:t.turnId,createdAt:t.createdAt,streaming:t.streaming,...t.streaming?{}:{completedAt:t.updatedAt},...n&&n.length>0?{attachments:n}:{}}}function hq(e){return{id:e.id,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId,createdAt:e.createdAt,updatedAt:e.updatedAt}}function gq(e){return{turnId:e.turnId,completedAt:e.completedAt,status:e.status,assistantMessageId:e.assistantMessageId??void 0,checkpointTurnCount:e.checkpointTurnCount,checkpointRef:e.checkpointRef,files:e.files.map(e=>({...e}))}}function HYe(e){switch(e){case`starting`:return`connecting`;case`running`:return`running`;case`error`:return`error`;case`ready`:case`interrupted`:return`ready`;case`idle`:case`stopped`:return`closed`}}function UYe(e){return e===`codex`||e===`claudeAgent`||e===`ollama`||e===`cmmd`||e===`apex`?e:`codex`}function WYe(e){return`/attachments/${encodeURIComponent(e)}`}var GYe=[],KYe=[],qYe=[],JYe=[],YYe={},XYe={},ZYe={},QYe={},$Ye=[],_q=new WeakMap,vq=new WeakMap;function yq(e,t,n){if(!e||e.length===0||!t)return n;let r=_q.get(e),i=r?.get(t);if(i)return i;let a=e.flatMap(e=>{let n=t[e];return n?[n]:[]}),o=r??new WeakMap;return o.set(t,a),r||_q.set(e,o),a}function eXe(e,t){return yq(e.messageIdsByThreadId[t],e.messageByThreadId[t]??YYe,GYe)}function tXe(e,t){return yq(e.activityIdsByThreadId[t],e.activityByThreadId[t]??XYe,KYe)}function nXe(e,t){return yq(e.proposedPlanIdsByThreadId[t],e.proposedPlanByThreadId[t]??ZYe,qYe)}function rXe(e,t){return yq(e.turnDiffIdsByThreadId[t],e.turnDiffSummaryByThreadId[t]??QYe,JYe)}function bq(e,t){let n=e.threadShellById[t];if(!n)return;let r=e.threadSessionById[t]??null,i=e.threadTurnStateById[t],a=e.threadRateLimitStatusById[t]??$Ye,o=eXe(e,t),s=tXe(e,t),c=nXe(e,t),l=rXe(e,t),u=vq.get(n);if(u&&u.session===r&&u.turnState===i&&u.rateLimitStatus===a&&u.messages===o&&u.activities===s&&u.proposedPlans===c&&u.turnDiffSummaries===l)return u.thread;let d={...n,session:r,latestTurn:i?.latestTurn??null,pendingSourceProposedPlan:i?.pendingSourceProposedPlan,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l};return vq.set(n,{session:r,turnState:i,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l,thread:d}),d}function iXe(e,t){let n=t.providerAccountId??null,r=e=>e.provider===t.provider&&(e.providerAccountId??null)===n,i=e.find(r),a={status:t.status,usedPercent:t.usedPercent,resetsAt:t.resetsAt},o={provider:t.provider,providerAccountId:n,fiveHour:t.window===`five_hour`?a:i?.fiveHour??null,sevenDay:t.window===`seven_day`?a:i?.sevenDay??null};return[...e.filter(e=>!r(e)),o]}function xq(e){return{settledAt:e.settledAt??null,settledOverride:e.settledOverride??null}}var Sq={projectIds:[],projectById:{},threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:{},messageIdsByThreadId:{},messageByThreadId:{},activityIdsByThreadId:{},activityByThreadId:{},proposedPlanIdsByThreadId:{},proposedPlanByThreadId:{},turnDiffIdsByThreadId:{},turnDiffSummaryByThreadId:{},sidebarThreadSummaryById:{},threadSubscriptionErrorById:{},bootstrapComplete:!1},aXe={activeEnvironmentId:null,environmentStateById:{}},Cq=[],wq=[];function Tq(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Eq(e,t){return{id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:dq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,session:e.session?pq(e.session):null,messages:e.messages.map(e=>mq(t,e)),proposedPlans:e.proposedPlans.map(hq),error:$W(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...xq(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan,branch:e.branch,worktreePath:e.worktreePath,turnDiffSummaries:e.checkpoints.map(gq),activities:e.activities.map(e=>({...e})),anchorKind:e.anchorKind,anchorCmmdId:e.anchorCmmdId,linkedPullRequest:e.linkedPullRequest??null,goal:e.goal??null,titleRegeneration:e.titleRegeneration??null,kind:e.kind,parentThreadId:e.parentThreadId,status:e.status,workerRole:e.workerRole??null,pendingAutoCreatePrompt:e.pendingAutoCreatePrompt??null,rateLimitStatus:e.rateLimitStatus??[]}}function Dq(e,t){let n={id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:dq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:$W(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...xq(e),updatedAt:e.updatedAt,branch:e.branch,worktreePath:e.worktreePath,anchorKind:e.anchorKind,anchorCmmdId:e.anchorCmmdId,linkedPullRequest:e.linkedPullRequest??null,goal:e.goal??null,titleRegeneration:e.titleRegeneration??null,kind:e.kind,parentThreadId:e.parentThreadId,status:e.status,workerRole:e.workerRole??null},r=e.session?pq(e.session):null;return{shell:n,session:r,turnState:{latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan},summary:{id:e.id,modelSelection:n.modelSelection,environmentId:t,projectId:e.projectId,title:e.title,interactionMode:e.interactionMode,session:r,createdAt:e.createdAt,archivedAt:e.archivedAt,...xq(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,branch:e.branch,worktreePath:e.worktreePath,latestUserMessageAt:e.latestUserMessageAt,hasPendingApprovals:e.hasPendingApprovals,hasPendingUserInput:e.hasPendingUserInput,hasActionableProposedPlan:e.hasActionableProposedPlan,anchorKind:e.anchorKind,anchorCmmdId:e.anchorCmmdId,linkedPullRequest:e.linkedPullRequest??null,goal:e.goal??null,titleRegeneration:e.titleRegeneration??null,kind:e.kind,parentThreadId:e.parentThreadId,status:e.status,workerRole:e.workerRole??null}}}function oXe(e){return{id:e.id,environmentId:e.environmentId,codexThreadId:e.codexThreadId,projectId:e.projectId,title:e.title,modelSelection:e.modelSelection,runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:e.error,createdAt:e.createdAt,archivedAt:e.archivedAt,settledAt:e.settledAt,settledOverride:e.settledOverride,updatedAt:e.updatedAt,branch:e.branch,worktreePath:e.worktreePath,anchorKind:e.anchorKind,anchorCmmdId:e.anchorCmmdId,linkedPullRequest:e.linkedPullRequest??null,kind:e.kind,parentThreadId:e.parentThreadId,status:e.status,workerRole:e.workerRole??null,goal:e.goal??null,titleRegeneration:e.titleRegeneration??null}}function sXe(e){return{latestTurn:e.latestTurn,...e.pendingSourceProposedPlan?{pendingSourceProposedPlan:e.pendingSourceProposedPlan}:{}}}function Oq(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.threadId===t.threadId&&e.planId===t.planId}function kq(e,t){return e===t?!0:e==null||t==null?!1:e.turnId===t.turnId&&e.state===t.state&&e.requestedAt===t.requestedAt&&e.startedAt===t.startedAt&&e.completedAt===t.completedAt&&e.assistantMessageId===t.assistantMessageId&&Oq(e.sourceProposedPlan,t.sourceProposedPlan)}function Aq(e,t){return e===t?!0:e==null||t==null?!1:e.provider===t.provider&&e.status===t.status&&e.orchestrationStatus===t.orchestrationStatus&&e.activeTurnId===t.activeTurnId&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt&&e.lastError===t.lastError}function jq(e,t){return e===t?!0:e==null||t==null?!1:e.projectId===t.projectId&&e.projectRepositoryId===t.projectRepositoryId&&e.provider===t.provider&&e.host===t.host&&e.repository===t.repository&&e.number===t.number&&e.url===t.url}function Mq(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.title===t.title&&Nq(e.titleRegeneration,t.titleRegeneration)&&e.interactionMode===t.interactionMode&&Aq(e.session,t.session)&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&kq(e.latestTurn,t.latestTurn)&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.latestUserMessageAt===t.latestUserMessageAt&&e.hasPendingApprovals===t.hasPendingApprovals&&e.hasPendingUserInput===t.hasPendingUserInput&&e.hasActionableProposedPlan===t.hasActionableProposedPlan&&e.anchorKind===t.anchorKind&&e.anchorCmmdId===t.anchorCmmdId&&jq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status}function Nq(e,t){return e===t?!0:e==null||t==null?!1:e.requestId===t.requestId&&e.startedAt===t.startedAt}function Pq(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.codexThreadId===t.codexThreadId&&e.projectId===t.projectId&&e.title===t.title&&e.modelSelection===t.modelSelection&&e.runtimeMode===t.runtimeMode&&e.interactionMode===t.interactionMode&&e.error===t.error&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.anchorKind===t.anchorKind&&e.anchorCmmdId===t.anchorCmmdId&&jq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status&&e.goal===t.goal&&Nq(e.titleRegeneration,t.titleRegeneration)}function Fq(e,t){return e!==void 0&&kq(e.latestTurn,t.latestTurn)&&Oq(e.pendingSourceProposedPlan,t.pendingSourceProposedPlan)}function cXe(e,t){return e.includes(t)?[...e]:[...e,t]}function Iq(e,t){return e.filter(e=>e!==t)}function lXe(e){return{ids:e.messages.map(e=>e.id),byId:Object.fromEntries(e.messages.map(e=>[e.id,e]))}}function uXe(e){return{ids:e.activities.map(e=>e.id),byId:Object.fromEntries(e.activities.map(e=>[e.id,e]))}}function dXe(e){return{ids:e.proposedPlans.map(e=>e.id),byId:Object.fromEntries(e.proposedPlans.map(e=>[e.id,e]))}}function fXe(e){return{ids:e.turnDiffSummaries.map(e=>e.turnId),byId:Object.fromEntries(e.turnDiffSummaries.map(e=>[e.turnId,e]))}}function pXe(e){return e.projectIds.flatMap(t=>{let n=e.projectById[t];return n?[n]:[]})}function Lq(e){return e.threadIds.flatMap(t=>{let n=bq(e,t);return n?[n]:[]})}function Rq(e,t,n,r){let i=e;if(e.threadIds.includes(t)||(i={...i,threadIds:[...i.threadIds,t]}),r!==n){let e=i.threadIdsByProjectId;if(r){let n=e[r]??Cq,i=Iq(n,t);if(i.length===0){let{[r]:t,...n}=e;e=n}else Tq(n,i)||(e={...e,[r]:i})}let a=e[n]??Cq,o=cXe(a,t);Tq(a,o)||(e={...e,[n]:o}),e!==i.threadIdsByProjectId&&(i={...i,threadIdsByProjectId:e})}return i}function zq(e,t,n){let r=oXe(t),i=sXe(t),a=e.threadShellById[t.id],o=e.threadTurnStateById[t.id],s=Rq(e,t.id,t.projectId,n?.projectId);Pq(a,r)||(s={...s,threadShellById:{...s.threadShellById,[t.id]:r}});let c=e.sidebarThreadSummaryById[t.id];if(c!==void 0){let e={...c,title:t.title,modelSelection:t.modelSelection,interactionMode:t.interactionMode,session:t.session,createdAt:t.createdAt,archivedAt:t.archivedAt,settledAt:t.settledAt,settledOverride:t.settledOverride,updatedAt:t.updatedAt,latestTurn:t.latestTurn,branch:t.branch,worktreePath:t.worktreePath,anchorKind:t.anchorKind,anchorCmmdId:t.anchorCmmdId,linkedPullRequest:t.linkedPullRequest??null,goal:t.goal,titleRegeneration:t.titleRegeneration??null,kind:t.kind,parentThreadId:t.parentThreadId,status:t.status,workerRole:t.workerRole};Mq(c,e)||(s={...s,sidebarThreadSummaryById:{...s.sidebarThreadSummaryById,[t.id]:e}})}if(Aq(n?.session??null,t.session)||(s={...s,threadSessionById:{...s.threadSessionById,[t.id]:t.session}}),(n?.rateLimitStatus??wq)!==(t.rateLimitStatus??wq)&&(s={...s,threadRateLimitStatusById:{...s.threadRateLimitStatusById,[t.id]:t.rateLimitStatus??wq}}),Fq(o,i)||(s={...s,threadTurnStateById:{...s.threadTurnStateById,[t.id]:i}}),n?.messages!==t.messages){let e=lXe(t);s={...s,messageIdsByThreadId:{...s.messageIdsByThreadId,[t.id]:e.ids},messageByThreadId:{...s.messageByThreadId,[t.id]:e.byId}}}if(n?.activities!==t.activities){let e=uXe(t);s={...s,activityIdsByThreadId:{...s.activityIdsByThreadId,[t.id]:e.ids},activityByThreadId:{...s.activityByThreadId,[t.id]:e.byId}}}if(n?.proposedPlans!==t.proposedPlans){let e=dXe(t);s={...s,proposedPlanIdsByThreadId:{...s.proposedPlanIdsByThreadId,[t.id]:e.ids},proposedPlanByThreadId:{...s.proposedPlanByThreadId,[t.id]:e.byId}}}if(n?.turnDiffSummaries!==t.turnDiffSummaries){let e=fXe(t);s={...s,turnDiffIdsByThreadId:{...s.turnDiffIdsByThreadId,[t.id]:e.ids},turnDiffSummaryByThreadId:{...s.turnDiffSummaryByThreadId,[t.id]:e.byId}}}return s}function Bq(e,t){let n=e.threadShellById[t.shell.id],r=Rq(e,t.shell.id,t.shell.projectId,n?.projectId);return Pq(n,t.shell)||(r={...r,threadShellById:{...r.threadShellById,[t.shell.id]:t.shell}}),Aq(e.threadSessionById[t.shell.id]??null,t.session)||(r={...r,threadSessionById:{...r.threadSessionById,[t.shell.id]:t.session}}),Fq(e.threadTurnStateById[t.shell.id],t.turnState)||(r={...r,threadTurnStateById:{...r.threadTurnStateById,[t.shell.id]:t.turnState}}),Mq(e.sidebarThreadSummaryById[t.shell.id],t.summary)||(r={...r,sidebarThreadSummaryById:{...r.sidebarThreadSummaryById,[t.shell.id]:t.summary}}),r}function Vq(e,t){return Object.fromEntries(Object.entries(e).flatMap(([e,n])=>t.has(e)?[[e,n]]:[]))}function Hq(e,t){let n=e.threadShellById[t],r=e.sidebarThreadSummaryById[t],i=n?.projectId??r?.projectId;if(!i)return e;let a=Iq(e.threadIds,t),o=Iq(e.threadIdsByProjectId[i]??Cq,t),s=o.length===0?(()=>{let{[i]:t,...n}=e.threadIdsByProjectId;return n})():{...e.threadIdsByProjectId,[i]:o},{[t]:c,...l}=e.threadShellById,{[t]:u,...d}=e.threadSessionById,{[t]:f,...p}=e.threadTurnStateById,{[t]:m,...h}=e.messageIdsByThreadId,{[t]:g,..._}=e.messageByThreadId,{[t]:v,...y}=e.activityIdsByThreadId,{[t]:b,...x}=e.activityByThreadId,{[t]:S,...C}=e.proposedPlanIdsByThreadId,{[t]:w,...T}=e.proposedPlanByThreadId,{[t]:E,...D}=e.turnDiffIdsByThreadId,{[t]:ee,...te}=e.turnDiffSummaryByThreadId,{[t]:ne,...O}=e.sidebarThreadSummaryById;return{...e,threadIds:a,threadIdsByProjectId:s,threadShellById:l,threadSessionById:d,threadTurnStateById:p,messageIdsByThreadId:h,messageByThreadId:_,activityIdsByThreadId:y,activityByThreadId:x,proposedPlanIdsByThreadId:C,proposedPlanByThreadId:T,turnDiffIdsByThreadId:D,turnDiffSummaryByThreadId:te,sidebarThreadSummaryById:O}}function mXe(e,t){let n=new Set(e.threadIdsByProjectId[t]??Cq);for(let[r,i]of Object.entries(e.threadShellById))i.projectId===t&&n.add(r);for(let[r,i]of Object.entries(e.sidebarThreadSummaryById))i.projectId===t&&n.add(r);return[...n]}function Uq(e,t){let n=mXe(e,t);if(!e.projectById[t]&&n.length===0&&!e.projectIds.includes(t))return e;let r=e;for(let e of n)r=Hq(r,e);let{[t]:i,...a}=r.projectById;return{...r,projectById:a,projectIds:Iq(r.projectIds,t)}}function Wq(e){return e===`error`?`error`:e===`missing`?`interrupted`:`completed`}function hXe(e,t){if(e.sequence!==void 0&&t.sequence!==void 0){if(e.sequence!==t.sequence)return e.sequence-t.sequence}else if(e.sequence!==void 0)return 1;else if(t.sequence!==void 0)return-1;return e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id)}function Gq(e){let t=e.previous?.turnId===e.turnId?e.previous.sourceProposedPlan:e.sourceProposedPlan;return{turnId:e.turnId,state:e.state,requestedAt:e.requestedAt,startedAt:e.startedAt,completedAt:e.completedAt,assistantMessageId:e.assistantMessageId,...t?{sourceProposedPlan:t}:{}}}function gXe(e,t,n){let r=!1,i=e.map(e=>e.turnId!==t||e.assistantMessageId===n?e:(r=!0,{...e,assistantMessageId:n??void 0}));return r?i:[...e]}function _Xe(e,t,n){let r=new Set;for(let n of e){if(n.role===`system`){r.add(n.id);continue}n.turnId!==void 0&&n.turnId!==null&&t.has(n.turnId)&&r.add(n.id)}let i=e.filter(e=>e.role===`user`&&r.has(e.id)).length,a=Math.max(0,n-i);if(a>0){let n=e.filter(e=>e.role===`user`&&!r.has(e.id)&&(e.turnId===void 0||e.turnId===null||t.has(e.turnId))).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id)).slice(0,a);for(let e of n)r.add(e.id)}let o=e.filter(e=>e.role===`assistant`&&r.has(e.id)).length,s=Math.max(0,n-o);if(s>0){let n=e.filter(e=>e.role===`assistant`&&!r.has(e.id)&&(e.turnId===void 0||e.turnId===null||t.has(e.turnId))).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id)).slice(0,s);for(let e of n)r.add(e.id)}return e.filter(e=>r.has(e.id))}function vXe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function yXe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function Kq(e,t,n){let r=bq(e,t);if(!r)return e;let i=n(r);return i===r?e:zq(e,i,r)}function qq(e,t,n,r){let i=Kq(e,t,e=>({...e,...r,updatedAt:n})),a=i.sidebarThreadSummaryById[t];return!a||Object.keys(r).every(e=>a[e]===r[e])?i:{...i,sidebarThreadSummaryById:{...i.sidebarThreadSummaryById,[t]:{...a,...r}}}}function bXe(e){return{projectIds:e.map(e=>e.id),projectById:Object.fromEntries(e.map(e=>[e.id,e]))}}function Jq(e,t){return e.environmentStateById[t]??Sq}function Yq(e,t,n){let r=e.environmentStateById[t]===n?e.environmentStateById:{...e.environmentStateById,[t]:n};return r===e.environmentStateById?e:{...e,environmentStateById:r}}function xXe(e,t,n){let r=t.projects.map(e=>uq(e,n)),i=new Set(t.threads.map(e=>e.id)),a={...e,...bXe(r),threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:Vq(e.threadRateLimitStatusById,i),sidebarThreadSummaryById:{},messageIdsByThreadId:Vq(e.messageIdsByThreadId,i),messageByThreadId:Vq(e.messageByThreadId,i),activityIdsByThreadId:Vq(e.activityIdsByThreadId,i),activityByThreadId:Vq(e.activityByThreadId,i),proposedPlanIdsByThreadId:Vq(e.proposedPlanIdsByThreadId,i),proposedPlanByThreadId:Vq(e.proposedPlanByThreadId,i),turnDiffIdsByThreadId:Vq(e.turnDiffIdsByThreadId,i),turnDiffSummaryByThreadId:Vq(e.turnDiffSummaryByThreadId,i),bootstrapComplete:!0};for(let e of t.threads)a=Bq(a,Dq(e,n));return a}function SXe(e,t,n){return Yq(e,n,xXe(Jq(e,n),t,n))}function CXe(e,t,n){let r=Jq(e,n),i=bq(r,t.id);return Yq(e,n,zq(r,Eq(t,n),i))}function wXe(e,t,n,r){let i=Jq(e,t);return Yq(e,t,{...i,threadSubscriptionErrorById:{...i.threadSubscriptionErrorById,[n]:r}})}function TXe(e,t,n){let r=Jq(e,t);if(!(n in r.threadSubscriptionErrorById))return e;let{[n]:i,...a}=r.threadSubscriptionErrorById;return Yq(e,t,{...r,threadSubscriptionErrorById:a})}function Xq(e,t,n){switch(t.type){case`project.created`:{let r=uq({id:t.payload.projectId,title:t.payload.title,workspaceRoot:t.payload.workspaceRoot,repositoryIdentity:t.payload.repositoryIdentity??null,defaultModelSelection:t.payload.defaultModelSelection,defaultThreadEnvMode:t.payload.defaultThreadEnvMode??null,cmmdRegistration:t.payload.cmmdRegistration??null,scripts:t.payload.scripts,createdAt:t.payload.createdAt,updatedAt:t.payload.updatedAt,deletedAt:null},n),i=e.projectIds.find(n=>n===t.payload.projectId||e.projectById[n]?.cwd===t.payload.workspaceRoot)??null,a=e.projectById,o=e.projectIds;if(i!==null&&i!==r.id){let{[i]:t,...n}=e.projectById;a={...n,[r.id]:r},o=e.projectIds.map(e=>e===i?r.id:e)}else a={...e.projectById,[r.id]:r},o=i===null&&!e.projectIds.includes(r.id)?[...e.projectIds,r.id]:e.projectIds;return{...e,projectById:a,projectIds:o}}case`project.meta-updated`:{let n=e.projectById[t.payload.projectId];if(!n)return e;let r=VYe(n,t.payload);return{...e,projectById:{...e.projectById,[t.payload.projectId]:r}}}case`project.deleted`:return Uq(e,t.payload.projectId);case`thread.created`:{let r=bq(e,t.payload.threadId);return zq(e,Eq({id:t.payload.threadId,projectId:t.payload.projectId,title:t.payload.title,modelSelection:t.payload.modelSelection,runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,branch:t.payload.branch,worktreePath:t.payload.worktreePath,latestTurn:null,createdAt:t.payload.createdAt,updatedAt:t.payload.updatedAt,archivedAt:null,deletedAt:null,messages:[],proposedPlans:[],activities:[],checkpoints:[],session:null,anchorKind:t.payload.anchorKind,anchorCmmdId:t.payload.anchorCmmdId,kind:t.payload.kind,parentThreadId:t.payload.parentThreadId,status:t.payload.status,workerRole:t.payload.workerRole,goal:t.payload.goal??null,titleRegeneration:null,pendingAutoCreatePrompt:null},n),r)}case`thread.deleted`:return Hq(e,t.payload.threadId);case`thread.archived`:return qq(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:t.payload.archivedAt});case`thread.unarchived`:return qq(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:null});case`thread.settled`:return qq(e,t.payload.threadId,t.payload.updatedAt,{settledAt:t.payload.settledAt,settledOverride:t.payload.settledOverride});case`thread.unsettled`:return qq(e,t.payload.threadId,t.payload.updatedAt,{settledAt:null,settledOverride:`active`});case`thread.meta-updated`:return Kq(e,t.payload.threadId,e=>({...e,...t.payload.title===void 0?{}:{title:t.payload.title},...t.payload.modelSelection===void 0?{}:{modelSelection:dq(t.payload.modelSelection)},...t.payload.branch===void 0?{}:{branch:t.payload.branch},...t.payload.worktreePath===void 0?{}:{worktreePath:t.payload.worktreePath},...t.payload.anchorKind===void 0?{}:{anchorKind:t.payload.anchorKind},...t.payload.anchorCmmdId===void 0?{}:{anchorCmmdId:t.payload.anchorCmmdId},...t.payload.status===void 0?{}:{status:t.payload.status},...t.payload.parentThreadId===void 0?{}:{parentThreadId:t.payload.parentThreadId},...t.payload.goal===void 0?{}:{goal:t.payload.goal},...t.payload.linkedPullRequest===void 0?{}:{linkedPullRequest:t.payload.linkedPullRequest},...t.payload.titleRegeneration===void 0?{}:{titleRegeneration:t.payload.titleRegeneration},updatedAt:t.payload.updatedAt}));case`thread.runtime-mode-set`:return Kq(e,t.payload.threadId,e=>({...e,runtimeMode:t.payload.runtimeMode,updatedAt:t.payload.updatedAt}));case`thread.interaction-mode-set`:return Kq(e,t.payload.threadId,e=>({...e,interactionMode:t.payload.interactionMode,updatedAt:t.payload.updatedAt}));case`thread.turn-start-requested`:return Kq(e,t.payload.threadId,e=>({...e,...t.payload.modelSelection===void 0?{}:{modelSelection:dq(t.payload.modelSelection)},runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,pendingSourceProposedPlan:t.payload.sourceProposedPlan,latestTurn:Gq({previous:e.latestTurn,turnId:mn.make(t.payload.messageId),state:`running`,requestedAt:t.payload.createdAt,startedAt:t.payload.createdAt,completedAt:null,assistantMessageId:null,sourceProposedPlan:t.payload.sourceProposedPlan}),updatedAt:t.occurredAt}));case`thread.turn-interrupt-requested`:return t.payload.turnId===void 0?e:Kq(e,t.payload.threadId,e=>{let n=e.latestTurn;return n===null||n.turnId!==t.payload.turnId?e:{...e,latestTurn:Gq({previous:n,turnId:t.payload.turnId,state:`interrupted`,requestedAt:n.requestedAt,startedAt:n.startedAt??t.payload.createdAt,completedAt:n.completedAt??t.payload.createdAt,assistantMessageId:n.assistantMessageId}),updatedAt:t.occurredAt}});case`thread.message-sent`:return Kq(e,t.payload.threadId,e=>{let n=mq(e.environmentId,{id:t.payload.messageId,role:t.payload.role,text:t.payload.text,...t.payload.attachments===void 0?{}:{attachments:t.payload.attachments},turnId:t.payload.turnId,streaming:t.payload.streaming,createdAt:t.payload.createdAt,updatedAt:t.payload.updatedAt}),r=(e.messages.find(e=>e.id===n.id)?e.messages.map(e=>e.id===n.id?{...e,text:n.streaming?`${e.text}${n.text}`:n.text.length>0?n.text:e.text,streaming:n.streaming,...n.turnId===void 0?{}:{turnId:n.turnId},...n.streaming?e.completedAt===void 0?{}:{completedAt:e.completedAt}:n.completedAt===void 0?{}:{completedAt:n.completedAt},...n.attachments===void 0?{}:{attachments:n.attachments}}:e):[...e.messages,n]).slice(-2e3),i=t.payload.role===`assistant`&&t.payload.turnId!==null?gXe(e.turnDiffSummaries,t.payload.turnId,t.payload.messageId):e.turnDiffSummaries,a=t.payload.role===`assistant`&&t.payload.turnId!==null&&(e.latestTurn===null||e.latestTurn.turnId===t.payload.turnId)?Gq({previous:e.latestTurn,turnId:t.payload.turnId,state:t.payload.streaming?`running`:e.latestTurn?.state===`interrupted`?`interrupted`:e.latestTurn?.state===`error`?`error`:`completed`,requestedAt:e.latestTurn?.turnId===t.payload.turnId?e.latestTurn.requestedAt:t.payload.createdAt,startedAt:e.latestTurn?.turnId===t.payload.turnId?e.latestTurn.startedAt??t.payload.createdAt:t.payload.createdAt,sourceProposedPlan:e.pendingSourceProposedPlan,completedAt:t.payload.streaming?e.latestTurn?.turnId===t.payload.turnId?e.latestTurn.completedAt??null:null:t.payload.updatedAt,assistantMessageId:t.payload.messageId}):e.latestTurn;return{...e,messages:r,turnDiffSummaries:i,latestTurn:a,updatedAt:t.occurredAt}});case`thread.session-set`:return Kq(e,t.payload.threadId,e=>({...e,session:pq(t.payload.session),error:$W(t.payload.session.lastError),latestTurn:t.payload.session.status===`running`&&t.payload.session.activeTurnId!==null?Gq({previous:e.latestTurn,turnId:t.payload.session.activeTurnId,state:`running`,requestedAt:e.latestTurn?.turnId===t.payload.session.activeTurnId?e.latestTurn.requestedAt:t.payload.session.updatedAt,startedAt:e.latestTurn?.turnId===t.payload.session.activeTurnId?e.latestTurn.startedAt??t.payload.session.updatedAt:t.payload.session.updatedAt,completedAt:null,assistantMessageId:e.latestTurn?.turnId===t.payload.session.activeTurnId?e.latestTurn.assistantMessageId:null,sourceProposedPlan:e.pendingSourceProposedPlan}):e.latestTurn,updatedAt:t.occurredAt}));case`thread.session-stop-requested`:return Kq(e,t.payload.threadId,e=>e.session===null?e:{...e,session:{...e.session,status:`closed`,orchestrationStatus:`stopped`,activeTurnId:void 0,updatedAt:t.payload.createdAt},updatedAt:t.occurredAt});case`thread.proposed-plan-upserted`:return Kq(e,t.payload.threadId,e=>{let n=hq(t.payload.proposedPlan),r=[...e.proposedPlans.filter(e=>e.id!==n.id),n].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id)).slice(-200);return{...e,proposedPlans:r,updatedAt:t.occurredAt}});case`thread.turn-diff-completed`:return Kq(e,t.payload.threadId,e=>{let n=gq({turnId:t.payload.turnId,checkpointTurnCount:t.payload.checkpointTurnCount,checkpointRef:t.payload.checkpointRef,status:t.payload.status,files:t.payload.files,assistantMessageId:t.payload.assistantMessageId,completedAt:t.payload.completedAt}),r=e.turnDiffSummaries.find(e=>e.turnId===n.turnId);if(r&&r.status!==`missing`&&n.status===`missing`)return e;let i=[...e.turnDiffSummaries.filter(e=>e.turnId!==n.turnId),n].toSorted((e,t)=>(e.checkpointTurnCount??2**53-1)-(t.checkpointTurnCount??2**53-1)).slice(-500),a=e.latestTurn===null||e.latestTurn.turnId===t.payload.turnId?Gq({previous:e.latestTurn,turnId:t.payload.turnId,state:Wq(t.payload.status),requestedAt:e.latestTurn?.requestedAt??t.payload.completedAt,startedAt:e.latestTurn?.startedAt??t.payload.completedAt,completedAt:t.payload.completedAt,assistantMessageId:t.payload.assistantMessageId,sourceProposedPlan:e.pendingSourceProposedPlan}):e.latestTurn;return{...e,turnDiffSummaries:i,latestTurn:a,updatedAt:t.occurredAt}});case`thread.reverted`:return Kq(e,t.payload.threadId,e=>{let n=e.turnDiffSummaries.filter(e=>e.checkpointTurnCount!==void 0&&e.checkpointTurnCount<=t.payload.turnCount).toSorted((e,t)=>(e.checkpointTurnCount??2**53-1)-(t.checkpointTurnCount??2**53-1)).slice(-500),r=new Set(n.map(e=>e.turnId)),i=_Xe(e.messages,r,t.payload.turnCount).slice(-2e3),a=yXe(e.proposedPlans,r).slice(-200),o=vXe(e.activities,r),s=n.at(-1)??null;return{...e,turnDiffSummaries:n,messages:i,proposedPlans:a,activities:o,pendingSourceProposedPlan:void 0,latestTurn:s===null?null:{turnId:s.turnId,state:Wq(s.status??`ready`),requestedAt:s.completedAt,startedAt:s.completedAt,completedAt:s.completedAt,assistantMessageId:s.assistantMessageId??null},updatedAt:t.occurredAt}});case`thread.activity-appended`:return Kq(e,t.payload.threadId,e=>{let n=[...e.activities.filter(e=>e.id!==t.payload.activity.id),{...t.payload.activity}].toSorted(hXe).slice(-500);return{...e,activities:n,updatedAt:t.occurredAt}});case`thread.rate-limit-set`:return Kq(e,t.payload.threadId,e=>({...e,rateLimitStatus:iXe(e.rateLimitStatus??[],t.payload),updatedAt:t.occurredAt}));case`thread.worker-spawned`:return Kq(e,t.payload.workerThreadId,e=>({...e,kind:`worker`,parentThreadId:t.payload.masterThreadId,branch:t.payload.branch,worktreePath:t.payload.worktreePath,workerRole:t.payload.workerRole??e.workerRole??null,updatedAt:t.occurredAt}));case`thread.approval-response-requested`:case`thread.user-input-response-requested`:return e}return e}function EXe(e,t,n){switch(t.kind){case`project-upserted`:{let r=uq(t.project,n),i=e.projectIds.find(n=>n===t.project.id||e.projectById[n]?.cwd===t.project.workspaceRoot)??null,a=e.projectById,o=e.projectIds;if(i!==null&&i!==r.id){let{[i]:t,...n}=e.projectById;a={...n,[r.id]:r},o=e.projectIds.map(e=>e===i?r.id:e)}else a={...e.projectById,[r.id]:r},o=i===null&&!e.projectIds.includes(r.id)?[...e.projectIds,r.id]:e.projectIds;return{...e,projectById:a,projectIds:o}}case`project-removed`:return Uq(e,t.projectId);case`thread-upserted`:return Bq(e,Dq(t.thread,n));case`thread-removed`:return Hq(e,t.threadId)}}function DXe(e,t,n){if(t.length===0)return e;let r=Jq(e,n);return Yq(e,n,t.reduce((e,t)=>Xq(e,t,n),r))}function Zq(e){return Object.entries(e.environmentStateById)}function Qq(e,t){return t?Jq(e,t):Sq}function OXe(e,t){return Lq(Qq(e,t))}function $q(e){return Zq(e).flatMap(([,e])=>pXe(e))}function eJ(e){return Zq(e).flatMap(([,e])=>Lq(e))}function kXe(e){return Zq(e).flatMap(([,e])=>tJ(e).flatMap(t=>{let n=e.threadShellById[t];return n?[n]:[]}))}function tJ(e){let t=[],n=new Set,r=e=>{n.has(e)||(n.add(e),t.push(e))};for(let t of e.threadIds)r(t);for(let t of Object.keys(e.threadShellById))r(t);for(let t of Object.keys(e.sidebarThreadSummaryById))r(t);return t}function nJ(e,t,n){let r=t.sidebarThreadSummaryById[n];if(r)return r.environmentId===e?r:{...r,environmentId:e};let i=t.threadShellById[n];return i?{id:i.id,environmentId:e,projectId:i.projectId,title:i.title,modelSelection:i.modelSelection,interactionMode:i.interactionMode,session:t.threadSessionById[n]??null,createdAt:i.createdAt,archivedAt:i.archivedAt,settledAt:i.settledAt,settledOverride:i.settledOverride,updatedAt:i.updatedAt,latestTurn:t.threadTurnStateById[n]?.latestTurn??null,branch:i.branch,worktreePath:i.worktreePath,latestUserMessageAt:null,hasPendingApprovals:!1,hasPendingUserInput:!1,hasActionableProposedPlan:!1,anchorKind:i.anchorKind,anchorCmmdId:i.anchorCmmdId,goal:i.goal,titleRegeneration:i.titleRegeneration,kind:i.kind,parentThreadId:i.parentThreadId,workerRole:i.workerRole,status:i.status}:null}function AXe(e){return Zq(e).flatMap(([e,t])=>tJ(t).flatMap(n=>{let r=nJ(e,t,n);return r?[r]:[]}))}function rJ(e,t){if(!t)return[];let n=Qq(e,t.environmentId),r=n.threadIdsByProjectId[t.projectId]??Cq;return(r.length>0?r:tJ(n)).flatMap(e=>{let r=nJ(t.environmentId,n,e);return!r||r.projectId!==t.projectId?[]:[r]})}function jXe(e,t){return t.length===0?[]:t.length===1?rJ(e,t[0]):t.flatMap(t=>rJ(e,t))}function MXe(e){return e.activeEnvironmentId===null?Object.values(e.environmentStateById).some(e=>e.bootstrapComplete):Qq(e,e.activeEnvironmentId).bootstrapComplete}function NXe(e,t){return t?Qq(e,t.environmentId).projectById[t.projectId]:void 0}function iJ(e,t){return t?bq(Qq(e,t.environmentId),t.threadId):void 0}function PXe(e,t){return t?Qq(e,t.environmentId).threadShellById[t.threadId]!==void 0:!1}function aJ(e,t){return t?nJ(t.environmentId,Qq(e,t.environmentId),t.threadId)??void 0:void 0}function FXe(e,t,n){if(e.activeEnvironmentId===null)return e;let r=Kq(Jq(e,e.activeEnvironmentId),t,e=>e.error===n?e:{...e,error:n});return Yq(e,e.activeEnvironmentId,r)}function IXe(e,t,n){return Yq(e,n,Xq(Jq(e,n),t,n))}function LXe(e,t,n){return Yq(e,n,EXe(Jq(e,n),t,n))}function RXe(e,t){return e.activeEnvironmentId===t?e:{...e,activeEnvironmentId:t}}function zXe(e,t,n,r){let i=Kq(Jq(e,t.environmentId),t.threadId,e=>{if(e.branch===n&&e.worktreePath===r)return e;let t=e.worktreePath!==r;return{...e,branch:n,worktreePath:r,...t?{session:null}:{}}});return Yq(e,t.environmentId,i)}var oJ=Jt(e=>({...aXe,setActiveEnvironmentId:t=>e(e=>RXe(e,t)),syncServerShellSnapshot:(t,n)=>e(e=>SXe(e,t,n)),syncServerThreadDetail:(t,n)=>e(e=>CXe(e,t,n)),setThreadSubscriptionError:(t,n,r)=>e(e=>wXe(e,t,n,r)),clearThreadSubscriptionError:(t,n)=>e(e=>TXe(e,t,n)),applyOrchestrationEvent:(t,n)=>e(e=>IXe(e,t,n)),applyOrchestrationEvents:(t,n)=>e(e=>DXe(e,t,n)),applyShellEvent:(t,n)=>e(e=>LXe(e,t,n)),setError:(t,n)=>e(e=>FXe(e,t,n)),setThreadBranch:(t,n,r)=>e(e=>zXe(e,t,n,r))})),sJ=`Thread not found or you no longer have access.`;function BXe(e){if(e==null)return sJ;let t=eq(ste(e)?Ie(e):e,sJ);return/\bnot found\b/i.test(t)?sJ:t}function VXe(e,t,n){oJ.getState().setThreadSubscriptionError(e,t,BXe(n))}function cJ(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var HXe={enabled:!0,leading:!0,trailing:!0,wait:0},UXe=class{#e;constructor(e,t){this.fn=e,this.store=new Dte(cJ()),this.setOptions=e=>{this.options={...this.options,...e},this.#n()||this.cancel()},this.#t=e=>{this.store.setState(t=>{let n={...t,...e},{isPending:r}=n;return{...n,status:this.#n()?r?`pending`:`idle`:`disabled`}}),Ste(`Throttler`,this)},this.#n=()=>!!qt(this.options.enabled,this),this.#r=()=>qt(this.options.wait,this),this.maybeExecute=(...e)=>{this.#t({maybeExecuteCount:this.store.state.maybeExecuteCount+1});let t=Date.now(),n=t-this.store.state.lastExecutionTime,r=this.#r();if(this.options.leading&&n>=r)this.#i(...e);else if(this.#t({lastArgs:e}),!this.#e&&this.options.trailing){let e=r-(this.store.state.lastExecutionTime?t-this.store.state.lastExecutionTime:0);this.#t({isPending:!0}),this.#e=setTimeout(()=>{let{lastArgs:e}=this.store.state;e!==void 0&&this.#i(...e)},e)}},this.#i=(...e)=>{if(!this.#n())return;this.fn(...e);let t=Date.now(),n=t+this.#r();this.#a(),this.#t({executionCount:this.store.state.executionCount+1,lastExecutionTime:t,nextExecutionTime:n,isPending:!1,lastArgs:void 0}),this.options.onExecute?.(e,this),setTimeout(()=>{this.store.state.isPending||this.#t({nextExecutionTime:void 0})},this.#r())},this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&this.#i(...this.store.state.lastArgs)},this.#a=()=>{this.#e&&=(clearTimeout(this.#e),void 0)},this.cancel=()=>{this.#a(),this.#t({lastArgs:void 0,isPending:!1})},this.reset=()=>{this.#t(cJ())},this.key=t.key,this.options={...HXe,...t},this.#t(this.options.initialState??{}),this.key&&Tte.on(`d-Throttler`,e=>{e.payload.key===this.key&&(this.#t(e.payload.store.state),this.setOptions(e.payload.options))})}#t;#n;#r;#i;#a};function WXe(e){return!!(e.prompt.trim()||e.images.length||e.terminalContexts.length||e.persistedAttachments.length||e.stagedSubmission)}function GXe(e,t,n){let r=Ro(t),i=Ro(n);if(r===i)return e;let a=e[r];if(!a)return e;let o=e[i];if(o&&WXe(o)&&!KXe(a,o))return null;let s={...e,[i]:{...a,...eZe(a,o)}};return delete s[r],s}function KXe(e,t){let n=e.stagedSubmission;return!n||!qXe(n)||!JXe(e,n)||!YXe(n,t.stagedSubmission)?!1:XXe(e,t)}function qXe(e){return!!e.commandId&&!!e.messageId}function JXe(e,t){return[e.prompt===t.prompt,uJ(e.persistedAttachments,t.attachments),uJ(e.terminalContexts,t.terminalContexts)].every(Boolean)}function YXe(e,t){return!t||ZXe(e,t)}function XXe(e,t){return[e.prompt===t.prompt,e.lastGeneratedPullRequestPrompt===t.lastGeneratedPullRequestPrompt,fJ(e.images,t.images),dJ(e.nonPersistedImageIds,t.nonPersistedImageIds),e.nonPersistedImageIds.length===0,fJ(e.persistedAttachments,t.persistedAttachments),fJ(e.terminalContexts,t.terminalContexts),$Xe(e.modelSelectionByProvider,t.modelSelectionByProvider),e.activeProvider===t.activeProvider,e.runtimeMode===t.runtimeMode,e.interactionMode===t.interactionMode].every(Boolean)}function ZXe(e,t){return[e.commandId===t.commandId&&e.messageId===t.messageId,e.prompt===t.prompt,uJ(e.attachments,t.attachments),uJ(e.terminalContexts,t.terminalContexts),lJ(e.modelSelection,t.modelSelection),lJ(e.runtimeMode,t.runtimeMode),lJ(e.interactionMode,t.interactionMode),QXe(e.executionIntent,t.executionIntent)].every(Boolean)}function lJ(e,t){return e===void 0||t===void 0||JSON.stringify(e)===JSON.stringify(t)}function QXe(e,t){return!e||!t||e.runtimeId===t.runtimeId}function uJ(e,t){return e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id)}function dJ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function fJ(e,t){return e.length===t.length&&e.every((e,n)=>JSON.stringify(e)===JSON.stringify(t[n]))}function $Xe(e,t){let n=Object.keys(e).toSorted();return dJ(n,Object.keys(t).toSorted())?n.every(n=>JSON.stringify(e[n])===JSON.stringify(t[n])):!1}function eZe(e,t){let n=t??e,r=e.stagedSubmission?e:n,i=e.stagedSubmission?n:e;return{modelSelectionByProvider:{...i.modelSelectionByProvider,...r.modelSelectionByProvider},activeProvider:r.activeProvider??i.activeProvider,runtimeMode:r.runtimeMode??i.runtimeMode,interactionMode:r.interactionMode??i.interactionMode}}var pJ=`full-access`,mJ=`default`,hJ=`default`,tZe=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,nZe=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function gJ(e){return e.replace(/\r\n/g,`
1007
1007
  `).replace(/^\n+|\n+$/g,``)}function _J(e){return gJ(e.text).length>0}function rZe(e){return!_J(e)}function iZe(e){return e.filter(e=>_J(e))}function aZe(e){let t=gJ(e.text),n=e.terminalId.trim(),r=e.terminalLabel.trim();if(t.length===0||n.length===0||r.length===0)return null;let i=Math.max(1,Math.floor(e.lineStart));return{terminalId:n,terminalLabel:r,lineStart:i,lineEnd:Math.max(i,Math.floor(e.lineEnd)),text:t}}function oZe(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function vJ(e){return`${e.terminalLabel} ${oZe(e)}`}function yJ(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function sZe(e){return gJ(e.text).split(`
1008
1008
  `).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function cZe(e){let t=e.map(e=>aZe(e)).filter(e=>e!==null);if(t.length===0)return``;let n=[];for(let e=0;e<t.length;e+=1){let r=t[e];n.push(`- ${vJ(r)}:`),n.push(...sZe(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
@@ -2531,4 +2531,4 @@ XID_Start XIDS`.split(/\s/).map(e=>[S5(e),e])),Eat=new Map([[`s`,G5(383)],[G5(38
2531
2531
  ${e}
2532
2532
  }
2533
2533
  }`}function Tst(e,t){let n=y9(t);return e.replace(Sst,n)}function Est(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Dst({code:e,pre:t,columnType:n,rowSpan:r,containerSize:i=!1}={}){return e??(e=document.createElement(`code`),e.setAttribute(`data-code`,``),n!=null&&e.setAttribute(`data-${n}`,``),t?.appendChild(e)),r==null?e.style.removeProperty(`grid-row`):e.style.setProperty(`grid-row`,`span ${r}`),i?e.setAttribute(`data-container-size`,``):e.removeAttribute(`data-container-size`),e}function Ost(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function kst(e,{type:t,diffIndicators:n,disableBackground:r,disableLineNumbers:i,overflow:a,split:o,totalLines:s,customProperties:c}){if(c!=null)for(let t in c){let n=c[t];n!=null&&e.setAttribute(t,`${n}`)}switch(t===`diff`?(e.setAttribute(`data-diff`,``),e.removeAttribute(`data-file`)):(e.setAttribute(`data-file`,``),e.removeAttribute(`data-diff`)),n){case`bars`:case`classic`:e.setAttribute(`data-indicators`,n);break;case`none`:e.removeAttribute(`data-indicators`)}return i?e.setAttribute(`data-disable-line-numbers`,``):e.removeAttribute(`data-disable-line-numbers`),r?e.removeAttribute(`data-background`):e.setAttribute(`data-background`,``),t===`diff`?e.setAttribute(`data-diff-type`,o?`split`:`single`):e.removeAttribute(`data-diff-type`),e.setAttribute(`data-overflow`,a),e.style.setProperty(`--diffs-min-number-column-width-default`,`${`${s}`.length}ch`),e}function Ast(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function jst(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function Mst(e,t){let n=e?.offsetHeight??0;if(e==null||n===0){t();return}e.style.minHeight=`${n}px`;try{t(),e.offsetHeight}finally{e.style.minHeight=``}}function Nst({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=Pst(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function Pst(){let e=document.createElement(`style`);return e.setAttribute(aet,``),e}var Fst=void 0;function Ist(){return Fst??=`safari`in window&&`pushNotification`in window.safari||/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}if(typeof HTMLElement<`u`&&customElements.get(`diffs-container`)==null){let e;class t extends HTMLElement{constructor(){if(super(),this.shadowRoot!=null)return;let t=this.attachShadow({mode:`open`});e??(e=new CSSStyleSheet,e.replaceSync(xst)),t.adoptedStyleSheets=[e]}connectedCallback(){v9(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(L2,t)}function Lst(e){return{...W2,...e}}function Rst(e,t){let n=zst(e,t);return t?n:e.diffHeaderHeight+n}function zst(e,t){return e.paddingTop??(t?e.spacing:0)}function Bst(e){return e.paddingBottom??e.spacing}function Vst(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function x9(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function S9(e,t){return Z2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function C9({line:e,spanStart:t,spanLength:n}){return{start:{line:e,character:t},end:{line:e,character:t+n},properties:{"data-diff-span":``},alwaysWrap:!0}}function w9({item:e,arr:t,enableJoin:n,isNeutral:r=!1,isLastItem:i=!1}){let a=t[t.length-1];if(a==null||i||!n){t.push([+!r,e.value]);return}let o=a[0]===0;if(r===o||r&&e.value.length===1&&!o){a[1]+=e.value;return}t.push([+!r,e.value])}function T9(e){return[t4(e.additionStart,e.additionCount)+1,n4(e.additionStart,e.additionCount)+1]}function E9({isPartial:e,rangeSize:t,expandedHunks:n,hunkIndex:r,collapsedContextThreshold:i}){let a=Math.max(t,0);if(a===0||e)return{fromStart:0,fromEnd:0,rangeSize:a,collapsedLines:a,renderAll:!1};if(n===!0||a<=i)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(r),s=Math.min(Math.max(o?.fromStart??0,0),a),c=Math.min(Math.max(o?.fromEnd??0,0),a),l=s+c,u=l>=a;return{fromStart:u?a:s,fromEnd:u?0:c,rangeSize:a,collapsedLines:Math.max(a-l,0),renderAll:u}}function Hst(e){let t=e.hunks[e.hunks.length-1];if(t==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return!1;let n=e.additionLines.length-n4(t.additionStart,t.additionCount),r=e.deletionLines.length-n4(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function D9({fileDiff:e,errorPrefix:t}){let n=e.hunks[e.hunks.length-1];if(n==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return 0;let r=e.additionLines.length-n4(n.additionStart,n.additionCount),i=e.deletionLines.length-n4(n.deletionStart,n.deletionCount);if(r<=0&&i<=0)return 0;if(r!==i)throw Error(`${t}: trailing context mismatch (additions=${r}, deletions=${i}) for ${e.name}`);return Math.min(r,i)}function O9({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=D9({fileDiff:e,errorPrefix:i});if(a<=0)return;if(n===!0||a<=r)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(e.hunks.length),s=Math.min(Math.max(o?.fromStart??0,0),a);return{fromStart:s,fromEnd:0,rangeSize:a,collapsedLines:a-s,renderAll:s>=a}}function Ust({fileDiff:e,lineNumber:t,expandedHunks:n,collapsedContextThreshold:r}){if(n===!0||e.isPartial)return!0;for(let[i,a]of e.hunks.entries()){let[o,s]=T9(a);if(t<o){let s=E9({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:n,hunkIndex:i,collapsedContextThreshold:r}),c=o-s.rangeSize;return s.renderAll||t<c+s.fromStart||t>=o-s.fromEnd}if(t<s)return!0}let i=O9({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:`isAdditionLineRenderable`});if(i==null||i.renderAll)return!0;let a=e.hunks[e.hunks.length-1],[,o]=T9(a);return t<o+i.fromStart||t>=o+i.rangeSize}function Wst({fileDiff:e,lineNumber:t,direction:n,expandedHunks:r,collapsedContextThreshold:i}){if(r===!0||e.isPartial)return t;let a=[],o=1;for(let[t,n]of e.hunks.entries()){let[s,c]=T9(n),l=E9({isPartial:e.isPartial,rangeSize:n.collapsedBefore,expandedHunks:r,hunkIndex:t,collapsedContextThreshold:i}),u=s-l.rangeSize;l.renderAll?a.push([u,s]):(l.fromStart>0&&a.push([u,u+l.fromStart]),l.fromEnd>0&&a.push([s-l.fromEnd,s])),a.push([s,c]),o=c}let s=O9({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:i,errorPrefix:`getNearestRenderableAdditionLine`});if(s!=null){let e=o;o=e+s.rangeSize,s.renderAll?a.push([e,o]):s.fromStart>0&&a.push([e,e+s.fromStart])}if(t>=o)return t;if(n===`down`){for(let[e,n]of a)if(n>t)return Math.max(e,t);return}for(let e=a.length-1;e>=0;e--){let[n,r]=a[e];if(n<=t)return Math.min(r-1,t)}}function k9({type:e,metrics:t}){return t.hunkSeparatorHeight??Vst(e)}function A9({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function Gst({type:e,hunkIndex:t,hunkSpecs:n}){switch(e){case`simple`:return t>0;case`metadata`:return n!=null;case`line-info`:case`line-info-basic`:case`custom`:return!0}}function Kst(e){return e!==`simple`&&e!==`metadata`}function qst({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!Gst({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=k9({type:e,metrics:t}),a=A9({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function Jst({type:e,metrics:t}){if(!Kst(e))return;let n=k9({type:e,metrics:t}),r=A9({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function j9({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=Yst({diff:e,diffStyle:t,startingLine:n,expandedHunks:i,collapsedContextThreshold:a}),c={viewportStart:n,viewportEnd:n+r,isWindowedHighlight:n>0||r<1/0,splitCount:s.splitCount,unifiedCount:s.unifiedCount,finalHunkIndex:e.hunks.length-1,shouldBreak(){if(!c.isWindowedHighlight)return!1;let e=c.unifiedCount>=n+r,i=c.splitCount>=n+r;return t===`unified`?e:(t===`split`||e)&&i},shouldSkip(e,r){if(!c.isWindowedHighlight)return!1;let i=e>0&&c.unifiedCount+e<=n,a=r>0&&c.splitCount+r<=n;return t===`unified`?i:(t===`split`||i)&&a},incrementCounts(e,n){(t===`unified`||t===`both`)&&(c.unifiedCount+=e),(t===`split`||t===`both`)&&(c.splitCount+=n)},isInWindow(e,n){if(!c.isWindowedHighlight)return!0;let r=c.isInUnifiedWindow(e),i=c.isInSplitWindow(n);return t===`unified`?r:t===`split`?i:r||i},isInUnifiedWindow(e){return!c.isWindowedHighlight||c.unifiedCount>=n-e&&c.unifiedCount<n+r},isInSplitWindow(e){return!c.isWindowedHighlight||c.splitCount>=n-e&&c.splitCount<n+r},emit(e,n=!1){return n||(t===`unified`?c.incrementCounts(1,0):t===`split`?c.incrementCounts(0,1):c.incrementCounts(1,1)),o(e)??!1}};hunkIterator:for(let n=s.hunkIndex;n<e.hunks.length;n++){let r=e.hunks[n];if(r==null)throw Error(`iterateOverDiff: invalid hunk index`);if(c.shouldBreak())break;let o=t4(r.deletionStart,r.deletionCount),s=t4(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=E9({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?O9({fileDiff:e,hunkIndex:n,expandedHunks:i,collapsedContextThreshold:a,errorPrefix:`iterateOverDiff`}):void 0,p=d.fromStart+d.fromEnd;function m(e,n){return f==null||f.collapsedLines<=0||f.fromStart+f.fromEnd>0?0:t===`unified`?e===r.unifiedLineStart+r.unifiedLineCount-1?f.collapsedLines:0:n===r.splitLineStart+r.splitLineCount-1?f.collapsedLines:0}let h=d.collapsedLines===0;function g(){return h?0:(h=!0,d.collapsedLines)}if(c.shouldSkip(p,p))c.incrementCounts(p,p),g();else{let e=r.unifiedLineStart-d.rangeSize,i=r.splitLineStart-d.rangeSize,a=l-d.rangeSize,f=u-d.rangeSize,p=o+1-d.rangeSize,m=s+1-d.rangeSize;if(M9(c,d.fromStart,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:0,collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}))||(e=r.unifiedLineStart-d.fromEnd,i=r.splitLineStart-d.fromEnd,a=l-d.fromEnd,f=u-d.fromEnd,p=o+1-d.fromEnd,m=s+1-d.fromEnd,M9(c,d.fromEnd,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}),()=>{g()})))break hunkIterator}let _=r.unifiedLineStart,v=r.splitLineStart,y=l,b=u,x=o+1,S=s+1,C=r.hunkContent.at(-1);for(let e of r.hunkContent){if(c.shouldBreak())break hunkIterator;let i=e===C;if(e.type===`context`){if(c.shouldSkip(e.lines,e.lines))c.incrementCounts(e.lines,e.lines),g();else if(M9(c,e.lines,t,t=>{let a=i&&t===e.lines-1,o=_+t,s=v+t;return c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:m(o,s),type:`context`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:a&&r.noEOFCRDeletions,unifiedLineIndex:o,splitLineIndex:s},additionLine:{unifiedLineIndex:o,splitLineIndex:s,lineIndex:b+t,lineNumber:S+t,noEOFCR:a&&r.noEOFCRAdditions}})},()=>{g()}))break hunkIterator;_+=e.lines,v+=e.lines,y+=e.lines,b+=e.lines,x+=e.lines,S+=e.lines}else{let a=Math.max(e.deletions,e.additions),o=e.deletions+e.additions;if(!c.shouldSkip(o,a)){let s=Qst(c,e,t);(s[0]?.[0]??0)>0&&g();for(let[l,u]of s)for(let s=l;s<u;s++){let l=m(_+s,t===`unified`?v+(s<e.deletions?s:s-e.deletions):v+s);if(c.emit($st({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:l,diffStyle:t,index:s,unifiedLineIndex:_,splitLineIndex:v,additionLineIndex:b,deletionLineIndex:y,additionLineNumber:S,deletionLineNumber:x,content:e,isLastContent:i,unifiedCount:o,splitCount:a}),!0))break hunkIterator}}g(),c.incrementCounts(o,a),_+=o,v+=a,y+=e.deletions,b+=e.additions,x+=e.deletions,S+=e.additions}}if(f!=null){let{collapsedLines:n,fromStart:r,fromEnd:i}=f,a=r+i;if(M9(c,a,t,t=>{let r=t===a-1;return c.emit({hunkIndex:e.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:r?n:0,type:`context-expanded`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:!1,unifiedLineIndex:_+t,splitLineIndex:v+t},additionLine:{unifiedLineIndex:_+t,splitLineIndex:v+t,lineIndex:b+t,lineNumber:S+t,noEOFCR:!1}})},void 0,()=>c.shouldBreak()))break hunkIterator}}}function Yst({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=Xst({diff:e,expandedHunks:r,collapsedContextThreshold:i}),o=0,s=e.hunks.length-1,c=e.hunks.length;for(;o<=s;){let e=o+s>>1,r=a[e+1];if(r==null)throw Error(`iterateOverDiff: invalid hunk prefix index`);(t===`unified`?r.unifiedCount:r.splitCount)>n?(c=e,s=e-1):o=e+1}if(c>=e.hunks.length){let t=a[e.hunks.length];if(t==null)throw Error(`iterateOverDiff: invalid terminal hunk prefix index`);return{hunkIndex:e.hunks.length,splitCount:t.splitCount,unifiedCount:t.unifiedCount}}let l=a[c];if(l==null)throw Error(`iterateOverDiff: invalid selected hunk prefix index`);return{hunkIndex:c,splitCount:l.splitCount,unifiedCount:l.unifiedCount}}function Xst({diff:e,expandedHunks:t,collapsedContextThreshold:n}){let r=0,i=0,a=e.hunks.length-1,o=[{splitCount:0,unifiedCount:0}];for(let s=0;s<e.hunks.length;s++){let c=e.hunks[s];if(c==null)throw Error(`iterateOverDiff: invalid hunk summary index`);let l=E9({isPartial:e.isPartial,rangeSize:c.collapsedBefore,expandedHunks:t,hunkIndex:s,collapsedContextThreshold:n}),u=l.fromStart+l.fromEnd;r+=u+c.splitLineCount,i+=u+c.unifiedLineCount;let d=s===a?O9({fileDiff:e,hunkIndex:s,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:`iterateOverDiff`}):void 0;if(d!=null){let e=d.fromStart+d.fromEnd;r+=e,i+=e}o.push({splitCount:r,unifiedCount:i})}return o}function Zst(e,t,n){if(!e.isWindowedHighlight||t<=0)return[0,t];let r=[];function i(n){let i=Math.max(0,e.viewportStart-n),a=Math.min(t,e.viewportEnd-n);a>i&&r.push([i,a])}if(n!==`split`&&i(e.unifiedCount),n!==`unified`&&i(e.splitCount),r.length===0)return[0,0];let a=r[0][0],o=r[0][1];for(let e=1;e<r.length;e++){let t=r[e];a=Math.min(a,t[0]),o=Math.max(o,t[1])}return[a,o]}function M9(e,t,n,r,i,a){let[o,s]=Zst(e,t,n);o>0&&(e.incrementCounts(o,o),i?.());let c=o;for(;c<t;){if(a?.()===!0)return!0;if(c>=s){e.incrementCounts(t-c,t-c);break}if(e.isInWindow(0,0)){if(r(c)===!0)return!0}else e.incrementCounts(1,1);c++}return!1}function Qst(e,t,n){if(!e.isWindowedHighlight)return[[0,n===`unified`?t.deletions+t.additions:Math.max(t.deletions,t.additions)]];let r=n!==`split`,i=n!==`unified`,a=n===`unified`?`unified`:`split`,o=[];function s(t,n){if(t+n<=e.viewportStart||t>=e.viewportEnd)return;let r=Math.max(0,e.viewportStart-t),i=Math.min(n,e.viewportEnd-t);return i>r?[r,i]:void 0}function c(e,n){return a===`split`?e:n===`additions`?[e[0]+t.deletions,e[1]+t.deletions]:e}function l(e,t){if(e==null)return;let[n,r]=c(e,t);r>n&&o.push([n,r])}if(r&&(l(s(e.unifiedCount,t.deletions),`deletions`),l(s(e.unifiedCount+t.deletions,t.additions),`additions`)),i&&(l(s(e.splitCount,t.deletions),`deletions`),l(s(e.splitCount,t.additions),`additions`)),o.length===0)return o;o.sort((e,t)=>e[0]-t[0]);let u=[o[0]];for(let[e,t]of o.slice(1)){let n=u[u.length-1];e<=n[1]?n[1]=Math.max(n[1],t):u.push([e,t])}return u}function $st({hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,diffStyle:i,index:a,unifiedLineIndex:o,splitLineIndex:s,additionLineIndex:c,deletionLineIndex:l,additionLineNumber:u,deletionLineNumber:d,content:f,isLastContent:p,unifiedCount:m,splitCount:h}){let g=a<f.deletions?o+a:void 0,_=i===`unified`?a>=f.deletions?o+a:void 0:a<f.additions?o+f.deletions+a:void 0,v=i===`unified`?s+(a<f.deletions?a:a-f.deletions):s+a,y=a<f.deletions?l+a:void 0,b=a<f.deletions?d+a:void 0,x=i===`unified`?a>=f.deletions?c+(a-f.deletions):void 0:a<f.additions?c+a:void 0,S=i===`unified`?a>=f.deletions?u+(a-f.deletions):void 0:a<f.additions?u+a:void 0,C=i===`unified`?p&&a===f.deletions-1&&t.noEOFCRDeletions:p&&a===h-1&&t.noEOFCRDeletions,w=i===`unified`?p&&a===m-1&&t.noEOFCRAdditions:p&&a===h-1&&t.noEOFCRAdditions,T=y!=null&&b!=null&&g!=null?{lineNumber:b,lineIndex:y,noEOFCR:C,unifiedLineIndex:g,splitLineIndex:v}:void 0,E=x!=null&&S!=null&&_!=null?{unifiedLineIndex:_,splitLineIndex:v,lineIndex:x,lineNumber:S,noEOFCR:w}:void 0;if(T==null&&E!=null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:void 0,additionLine:E};if(T!=null&&E==null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:T,additionLine:void 0};if(T==null||E==null)throw Error(`iterateOverDiff: missing change line data`);return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:T,additionLine:E}}var ect={forcePlainText:!1};function N9(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=ect){r?(i??=0,a??=1/0):(i=0,a=1/0);let c=i>0||a<1/0,l=typeof n.theme==`string`?t.getTheme(n.theme).type:void 0,u=c9({theme:n.theme,highlighter:t}),d=r&&!c&&(e.unifiedLineCount>1e3||e.splitLineCount>1e3)?`none`:n.lineDiffType,f={deletionLines:[],additionLines:[]},{maxLineDiffLength:p}=n,m=!r&&!e.isPartial,h=r?o:void 0,g=new Map;function _(e){let t=m?0:e,n=g.get(t)??nct();return g.set(t,n),n}function v(e,t,n,r){if(c){let e=n.at(-1);(e==null||e.targetIndex+e.count!==t)&&(e={targetIndex:t,originalOffset:r.length,count:0},n.push(e)),e.count++}r.push(e)}j9({diff:e,diffStyle:`both`,startingLine:i,totalLines:a,expandedHunks:!c||h,collapsedContextThreshold:s,callback:({hunkIndex:t,additionLine:n,deletionLine:r,type:i})=>{let a=_(t),o=n==null?r.splitLineIndex:n.splitLineIndex;i===`change`&&n!=null&&r!=null&&tct({additionLine:e.additionLines[n.lineIndex],deletionLine:e.deletionLines[r.lineIndex],deletionLineIndex:a.deletionContent.length,additionLineIndex:a.additionContent.length,deletionDecorations:a.deletionDecorations,additionDecorations:a.additionDecorations,lineDiffType:d,maxLineDiffLength:p}),r!=null&&(v(e.deletionLines[r.lineIndex],r.lineIndex,a.deletionSegments,a.deletionContent),a.deletionInfo.push({type:i===`change`?`change-deletion`:i,lineNumber:r.lineNumber,altLineNumber:i===`change`?void 0:n.lineNumber??void 0,lineIndex:`${r.unifiedLineIndex},${o}`})),n!=null&&(v(e.additionLines[n.lineIndex],n.lineIndex,a.additionSegments,a.additionContent),a.additionInfo.push({type:i===`change`?`change-addition`:i,lineNumber:n.lineNumber,altLineNumber:i===`change`?void 0:r.lineNumber??void 0,lineIndex:`${n.unifiedLineIndex},${o}`}))}});for(let i of g.values()){if(i.deletionContent.length===0&&i.additionContent.length===0)continue;let a={name:e.prevName??e.name,contents:i.deletionContent.value},o={name:e.name,contents:i.additionContent.value},{deletionLines:s,additionLines:c}=rct({deletionFile:a,deletionInfo:i.deletionInfo,deletionDecorations:i.deletionDecorations,additionFile:o,additionInfo:i.additionInfo,additionDecorations:i.additionDecorations,highlighter:t,options:n,languageOverride:r?`text`:e.lang});if(m){f.deletionLines=s,f.additionLines=c;continue}if(i.deletionSegments.length>0)for(let e of i.deletionSegments)for(let t=0;t<e.count;t++)f.deletionLines[e.targetIndex+t]=s[e.originalOffset+t];else f.deletionLines.push(...s);if(i.additionSegments.length>0)for(let e of i.additionSegments)for(let t=0;t<e.count;t++)f.additionLines[e.targetIndex+t]=c[e.originalOffset+t];else f.additionLines.push(...c)}return{code:f,themeStyles:u,baseThemeType:l}}function tct({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=e4(e),t=e4(t),e.length>s||t.length>s))return;let c=o===`char`?xet(e,t):Eet(e,t),l=[],u=[],d=o===`word-alt`,f=c.at(-1);for(let e of c){let t=e===f;!e.added&&!e.removed?(w9({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),w9({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?w9({item:e,arr:l,enableJoin:d,isLastItem:t}):w9({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(C9({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(C9({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function nct(){return{deletionContent:{push(e){this.value+=e,this.length++},value:``,length:0},additionContent:{push(e){this.value+=e,this.length++},value:``,length:0},deletionInfo:[],additionInfo:[],deletionDecorations:[],additionDecorations:[],deletionSegments:[],additionSegments:[]}}function rct({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=H2,...l}}){let u=s??K7(e.name),d=s??K7(t.name),{state:f,transformers:p}=$7(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:t9(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:t9(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,u9(i.codeToHast(e4(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,u9(i.codeToHast(e4(t.contents),m)))}}function P9(e){let t=e.lang??K7(e.name),n=e.lang??(e.prevName==null?`text`:K7(e.prevName));return t===`text`&&n===`text`}function F9(e){let t=[];for(let n of e){let e=R3.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function I9(e){for(let t of Array.isArray(e)?e:[e])if(!R3.has(t))return!1;return!0}async function L9(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=E7(r)??T7(r);`then`in e?n.push(e):t.push(e)}return n.length>0&&await Promise.all(n).then(e=>{for(let n of e){if(n==null)throw Error(`resolvedLanguages: unable to resolve language`);t.push(n)}}),t}function R9(e){return j7.getResolvedThemes(e)}async function z9(e){for(let t of e)L7(t);let t=await j7.resolveThemes(e);for(let n=0;n<e.length;n++)R7(e[n],t[n]);return t}var B9={light:`pierre-light`,dark:`pierre-dark`};function ict(e){return e===`dark`?B9.dark:B9.light}var V9=2166136261,H9=16777619,act=2654435769,oct=2246822507;function U9(e,t=V9,n=H9){let r=t>>>0;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,n)>>>0;return r>>>0}function sct(e,t=`diff-panel`){let n=e.trim(),r=U9(n,V9,H9).toString(36),i=U9(n,act,oct).toString(36);return`${t}:${n.length}:${r}:${i}`}function cct(e){let t=(0,F.useRef)(e);return(0,F.useInsertionEffect)(()=>void(t.current=e)),(0,F.useCallback)((...e)=>t.current(...e),[])}var lct=(0,F.createContext)(void 0);function uct(){return(0,F.useContext)(lct)}var dct={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},fct={display:`contents`};function pct(){return null}var W9=t(n(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):r((n||=self).lru_map=n.lru_map||{})})(e,function(e){let t=Symbol(`newer`),n=Symbol(`older`);class r{constructor(e,t){typeof e!=`number`&&(t=e,e=0),this.size=0,this.limit=e,this.oldest=this.newest=void 0,this._keymap=new Map,t&&(this.assign(t),e<1&&(this.limit=this.size))}_markEntryAsUsed(e){e!==this.newest&&(e[t]&&(e===this.oldest&&(this.oldest=e[t]),e[t][n]=e[n]),e[n]&&(e[n][t]=e[t]),e[t]=void 0,e[n]=this.newest,this.newest&&(this.newest[t]=e),this.newest=e)}assign(e){let r,a=this.limit||Number.MAX_VALUE;this._keymap.clear();let o=e[Symbol.iterator]();for(let e=o.next();!e.done;e=o.next()){let o=new i(e.value[0],e.value[1]);if(this._keymap.set(o.key,o),r?(r[t]=o,o[n]=r):this.oldest=o,r=o,a--==0)throw Error(`overflow`)}this.newest=r,this.size=this._keymap.size}get(e){var t=this._keymap.get(e);return t?(this._markEntryAsUsed(t),t.value):void 0}set(e,r){var a=this._keymap.get(e);return a?(a.value=r,this._markEntryAsUsed(a),this):(this._keymap.set(e,a=new i(e,r)),this.newest?(this.newest[t]=a,a[n]=this.newest):this.oldest=a,this.newest=a,++this.size,this.size>this.limit&&this.shift(),this)}shift(){var e=this.oldest;if(e)return this.oldest[t]?(this.oldest=this.oldest[t],this.oldest[n]=void 0):(this.oldest=void 0,this.newest=void 0),e[t]=e[n]=void 0,this._keymap.delete(e.key),--this.size,[e.key,e.value]}find(e){let t=this._keymap.get(e);return t?t.value:void 0}has(e){return this._keymap.has(e)}delete(e){var r=this._keymap.get(e);return r?(this._keymap.delete(r.key),r[t]&&r[n]?(r[n][t]=r[t],r[t][n]=r[n]):r[t]?(r[t][n]=void 0,this.oldest=r[t]):r[n]?(r[n][t]=void 0,this.newest=r[n]):this.oldest=this.newest=void 0,this.size--,r.value):void 0}clear(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new o(this.oldest)}values(){return new s(this.oldest)}entries(){return this}[Symbol.iterator](){return new a(this.oldest)}forEach(e,n){typeof n!=`object`&&(n=this);let r=this.oldest;for(;r;)e.call(n,r.value,r.key,this),r=r[t]}toJSON(){for(var e=Array(this.size),n=0,r=this.oldest;r;)e[n++]={key:r.key,value:r.value},r=r[t];return e}toString(){for(var e=``,n=this.oldest;n;)e+=String(n.key)+`:`+n.value,n=n[t],n&&(e+=` < `);return e}}e.LRUMap=r;function i(e,r){this.key=e,this.value=r,this[t]=void 0,this[n]=void 0}function a(e){this.entry=e}a.prototype[Symbol.iterator]=function(){return this},a.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:[e.key,e.value]}):{done:!0,value:void 0}};function o(e){this.entry=e}o.prototype[Symbol.iterator]=function(){return this},o.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.key}):{done:!0,value:void 0}};function s(e){this.entry=e}s.prototype[Symbol.iterator]=function(){return this},s.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.value}):{done:!0,value:void 0}}})}))(),1),G9=Symbol(`IGNORE_RESPONSE`),K9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled because the pool terminated`)}},q9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled before the task completed`)}},mct=class{options;highlighter;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(e,{langs:t,theme:n=H2,useTokenTransformer:r=!1,lineDiffType:i=`word-alt`,maxLineDiffLength:a=1e3,tokenizeMaxLineLength:o=1e3,preferredHighlighter:s=`shiki-js`}){this.options=e,this.preferredHighlighter=s,this.renderOptions={theme:n,useTokenTransformer:r,lineDiffType:i,maxLineDiffLength:a,tokenizeMaxLineLength:o},this.fileCache=new W9.default.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new W9.default.LRUMap(e.totalASTLRUCacheSize??100),this.queueInitialization(t)}isWorkingPool(){return!this.workersFailed}getFileResultCache(e){return e.cacheKey==null?void 0:this.fileCache.get(e.cacheKey)}getDiffResultCache(e){return e.cacheKey==null?void 0:this.diffCache.get(e.cacheKey)}inspectCaches(){let{fileCache:e,diffCache:t}=this;return{fileCache:e,diffCache:t}}evictFileFromCache(e){try{return this.fileCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(e){try{return this.diffCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme:e=this.renderOptions.theme??H2,useTokenTransformer:t=this.renderOptions.useTokenTransformer??!1,lineDiffType:n=this.renderOptions.lineDiffType??`word-alt`,maxLineDiffLength:r=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength:i=this.renderOptions.tokenizeMaxLineLength??1e3}){let{lifecycleGeneration:a}=this,o=++this.renderOptionsRequestVersion,s=()=>this.isCurrentLifecycle(a)&&this.renderOptionsRequestVersion===o;try{let a={theme:e,useTokenTransformer:t,lineDiffType:n,maxLineDiffLength:r,tokenizeMaxLineLength:i};if(this.isInitialized()||await this.initialize(),!s()||S9(a,this.renderOptions))return;let o=V7(e),c=[];if(Z2(a.theme,this.renderOptions.theme)||(c=H7(o)?R9(o):await z9(o)),!s())return;if(this.highlighter!=null)M7(c,this.highlighter);else{let e=await B7({themes:o,langs:[`text`],preferredHighlighter:this.preferredHighlighter});if(!s())return;this.highlighter=e}let l=this.setRenderOptionsOnWorkers(a,c);this.renderOptions=a,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(let e of this.themeSubscribers)e.onThemeChange();await l}catch(e){if(e instanceof K9||!s())return;throw e}}getPreferredHighlighter(){return this.preferredHighlighter}getFileRenderOptions(){let{tokenizeMaxLineLength:e,theme:t,useTokenTransformer:n}=this.renderOptions;return{theme:t,useTokenTransformer:n,tokenizeMaxLineLength:e}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(e,t){if(this.workersFailed)return;this.isInitialized()||await this.initialize();let n=[];for(let r of this.workers){if(!r.initialized)throw console.log({managedWorker:r}),Error(`setRenderOptionsOnWorkers: Somehow we have an uninitialized worker`);n.push(new Promise((n,i)=>{let a=this.generateRequestId(),o={type:`set-render-options`,id:a,request:{type:`set-render-options`,id:a,renderOptions:e,resolvedThemes:t},resolve:n,reject:i,requestStart:Date.now()};this.activeTaskById.set(a,o),r.pendingSetupRequestId=a,r.worker.postMessage(o.request)}))}await Promise.all(n)}subscribeToThemeChanges(e){return this.themeSubscribers.add(e),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(e),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(e){this.themeSubscribers.delete(e),this.queueBroadcastStateChanges()}subscribeToStatChanges(e){return this.statSubscribers.add(e),e(this.getStats()),()=>{this.statSubscribers.delete(e)}}queueBroadcastStateChanges(){this._queuedBroadcast??=requestAnimationFrame(this._broadcastStateChanges)}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);let e=this.getStats();for(let t of this.statSubscribers)t(e)};cleanUpTasks(e){this.detachInstanceFromQueuedTasks(e);let t=this.activeRequestByInstance.get(e);if(t!=null){let n=this.activeTaskById.get(t);J9(n)?(this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeActiveTask(n)):this.activeTaskById.delete(t)}this.activeRequestByInstance.delete(e),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(e=[]){if(this.initialized!==!0)if(this.initialized===!1){let{lifecycleGeneration:t}=this;this.initialized=new Promise((n,r)=>{(async()=>{try{let r=V7(this.renderOptions.theme),i=[];if(i=H7(r)?R9(r):await z9(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=I9(e)?F9(e):await L9(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([B7({themes:r,langs:[`text`,...e],preferredHighlighter:this.preferredHighlighter}),this.initializeWorkers(i,a)]);if(!this.isCurrentLifecycle(t)){this.terminateWorkers(),n();return}this.highlighter=o,this.initialized=!0,this.diffCache.clear(),this.fileCache.clear(),this.drainQueue(),this.queueBroadcastStateChanges(),n()}catch(e){if(e instanceof K9||!this.isCurrentLifecycle(t)){n();return}this.initialized=!1,this.workersFailed=!0;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,X9(e));this.queueBroadcastStateChanges(),r(e)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;let n=[],r=q7(),i=r>0?J7():void 0;this.workers.length>0&&this.terminateWorkers();for(let a=0;a<(this.options.poolSize??8);a++){let a=this.options.workerFactory(),o={worker:a,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set([`text`,...t.map(({name:e})=>e)]),customExtensionsVersion:0};a.addEventListener(`message`,e=>{this.handleWorkerMessage(o,e.data)}),a.addEventListener(`error`,e=>console.error(`Worker error:`,e,o)),this.workers.push(o),n.push(new Promise((n,a)=>{let s=this.generateRequestId(),c={type:`initialize`,id:s,request:{type:`initialize`,id:s,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes:e,resolvedLanguages:t,customExtensionsVersion:i==null?void 0:r,customExtensionMap:i},resolve(){o.initialized=!0,n()},reject:a,requestStart:Date.now()};this.activeTaskById.set(s,c),this.executeTask(o,c)}))}await Promise.all(n)}drainQueue=()=>{if(this._queuedDrain=void 0,this.initialized===!0&&this.queuedTasks.length!==0){for(let e=0;e<this.queuedTasks.length;){let t=this.queuedTasks[e];if(this.hasActiveRequest(t)){e++;continue}let n=gct(t),r=this.getAvailableWorker(n);if(r==null)break;this.queuedTasks.splice(e,1),this.assignWorkerToTask(t,r),this.resolveLanguagesAndExecuteTask(r,t,n)}this.queueBroadcastStateChanges()}};highlightFileAST(e,t){let n=this.getFileResultCache(t);h9(t)||n!=null&&U7(n.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(e,t)||this.submitTask(e,{type:`file`,file:t})}primeFileHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeFileHighlightCache: worker pool is not working`));let t=this.getOrCreateFileHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateFileHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${e.name}".`);return}let t=this.getFileResultCache(e),n=this.getFileHighlightKey(e);if(n==null||h9(e)||t!=null&&U7(t.options,this.getFileRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`file`?r:void 0;{let t=this.submitCacheTask({type:`file`,file:e},n);return t.type===`file`?t:void 0}}getPlainFileAST(e,t,n,r){if(this.highlighter==null){this.queueInitialization();return}return m9(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);P9(t)||n!=null&&S9(n.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(e,t)||this.submitTask(e,{type:`diff`,diff:t})}primeDiffHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeDiffHighlightCache: worker pool is not working`));let t=this.getOrCreateDiffHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateDiffHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${e.prevName??e.name}" -> "${e.name}".`);return}let t=this.getDiffResultCache(e),n=this.getDiffHighlightKey(e);if(n==null||P9(e)||t!=null&&S9(t.options,this.getDiffRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`diff`?r:void 0;{let t=this.submitCacheTask({type:`diff`,diff:e},n);return t.type===`diff`?t:void 0}}getPlainDiffAST(e,t,n,r,i){return this.highlighter==null?void 0:N9(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,expandedHunks:r,collapsedContextThreshold:i})}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers();let e=new K9;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,e);this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.highlighter=void 0,this.initialized=!1,this.workersFailed=!1,this.queueBroadcastStateChanges()}isCurrentLifecycle(e){return this.lifecycleGeneration===e}queueInitialization(e){this.initialize(e).catch(e=>{console.error(e)})}cancelActiveWorkerTasks(){let e=new K9;for(let t of this.activeTaskById.values())`reject`in t?t.reject(e):J9(t)&&this.rejectRenderTaskCallbacks(t,e)}terminateWorkers(){for(let e of this.workers)e.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?`waiting`:this.initialized===!0?`initialized`:`initializing`,totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(e=>e.requestId!=null||e.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.getHighlightKeyForRequest(t),r=n==null?void 0:this.getTaskByHighlightKey(n);if(r!=null){this.detachInstanceFromQueuedTasks(e,r),this.addInstanceToTask(r,e),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(e);let i=this.generateRequestId(),a=Date.now(),{renderOptionsVersion:o}=this,s=(()=>{switch(t.type){case`file`:return{type:`file`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a};case`diff`:return{type:`diff`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a}}})();this.enqueueRenderTask(s,e)}submitCacheTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.generateRequestId(),r=Date.now(),{renderOptionsVersion:i}=this,a=(()=>{switch(e.type){case`file`:return{type:`file`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r};case`diff`:return{type:`diff`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r}}})();return this.enqueueRenderTask(a),a}enqueueRenderTask(e,t){this.queuedTasks.push(e),t!=null&&this.queuedTaskByInstance.set(t,e),e.highlightKey!=null&&this.taskByHighlightKey.set(e.highlightKey,e),this.queueDrain()}async resolveLanguagesAndExecuteTask(e,t,n){try{let r=n.filter(t=>!e.langs.has(t));if(r.length>0&&(I9(r)?t.request.resolvedLanguages=F9(r):t.request.resolvedLanguages=await L9(r)),!this.activeTaskById.has(t.id)){e.requestId===t.id&&(this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(e,t)}catch(n){this.rejectRenderTaskCallbacks(t,X9(n)),this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(e,t){let n=this.activeTaskById.get(t.id);try{if(n==null)throw G9;if(t.type===`error`){let e=Error(t.error);if(t.stack&&(e.stack=t.stack),`reject`in n)n.reject(e);else if(J9(n))this.notifyHighlightError(n,e),this.rejectRenderTaskCallbacks(n,e);else throw Error(`handleWorkerMessage: unknown task type`);throw e}switch(t.requestType){case`initialize`:if(n.type!==`initialize`)throw Error(`handleWorkerMessage: task/response dont match`);this.syncCustomExtensionVersion(e,n.request),n.resolve();break;case`set-render-options`:if(n.type!==`set-render-options`)throw Error(`handleWorkerMessage: task/response dont match`);n.resolve();break;case`file`:{if(n.type!==`file`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!U7(i,this.getFileRenderOptions()))throw G9;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.fileCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyFileInstances(n,r,i);break}case`diff`:{if(n.type!==`diff`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!S9(i,this.getDiffRenderOptions()))throw G9;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.diffCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyDiffInstances(n,r,i);break}}}catch(e){e!==G9&&console.error(e,n,t)}this.cleanWorkerAndTask(e,n,t.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain??(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(e,t){t.requestId=e.id,J9(e)&&(this.clearQueuedInstanceRequests(e),this.trackInstanceRequests(e)),this.activeTaskById.set(e.id,e)}cleanWorkerAndTask(e,t,n=t?.id){e.requestId===n&&(e.requestId=void 0),e.pendingSetupRequestId===n&&(e.pendingSetupRequestId=void 0),t!=null&&(J9(t)&&(this.rejectRenderTaskCallbacks(t,new q9),this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){hct(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(let n of gct(t))e.langs.add(n);try{t.type===`file`?t.cacheKeyAtDispatch=t.request.file.cacheKey:t.type===`diff`&&(t.cacheKeyAtDispatch=t.request.diff.cacheKey),e.worker.postMessage(t.request)}catch(n){console.error(`Failed to post message to worker:`,n),J9(t)?(this.notifyHighlightError(t,n),this.rejectRenderTaskCallbacks(t,X9(n))):`reject`in t&&t.reject(n),this.cleanWorkerAndTask(e,t),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(e,t){if(t.customExtensionsVersion!=null)return;let n=q7();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=J7())}syncCustomExtensionVersion(e,t){t.customExtensionsVersion!=null&&(e.customExtensionsVersion=t.customExtensionsVersion)}getAvailableWorker(e){let t;for(let n of this.workers){if(n.requestId!=null||n.pendingSetupRequestId!=null||!n.initialized)continue;if(t=n,e.length===0)break;let r=!0;for(let t of e)if(!n.langs.has(t)){r=!1;break}if(r)break}return t}getFileHighlightKey(e){if(e.cacheKey!=null)return`file:${e.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(e){if(e.cacheKey!=null)return`diff:${e.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(e){switch(e.type){case`file`:return this.getFileHighlightKey(e.file);case`diff`:return this.getDiffHighlightKey(e.diff)}}hasActiveRequest(e){for(let t of Y9(e))if(this.activeRequestByInstance.has(t))return!0;return!1}addInstanceToTask(e,t){e.type,e.instances.add(t),this.activeTaskById.has(e.id)?this.activeRequestByInstance.set(t,e.id):this.queuedTaskByInstance.set(t,e)}detachInstanceFromQueuedTasks(e,t){let n=this.queuedTaskByInstance.get(e);n!=null&&n!==t&&(this.queuedTaskByInstance.delete(e),this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeQueuedTask(n))}detachInstanceFromRenderTask(e,t){e.type,e.instances.delete(t)}removeQueuedTask(e){let t=this.queuedTasks.indexOf(e);t!==-1&&this.queuedTasks.splice(t,1),this.rejectRenderTaskCallbacks(e,new q9),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.rejectRenderTaskCallbacks(e,new q9),this.clearInstanceRequests(e),this.clearHighlightKey(e),this.activeTaskById.delete(e.id)}createRenderTaskCallbacks(e){return new Promise((t,n)=>{e.callbacks.add({resolve:t,reject:n})})}resolveRenderTaskCallbacks(e){for(let t of e.callbacks)t.resolve();e.callbacks.clear()}rejectRenderTaskCallbacks(e,t){for(let n of e.callbacks)n.reject(t);e.callbacks.clear()}invalidateRenderTasks(){for(let e=this.queuedTasks.length-1;e>=0;e--){let t=this.queuedTasks[e];t.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(t)}for(let e of Array.from(this.activeTaskById.values()))J9(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(let t of Y9(e))this.queuedTaskByInstance.get(t)===e&&this.queuedTaskByInstance.delete(t)}clearHighlightKey(e){e.highlightKey!=null&&this.taskByHighlightKey.get(e.highlightKey)===e&&this.taskByHighlightKey.delete(e.highlightKey)}trackInstanceRequests(e){for(let t of Y9(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(let t of Y9(e))this.activeRequestByInstance.get(t)===e.id&&this.activeRequestByInstance.delete(t)}notifyFileInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.file,t,n)}notifyDiffInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.diff,t,n)}notifyHighlightError(e,t){for(let n of Y9(e))this.activeRequestByInstance.get(n)===e.id&&n.onHighlightError(t)}hasMatchingFileInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`file`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&w4(t,n.request.file))return!0;return!1}hasMatchingDiffInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`diff`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&x9(n.request.diff,t))return!0;return!1}getTaskByHighlightKey(e){let t=this.taskByHighlightKey.get(e);return t!=null&&this.isCurrentRenderTask(t)?t:void 0}isCurrentRenderTask(e){return e.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(let e of this.queuedTasks)yield e;for(let e of this.activeTaskById.values())J9(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function hct(e){return e.type===`initialize`||e.type===`file`||e.type===`diff`}function gct(e){let t=new Set;if(e.type===`initialize`||e.type===`set-render-options`)return[];switch(e.type){case`file`:t.add(e.request.file.lang??K7(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??K7(e.request.diff.name)),t.add(e.request.diff.lang??K7(e.request.diff.prevName??`-`))}return t.delete(`text`),Array.from(t)}function J9(e){return e?.type===`file`||e?.type===`diff`}function Y9(e){return e.instances}function X9(e){return e instanceof Error?e:Error(String(e))}var Z9;function _ct({poolOptions:e,highlighterOptions:t}){return Z9??=new mct(e,t),Z9}function vct(){Z9!=null&&(Z9.terminate(),Z9=void 0)}var Q9=(0,F.createContext)(void 0),$9=0;function yct({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,F.useState)(()=>{if(!(typeof window>`u`))return _ct({poolOptions:t,highlighterOptions:n})});return(0,F.useInsertionEffect)(()=>{if(r!=null)return $9++,()=>{$9--}},[r]),(0,F.useEffect)(()=>()=>{$9===0&&vct()},[]),(0,Mr.jsx)(Q9.Provider,{value:r,children:e})}function bct(){return(0,F.useContext)(Q9)}function xct(e){return Yt(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,Nr&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function Sct(e){let t=(0,ol.c)(10),n=Nr&&e.mode!==`sheet`,r=e.mode===`inline`?`w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border`:`w-full`,i;t[0]===r?i=t[1]:(i=Yt(`flex h-full min-w-0 flex-col bg-background`,r),t[0]=r,t[1]=i);let a;t[2]!==e.header||t[3]!==e.mode||t[4]!==n?(a=n?(0,Mr.jsx)(`div`,{className:xct(e.mode),children:e.header}):(0,Mr.jsx)(`div`,{className:`border-b border-border`,children:(0,Mr.jsx)(`div`,{className:xct(e.mode),children:e.header})}),t[2]=e.header,t[3]=e.mode,t[4]=n,t[5]=a):a=t[5];let o;return t[6]!==e.children||t[7]!==i||t[8]!==a?(o=(0,Mr.jsxs)(`div`,{className:i,children:[a,e.children]}),t[6]=e.children,t[7]=i,t[8]=a,t[9]=o):o=t[9],o}function Cct(){let e=(0,ol.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Mr.jsx)(R1,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,Mr.jsx)(R1,{className:`absolute right-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),e[0]=t,e[1]=n):(t=e[0],n=e[1]);let r;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Mr.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,Mr.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,Mr.jsx)(R1,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,Mr.jsx)(R1,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,Mr.jsx)(R1,{className:`h-6 w-24 shrink-0 rounded-md max-sm:hidden`})]})]}),e[2]=r):r=e[2];let i;return e[3]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Mr.jsxs)(Mr.Fragment,{children:[r,(0,Mr.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,Mr.jsx)(R1,{className:`size-7 rounded-md`}),(0,Mr.jsx)(R1,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function wct(e){let t=(0,ol.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Mr.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,Mr.jsx)(R1,{className:`h-4 w-32 rounded-full`}),(0,Mr.jsx)(R1,{className:`ml-auto h-4 w-20 rounded-full`})]}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Mr.jsxs)(`div`,{className:`space-y-2`,children:[(0,Mr.jsx)(R1,{className:`h-3 w-full rounded-full`}),(0,Mr.jsx)(R1,{className:`h-3 w-full rounded-full`}),(0,Mr.jsx)(R1,{className:`h-3 w-10/12 rounded-full`}),(0,Mr.jsx)(R1,{className:`h-3 w-11/12 rounded-full`}),(0,Mr.jsx)(R1,{className:`h-3 w-9/12 rounded-full`})]}),t[1]=r):r=t[1];let i;t[2]===e.label?i=t[3]:(i=(0,Mr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,Mr.jsx)(`span`,{className:`sr-only`,children:e.label})]}),t[2]=e.label,t[3]=i);let a;return t[4]!==e.label||t[5]!==i?(a=(0,Mr.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,Mr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25`,role:`status`,"aria-live":`polite`,"aria-label":e.label,children:[n,i]})}),t[4]=e.label,t[5]=i,t[6]=a):a=t[6],a}export{dst as $,PY as $a,Di as $c,BQ as $i,e2 as $n,mJ as $o,u8e as $r,sJe as $s,uet as $t,Rst as A,QX as Aa,hl as Ac,E$ as Ai,Nr as Al,L9e as An,FZe as Ao,l5e as Ar,KK as As,t3 as At,Tst as B,NX as Ba,cl as Bc,c3e as Bi,$ne as Bl,f7e as Bn,FJ as Bo,U1 as Br,cYe as Bs,w4 as Bt,O9 as C,Y1e as Ca,Tl as Cc,c6e as Ci,Gr as Cl,G9e as Cn,wQe as Co,u0 as Cr,lq as Cs,ptt as Ct,S9 as D,NZ as Da,yl as Dc,D$ as Di,Zr as Dl,F2 as Dn,tY as Do,e5e as Dr,MYe as Ds,u3 as Dt,Ust as E,jZ as Ea,_l as Ec,s6e as Ei,$r as El,q9e as En,gQe as Eo,Z8e as Er,jYe as Es,d3 as Et,jst as F,UX as Fa,Wce as Fc,_$ as Fi,Dr as Fl,j9e as Fn,HJ as Fo,_0 as Fr,HK as Fs,Pet as Ft,yst as G,W$e as Ga,Lo as Gc,o$ as Gi,Wne as Gl,b7e as Gn,pZe as Go,S8e as Gr,wK as Gs,yet as Gt,Cst as H,K$e as Ha,Vo as Hc,l$ as Hi,Sr as Hl,j7e as Hn,SJ as Ho,A8e as Hr,aYe as Hs,n4 as Ht,Ast as I,BX as Ia,ul as Ic,v$ as Ii,Er as Il,b2 as In,BJ as Io,c5e as Ir,FK as Is,Net as It,hst as J,p$e as Ja,kre as Jc,Q4e as Ji,Vne as Jl,g7e as Jn,vJ as Jo,v8e as Jr,oK as Js,Z2 as Jt,vst as K,jX as Ka,Ro as Kc,i$ as Ki,gr as Kl,h7e as Kn,iZe as Ko,R1 as Kr,ZJe as Ks,$2 as Kt,kst as L,RX as La,dl as Lc,S3e as Li,Tr as Ll,y2 as Ln,kJ as Lo,L8e as Lr,CK as Ls,E4 as Lt,Ist as M,eZ as Ma,pl as Mc,G3e as Mi,jr as Ml,P9e as Mn,RZe as Mo,o5e as Mr,ZK as Ms,M4 as Mt,Nst as N,ZX as Na,Gce as Nc,S$ as Ni,Ar as Nl,F9e as Nn,KJ as No,s5e as Nr,DYe as Ns,k4 as Nt,x9 as O,tZ as Oa,vl as Oc,e6e as Oi,Fr as Ol,J9e as On,nY as Oo,a5e as Or,eq as Os,r3 as Ot,Mst as P,KX as Pa,Kce as Pc,q3e as Pi,Or as Pl,O9e as Pn,GJ as Po,r5e as Pr,JK as Ps,Fet as Pt,lst as Q,FY as Qa,Oi as Qc,z4e as Qi,C7e as Qn,_Ze as Qo,g8e as Qr,LJe as Qs,ret as Qt,Ost as R,FX as Ra,fl as Rc,f$ as Ri,wr as Rl,x2 as Rn,PJ as Ro,R8e as Rr,sYe as Rs,D4 as Rt,D9 as S,J1e as Sa,Sle as Sc,j$ as Si,Wr as Sl,K9e as Sn,NQe as So,b0 as Sr,nq as Ss,p3 as St,Hst as T,X1e as Ta,Cl as Tc,d6e as Ti,Kr as Tl,X9e as Tn,DQe as To,c0 as Tr,zYe as Ts,ftt as Tt,v9 as U,C$e as Ua,No as Uc,s$ as Ui,Qne as Ul,y7e as Un,wJ as Uo,V1 as Ur,tYe as Us,t4 as Ut,wst as V,nX as Va,ll as Vc,s3e as Vi,Zne as Vl,A7e as Vn,OJ as Vo,j8e as Vr,rYe as Vs,Aet as Vt,bst as W,S$e as Wa,Po as Wc,n$ as Wi,Hne as Wl,u9e as Wn,uZe as Wo,O8e as Wr,uYe as Ws,e4 as Wt,mst as X,GY as Xa,ki as Xc,Y4e as Xi,_r as Xl,l9e as Xn,rZe as Xo,y8e as Xr,AJe as Xs,J2 as Xt,h9 as Y,s$e as Ya,Ai as Yc,X4e as Yi,Kne as Yl,v7e as Yn,gZe as Yo,_8e as Yr,kJe as Ys,X2 as Yt,pst as Z,WY as Za,Ei as Zc,H4e as Zi,t9e as Zn,vZe as Zo,b8e as Zr,PJe as Zs,q2 as Zt,j9 as _,x0e as _a,$W as _c,M$ as _i,Hr as _l,z2 as _n,gY as _o,P0 as _r,iq as _s,fnt as _t,yct as a,K2e as aa,FJe as ac,P1 as ai,Tre as al,het as an,kY as ao,c9e as ar,$q as as,Wot as at,qst as b,e0e as ba,ble as bc,A$ as bi,cre as bl,iet as bn,_Y as bo,_5e as br,aq as bs,Xtt as bt,fct as c,Y2e as ca,BG as cc,d8e as ci,Sre as cl,H2 as cn,SY as co,k7e as cr,rJ as cs,Rot as ct,cct as d,y2e as da,Eqe as dc,h8e as di,si as dl,Z9e as dn,EY as do,s7e as dr,PXe as ds,U7 as dt,UQ as ea,zJe as ec,f8e as ei,Ci as el,cet as en,IY as eo,x7e as er,pJ as es,ust as et,sct as f,S2e as fa,Dqe as fc,M1 as fi,oi as fl,L2 as fn,TY as fo,o7e as fr,kXe as fs,H7 as ft,N9 as g,y0e as ga,oqe as gc,f6e as gi,Ur as gl,$9e as gn,mY as go,W5e as gr,cq as gs,B7 as gt,P9 as h,tQ as ha,sG as hc,N$ as hi,sre as hl,net as hn,pY as ho,Y5e as hr,BYe as hs,Mot as ht,Q9 as i,FQ as ia,uK as ic,s8e as ii,xi as il,pet as in,HQe as io,e9e as ir,NXe as is,Got as it,Bst as j,D1e as ja,ml as jc,w$ as ji,rre as jl,N9e as jn,LZe as jo,i5e as jr,GK as js,$4 as jt,Lst as k,C1e as ka,xl as kc,$3e as ki,Pr as kl,M9e as kn,NZe as ko,n5e as kr,YK as ks,e3 as kt,pct as l,EQ as la,Kqe as lc,i8e as li,bre as ll,det as ln,xY as lo,X0 as lr,jXe as ls,Iot as lt,ict as m,q0e as ma,lG as mc,P$ as mi,ni as ml,tet as mn,lY as mo,H0 as mr,oJ as ms,V7 as mt,wct as n,LQ as na,$G as nc,p8e as ni,wi as nl,V2 as nn,VQe as no,a2 as nr,MXe as ns,m9 as nt,bct as o,t4e as oa,WG as oc,N1 as oi,yi as ol,get as on,OY as oo,Z0 as or,aJ as os,K7 as ot,U9 as p,p2e as pa,wqe as pc,L$ as pi,ri as pl,_et as pn,wY as po,a7e as pr,OXe as ps,Pot as pt,gst as q,U$e as qa,Mo as qc,r$ as qi,Xne as ql,s9e as qn,yJ as qo,x8e as qr,bK as qs,vet as qt,Sct as r,IQ as ra,EJe as rc,m8e as ri,Si as rl,fet as rn,jY as ro,S7e as rr,Qq as rs,p9 as rt,dct as s,q2e as sa,VG as sc,c8e as si,pi as sl,met as sn,DY as so,s2 as sr,AXe as ss,Vot as st,Cct as t,D4e as ta,RJe as tc,a8e as ti,Ti as tl,Q9e as tn,GQe as to,m7e as tr,hJ as ts,fst as tt,uct as u,DQ as ua,Tqe as uc,B6e as ui,xre as ul,W2 as un,BQe as uo,Y0 as ur,iJ as us,Fot as ut,E9 as v,_0e as va,XW as vc,p6e as vi,fre as vl,B2 as vn,LQe as vo,F0 as vr,tq as vs,ant as vt,Jst as w,Z1e as wa,Sl as wc,k$ as wi,Br as wl,Y9e as wn,xQe as wo,d0 as wr,sq as ws,f3 as wt,Wst as x,PZ as xa,yle as xc,l6e as xi,Lr as xl,eet as xn,aY as xo,m5e as xr,oq as xs,T3 as xt,T9 as y,BZ as ya,ZW as yc,O$ as yi,lre as yl,R2 as yn,hY as yo,y0 as yr,rq as ys,Ytt as yt,Dst as z,PX as za,Uce as zc,f3e as zi,Yne as zl,C2 as zn,SZe as zo,M8e as zr,pYe as zs,T4 as zt};
2534
- //# sourceMappingURL=DiffPanelShell-BNlM5rgR.js.map
2534
+ //# sourceMappingURL=DiffPanelShell-BhFrbxca.js.map