@cmmd-center/forge 0.13.33 → 0.13.35

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 it,fi as at,fr as zee,ft as ot,gi as st,gn as ct,gt as lt,hn as ut,hr as dt,ht as ft,in as pt,it as Bee,j as mt,ja as Vee,jn as ht,jr as Hee,jt as gt,ki as _t,kr as Uee,kt as vt,li as yt,ln as Wee,m as Gee,mn as bt,mr as xt,mt as St,na as Kee,ni as qee,nr as Ct,nt as wt,oa as Jee,on as Yee,or as Tt,pi as Xee,pn as Et,pt as Dt,q as Ot,qn as kt,qt as Zee,r as Qee,ri as $ee,rn as At,rr as ete,rt as tte,s as nte,si as rte,sn as ite,st as jt,ui as ate,un as Mt,ut as Nt,vn as Pt,vr as ote,vt as ste,w as Ft,wn as cte,wr as lte,wt as It,x as ute,xi as dte,xn as Lt,y as fte,yi as pte,yn as Rt,yt as mte,z as zt,zn as Bt,zt as hte}from"./Stream-mUTFnSY9.js";import{i as gte,l as Vt,n as Ht,o as Ut,s as Wt}from"./atomRegistry-C1yW8tyM.js";import{En as _te,Fn as Gt,J as Kt,On as vte,Rn as yte,Tn as qt,an as Jt,cn as bte,dn as Yt,fn as Xt,gn as xte,hn as Zt,i as Ste,ln as Cte,on as wte,sn as Qt,un as Tte}from"./CompositeItem-BuglG3oi.js";import{$n as $t,$t as Ete,A as en,An as Dte,At as tn,Bn as Ote,Bt as kte,C as Ate,Ct as jte,D as nn,Dn as rn,Dt as an,En as on,Et as sn,Fn as cn,Ft as Mte,Gn as Nte,Gt as ln,H as un,Hn as Pte,Ht as dn,In as fn,It as pn,Jn as Fte,Jt as Ite,Kt as mn,L as Lte,Ln as hn,Lt as Rte,Mn as zte,Mt as gn,Nt as Bte,O as _n,On as vn,Pn as yn,Pt as Vte,Qt as Hte,Rn as Ute,Rt as Wte,St as bn,Tn as xn,Tt as Sn,U as Gte,Un as Kte,Ut as Cn,V as wn,Vn as qte,Vt as Tn,W as Jte,Wn as Yte,Wt as En,Xt as Dn,Y as Xte,Yt as Zte,Z as Qte,Zt as $te,_n as j,_t as On,a as ene,an as kn,b as An,bn as jn,c as Mn,cn as Nn,d as tne,dt as Pn,en as nne,et as rne,f as ine,fn as Fn,g as ane,gn as In,gt as one,hn as Ln,ht as Rn,i as sne,in as cne,j as zn,jn as Bn,jt as Vn,k as lne,kn as une,kt as Hn,l as Un,ln as Wn,lt as Gn,m as dne,mn as Kn,nn as fne,nt as qn,o as pne,on as Jn,p as mne,pn as hne,pt as gne,q as _ne,qt as Yn,rn as vne,s as M,sn as Xn,tn as Zn,tt as Qn,u as $n,ut as er,v as tr,vn as nr,w as yne,wn as rr,x as bne,xn as ir,yn as xne,yt as Sne,z as Cne,zt as ar}from"./src-DVtrA7UW.js";import{A as or,C as wne,D as sr,F as Tne,I as Ene,L as cr,M as lr,N as Dne,O as ur,S as One,T as dr,a as fr,b as kne,c as Ane,d as jne,j as pr,k as mr,l as Mne,n as hr,s as Nne,u as Pne,v as Fne,x as Ine,y as Lne}from"./cmmdAuthRedirect-BUli2MC4.js";import{t as N}from"./preload-helper-Czpn1I53.js";import{n as P,t as gr}from"./transport-CgH8pQK3.js";import{n as Rne,t as zne}from"./workspaceReadinessAtom-D6bgTvKb.js";function Bne(e){return e[e.length-1]}function Vne(e,t){return typeof e==`function`?e(t):e}var _r=Object.prototype.hasOwnProperty,Hne=Object.prototype.propertyIsEnumerable;function Une(e){for(let t in e)if(_r.call(e,t))return!0;return!1}var Wne=()=>Object.create(null),Gne=(e,t)=>vr(e,t,Wne);function vr(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Sr(e)&&Sr(i);if(!a&&!(br(e)&&br(i)))return i;let o=a?e:yr(e);if(!o)return i;let s=a?i:yr(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:_r.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=vr(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function yr(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(!Hne.call(e,r))return!1;t.push(r)}return t}function br(e){if(!xr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!xr(n)||!n.hasOwnProperty(`isPrototypeOf`))}function xr(e){return Object.prototype.toString.call(e)===`[object Object]`}function Sr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Cr(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(!Cr(e[r],t[r],n))return!1;return!0}if(br(e)&&br(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Cr(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||!Cr(e[o],t[o],n)))return!1;return i===a}return!1}var Kne=/[\x00-\x1f\x7f"<>`{}]/g;function qne(e){return e.replace(Kne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function wr(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 qne(t)}var Jne=[`http:`,`https:`,`mailto:`,`tel:`];function Yne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Xne(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+=wr(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=wr(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Zne(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Qne(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 Tr(){throw Error(`Invariant failed`)}var F=t(hee(),1),Er=F.createContext(null);function Dr(e){return F.useContext(Er)}var Or=F.createContext(void 0),$ne=F.createContext(void 0),ere=yte();function tre(e,t){return e===t}function kr(e,t,n=tre){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,ere.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Ar={};function jr(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=vr(n.current,i):i}}function Mr(e){let t=Dr(),n=F.useContext(e.from?$ne:Or),r=e.from??n,i=t.stores.getMatchStore(r),a=jr(e,t),o=kr(i,e=>e?a(e):Ar);if(o!==Ar)return o;(e.shouldThrow??!0)&&Tr()}function nre(e){return Mr({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 Nr=fee(),Pr=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Fr=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(){}},Ir=new class extends Fr{#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`}},rre={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Lr=new class{#e=rre;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 ire(e){setTimeout(e,0)}var are=typeof window>`u`||`Deno`in globalThis;function Rr(){}function ore(e,t){return typeof e==`function`?e(t):e}function zr(e){return typeof e==`number`&&e>=0&&e!==1/0}function Br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Vr(e,t){return typeof e==`function`?e(t):e}function Hr(e,t){return typeof e==`function`?e(t):e}function sre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Ur(o,t.options))return!1}else if(!Gr(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 cre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Wr(t.options.mutationKey)!==Wr(a))return!1}else if(!Gr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ur(e,t){return(t?.queryKeyHashFn||Wr)(e)}function Wr(e){return JSON.stringify(e,(e,t)=>Yr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Gr(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(!Gr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Gr(e[r],t[r]))return!1;return!0}return!1}var lre=Object.prototype.hasOwnProperty;function Kr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Jr(e)&&Jr(t);if(!r&&!(Yr(e)&&Yr(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:lre.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Kr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function qr(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 Jr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Yr(e){if(!Xr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Xr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Xr(e){return Object.prototype.toString.call(e)===`[object Object]`}function ure(e){return new Promise(t=>{Lr.setTimeout(t,e)})}function Zr(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Kr(e,t)}function dre(e){return e}function fre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function pre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Qr=Symbol();function $r(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Qr?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ei(e,t){return typeof e==`function`?e(...t):!!e}function mre(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 ti=(()=>{let e=()=>are;return{isServer(){return e()},setIsServer(t){e=t}}})();function ni(){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 hre=ire;function gre(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=hre,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 ri=gre(),ii=new class extends Fr{#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 _re(e){return Math.min(1e3*2**e,3e4)}function ai(e){return(e??`online`)!==`online`||ii.isOnline()}var oi=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function si(e){let t=!1,n=0,r,i=ni(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new oi(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Ir.isFocused()&&(e.networkMode===`always`||ii.isOnline())&&e.canRun(),u=()=>ai(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??(ti.isServer()?0:3),o=e.retryDelay??_re,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),ure(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 ci=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),zr(this.gcTime)&&(this.#e=Lr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ti.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Lr.clearTimeout(this.#e),this.#e=void 0)}};function vre(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=>{mre(e,()=>t.signal,()=>n=!0)},u=$r(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?pre:fre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?ui:li,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:li(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 li(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 ui(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function yre(e,t){return t?li(e,t)!=null:!1}function bre(e,t){return!t||!e.getPreviousPageParam?!1:ui(e,t)!=null}var xre=class extends ci{#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=pi(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=pi(this.options);e.data!==void 0&&(this.setState(fi(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Zr(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(Rr).catch(Rr):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=>Hr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qr||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Vr(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:!Br(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=$r(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`?vre(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=si({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof oi&&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 oi){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,...di(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...fi(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),ri.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function di(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ai(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function fi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function pi(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 mi=class extends Fr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ni(),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),hi(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return gi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return gi(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 Hr(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&&!qr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&_i(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Hr(this.options.enabled,this.#t)!==Hr(t.enabled,this.#t)||Vr(this.options.staleTime,this.#t)!==Vr(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Hr(this.options.enabled,this.#t)!==Hr(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 Cre(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(Rr)),t}#g(){this.#b();let e=Vr(this.options.staleTime,this.#t);if(ti.isServer()||this.#r.isStale||!zr(e))return;let t=Br(this.#r.dataUpdatedAt,e)+1;this.#d=Lr.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,!(ti.isServer()||Hr(this.options.enabled,this.#t)===!1||!zr(this.#p)||this.#p===0)&&(this.#f=Lr.setInterval(()=>{(this.options.refetchIntervalInBackground||Ir.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Lr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Lr.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&&hi(e,t),o=i&&_i(e,n,t,r);(a||o)&&(l={...l,...di(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=Zr(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=Zr(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:vi(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Hr(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=ni();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),!qr(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){ri.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Sre(e,t){return Hr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Hr(t.retryOnMount,e)!==!1)}function hi(e,t){return Sre(e,t)||e.state.data!==void 0&&gi(e,t,t.refetchOnMount)}function gi(e,t,n){if(Hr(t.enabled,e)!==!1&&Vr(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&vi(e,t)}return!1}function _i(e,t,n,r){return(e!==t||Hr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&vi(e,n)}function vi(e,t){return Hr(t.enabled,e)!==!1&&e.isStaleByTime(Vr(t.staleTime,e))}function Cre(e,t){return!qr(e.getCurrentResult(),t)}var yi=F.createContext(void 0),bi=e=>{let t=F.useContext(yi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},wre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Nr.jsx)(yi.Provider,{value:e,children:t})),xi=F.createContext(!1),Si=()=>F.useContext(xi);xi.Provider;function Tre(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ere=F.createContext(Tre()),Ci=()=>F.useContext(Ere),wi=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ei(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ti=e=>{F.useEffect(()=>{e.clearReset()},[e])},Ei=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ei(n,[e.error,r])),Di=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))}},Dre=(e,t)=>e.isLoading&&e.isFetching&&!t,Oi=(e,t)=>e?.suspense&&t.isPending,ki=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ai(e,t,n){let r=Si(),i=Ci(),a=bi(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,Di(o),wi(o,i,s),Ti(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(ri.batchCalls(e)):Rr;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Oi(o,d))throw ki(o,u,i);if(Ei({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&&!ti.isServer()&&Dre(d,r)&&(l?ki(o,u,i):s?.promise)?.catch(Rr).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function ji(e,t){return Ai(e,mi,t)}function Ore(e){return e}var kre={[Symbol.iterator](){return Are}},Are={next(){return{done:!0,value:void 0}}},jre=()=>kre,Mre=x,Mi=globalThis.Number,Nre=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=Mi(e);return Mi.isNaN(t)?Ee():T(t)},Pre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Ni=`~effect/http/HttpClientRequest`,Fre={[Ni]:Ni,...ke,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Jee(this.headers),body:this.body.toJSON()}},pipe(){return Ve(this,arguments)}};function Pi(e,t,n,r,i,a){let o=Object.create(Fre);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Ire=Pi(`GET`,``,$te,Ee(),Tn,Zte),Fi=e=>(t,n)=>Rre(Ire,{method:e,url:t,...n??void 0}),Lre=Fi(`POST`),Rre=w(2,(e,t)=>{let n=e;return t.method&&(n=zre(n,t.method)),t.url&&(n=Hre(n,t.url)),t.headers&&(n=Ii(n,t.headers)),t.urlParams&&(n=Ure(n,t.urlParams)),t.hash&&(n=Wre(n,t.hash)),t.body&&(n=Ri(n,t.body)),t.accept&&(n=Li(n,t.accept)),t.acceptJson&&(n=Vre(n)),n}),zre=w(2,(e,t)=>Pi(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Bre=w(3,(e,t,n)=>Pi(e.method,e.url,e.urlParams,e.hash,Yn(e.headers,t,n),e.body)),Ii=w(2,(e,t)=>Pi(e.method,e.url,e.urlParams,e.hash,Ite(e.headers,t),e.body)),Li=w(2,(e,t)=>Bre(e,`Accept`,t)),Vre=Li(`application/json`),Hre=w(2,(e,t)=>{if(typeof t==`string`)return Pi(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Hte(n.searchParams),i=dte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Pi(e.method,n.toString(),r,i,e.headers,e.body)}),Ure=w(2,(e,t)=>Pi(e.method,e.url,nne(e.urlParams,t),e.hash,e.headers,e.body)),Wre=w(2,(e,t)=>Pi(e.method,e.url,e.urlParams,T(t),e.headers,e.body)),Ri=w(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=mn(mn(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Yn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Yn(n,`content-length`,t.contentLength.toString()))),Pi(e.method,e.url,e.urlParams,e.hash,n,t)}),Gre=e=>Cn({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`}`}),zi=`~effect/http/HttpClient`,Bi=yt(`effect/HttpClient`),Vi=w(2,(e,t)=>Hi(n=>t(e.postprocess(n)),e.preprocess)),Kre=Vi(wt(Rte)),Hi=(e,t)=>{let n=Object.create(qre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},qre={[zi]:zi,pipe(){return Ve(this,arguments)},...ke,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Pre.map(([e,t])=>[t,function(t,n){return this.execute(Fi(e)(t,n))}]))},Jre=e=>Hi(t=>wt(t,t=>Pt(n=>{let i=Qre.get(t),a=i??new AbortController,o=Ete(t.url,t.urlParams,y(t.hash));if(qee(o))return r(new Zn({reason:new vne({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Uee)||n.getRef(Ui)(t)){let r=e(t,s,a.signal,n);return i?r:Et(e=>Le(e(r),{onSuccess(e){return Gi.register(e,a),rt(new Ki(e,a))},onFailure(e){return xt(e)&&a.abort(),it(e)}}))}return ut(n.getRef(Xre)(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(kte),l=ln(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Wi)?Ii(t,Gre(r)):t,Et(o=>o(e(t,s,a.signal,n)).pipe(Rt(r,{captureStackTrace:!1}),Le({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=ln(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?rt(e):(Gi.register(e,a),rt(new Ki(e,a)))},onFailure(e){return!i&&xt(e)&&a.abort(),it(e)}})))})})),rt),Yre=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 Vi(e,ie(r===`errors-only`?me:oe({schedule:o,times:s,while:Ji}),r===`response-only`?me:_e({while:n||t.while===void 0?qi:a(qi,t.while),schedule:i,times:s})))}),Ui=$e(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Vee}),Wi=$e(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:ye}),Xre=$e(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Zre=e=>ht(Bi)(se(t=>Ze(e,e=>Vi(e,bt(e=>st(t,e)))))),Gi=(()=>{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))}}})(),Qre=new WeakMap,Ki=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[pn]=pn;[ar]=ar;applyInterrupt(e){return At(()=>(Gi.unregister(this.original),vt(e,()=>pt(()=>{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(()=>(Gi.unregister(this.original),Qee(this.original.stream,pt(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[nt](){return this.original[nt]()}pipe(){return Ve(this,arguments)}},qi=e=>Mee(e)||$re(e),$re=e=>kn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Ji(e.reason.response)),Ji=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Yi=`~effect/FiberSet`,eie=e=>Ye(e,Yi),tie={[Yi]:Yi,[Symbol.iterator](){return this.state._tag===`Closed`?jre():this.state.backing[Symbol.iterator]()},...Ke,toJSON(){return{_id:`FiberMap`,state:this.state}}},nie=(e,t)=>{let n=Object.create(tie);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},rie=()=>je(pt(()=>nie(new Set,qe())),e=>At(()=>{let t=e.state;if(t._tag===`Closed`)return ct;e.state={_tag:`Closed`};let n=t.backing;return C(n).pipe(ce(e.deferred))})),Xi=-1,iie=ge(D(Iee,ae(Xi))),aie=w(e=>eie(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Xi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),Ct(r)&&(n?.propagateInterruption===!0?!iie(r.cause):!dt(r.cause))&&kt(e.deferred,r))}))}),oie=function(){let e;return()=>(e===void 0&&(e=f(St)),e)}(),sie=e=>()=>Ze(Ot(),t=>{let n=We(t);return(t,r)=>{if(e.state._tag===`Closed`)return oie();let i=n(t,r);return aie(e,i),i}}),Zi=e=>de(e.deferred),Qi=`~effect/socket/Socket`,$i=yt(`effect/socket/Socket`),cie=`~effect/socket/Socket/CloseEvent`,lie=e=>Ye(e,cie),ea=`~effect/socket/Socket/SocketError`,uie=e=>Ye(e,ea),ta=class extends Wn(`effect/socket/Socket/SocketReadError`)({_tag:fn(`SocketReadError`),cause:Nn}){message=`An error occurred during Read`},die=class extends Wn(`effect/socket/Socket/SocketWriteError`)({_tag:fn(`SocketWriteError`),cause:Nn}){message=`An error occurred during Write`},na=class extends Wn(`effect/socket/Socket/SocketOpenError`)({_tag:fn(`SocketOpenError`),kind:Fn([`Unknown`,`Timeout`]),cause:Nn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},ra=class extends Wn(`effect/socket/Socket/SocketCloseError`)({_tag:fn(`SocketCloseError`),code:Ln,closeReason:yn(j)}){static filterClean(e){return function(t){return aa.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?rte(t.reason):Lee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},ia=ir([ta,die,na,ra]),aa=class extends xne(ea)(`SocketError`,{_tag:fn(`SocketError`),reason:ia}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[ea]=ea;static is(e){return uie(e)}message=this.reason.message},fie=e=>!0,pie=class extends yt()(`~effect/socket/Socket/WebSocket`){},oa=class extends yt()(`@effect/platform/Socket/WebSocketConstructor`){},mie=(e,t)=>oa.use(n=>hie(je((typeof e==`string`?rt(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>pt(()=>e.close(1e3))),t)),hie=(e,t)=>Pt(n=>{let i,a=mt(!1),o=n.context,s=t?.closeCodeIsError??fie,c=(n,c)=>Tee(Xe(function*(o){let l=yield*rie().pipe(te(o)),u=yield*te(e,o),d=yield*Oe(sie(l)(),pie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=wt(gt(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return lt(t)?t:ct});return d(t)}let t=n(e.data);lt(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),kt(l.deferred,r(new aa({reason:f?new ta({cause:e}):new na({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),kt(l.deferred,r(new aa({reason:new ra({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,kt(e,ct)},{once:!0}),yield*de(e).pipe(Mt({duration:t?.openTimeout??1e4,orElse:()=>r(new aa({reason:new na({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),ee(Zi(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ue(Zi(l),ra.filterClean(e=>!s(e)),()=>ct)})).pipe(bt(e=>st(o,e)),Je(pt(()=>{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(pt(()=>{let t=i;lie(e)?t.close(e.code,e.reason):t.send(e)})));return rt($i.of({[Qi]:Qi,run:u,runRaw:c,writer:d}))}),sa=ie(mie,ht($i)),ca=class extends yt()(`effect/workers/Transferable/Collector`){},gie=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ca.of({addAllUnsafe:t,addAll:e=>pt(()=>t(e)),readUnsafe:n,read:pt(n),clearUnsafe:r,clear:pt(r)})},_ie=`~effect/workers/WorkerError`,vie=class extends Wn(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:fn(`WorkerSpawnError`),message:j,cause:yn(Nn)}){},yie=class extends Wn(`effect/workers/WorkerError/WorkerSendError`)({_tag:fn(`WorkerSendError`),message:j,cause:yn(Nn)}){},bie=class extends Wn(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:fn(`WorkerReceiveError`),message:j,cause:yn(Nn)}){},xie=class extends Wn(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:fn(`WorkerUnknownError`),message:j,cause:yn(Nn)}){},la=ir([vie,yie,bie,xie]);Wn(_ie)({_tag:fn(`WorkerError`),reason:la});var ua=`~effect/rpc/RpcClientError`,da=class extends Wn(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:fn(`RpcClientDefect`),message:j,cause:Nn}){},fa=class extends Wn(ua)({_tag:fn(`RpcClientError`),reason:ir([la,ia,fne,da])}){[ua]=ua;get message(){return`${this.reason._tag}: ${this.reason.message}`}},pa=e=>typeof e==`bigint`?e:BigInt(e),Sie={_tag:`Ping`},ma;try{ma=new TextDecoder}catch{}var I,ha,L=0,ga=[],_a=ga,va=0,ya={},ba,xa,Sa=0,Ca=0,wa,Ta,Ea=[],Da,Oa={useRecords:!1,mapsAsObjects:!0},ka=class{},Aa=new ka;Aa.name=`MessagePack 0xC1`;var ja=!1,Ma=2,Na,Pa,Fa;try{Function(``)}catch{Ma=1/0}var Ia=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 ao(()=>(oo(),this?this.unpack(t,n):e.prototype.unpack.call(Oa,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(ha=n.end||t.length,L=n.start||0):(L=0,ha=n>-1?n:t.length),va=0,Ca=0,xa=null,_a=ga,wa=null,I=t;try{Da=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(ya=this,this.structures)return ba=this.structures,La(n);(!ba||ba.length>0)&&(ba=[])}else ya=Oa,(!ba||ba.length>0)&&(ba=[]);return La(n)}unpackMultiple(e,t){let n,r=0;try{ja=!0;let i=e.length,a=this?this.unpack(e,i):co.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(La(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(La());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{ja=!1,oo()}}_mergeStructures(e,t){Pa&&(e=Pa.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 La(e){try{if(!ya.trusted&&!ja){let e=ba.sharedLength||0;e<ba.length&&(ba.length=e)}let t;if(ya.randomAccessStructure&&I[L]<64&&I[L]>=32&&Na?(t=Na(I,L,ha,ya),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=ha):t=za(),wa&&=(L=wa.postBundlePosition,null),ja&&(ba.restoreStructures=null),L==ha)ba&&ba.restoreStructures&&Ra(),ba=null,I=null,Ta&&=null;else if(L>ha)throw Error(`Unexpected end of MessagePack data`);else if(!ja){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 ba&&ba.restoreStructures&&Ra(),oo(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>ha)&&(e.incomplete=!0),e}}function Ra(){for(let e in ba.restoreStructures)ba[e]=ba.restoreStructures[e];ba.restoreStructures=null}function za(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=ba[e&63]||ya.getStructures&&Ha()[e&63];return t?(t.read||=Ba(t,e&63),t.read()):e}}else if(e<144){if(e-=128,ya.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=eo();e===`__proto__`&&(e=`__proto_`),t[e]=za()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(za(),za());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=za();return ya.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Ca>=L)return xa.slice(L-Sa,(L+=t)-Sa);if(Ca==0&&ha<140){let e=t<16?Ya(t):Ja(t);if(e!=null)return e}return Ua(t)}{let t;switch(e){case 192:return null;case 193:return wa?(t=za(),t>0?wa[1].slice(wa.position1,wa.position1+=t):wa[0].slice(wa.position0,wa.position0-=t)):Aa;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return Za(t);case 197:return t=Da.getUint16(L),L+=2,Za(t);case 198:return t=Da.getUint32(L),L+=4,Za(t);case 199:return Qa(I[L++]);case 200:return t=Da.getUint16(L),L+=2,Qa(t);case 201:return t=Da.getUint32(L),L+=4,Qa(t);case 202:if(t=Da.getFloat32(L),ya.useFloat32>2){let e=so[(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=Da.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=Da.getUint16(L),L+=2,t;case 206:return t=Da.getUint32(L),L+=4,t;case 207:return ya.int64AsType===`number`?(t=Da.getUint32(L)*4294967296,t+=Da.getUint32(L+4)):ya.int64AsType===`string`?t=Da.getBigUint64(L).toString():ya.int64AsType===`auto`?(t=Da.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Da.getBigUint64(L),L+=8,t;case 208:return Da.getInt8(L++);case 209:return t=Da.getInt16(L),L+=2,t;case 210:return t=Da.getInt32(L),L+=4,t;case 211:return ya.int64AsType===`number`?(t=Da.getInt32(L)*4294967296,t+=Da.getUint32(L+4)):ya.int64AsType===`string`?t=Da.getBigInt64(L).toString():ya.int64AsType===`auto`?(t=Da.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Da.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return no(I[L++]&63);{let e=Ea[t];if(e)return e.read?(L++,e.read(za())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,no(I[L++]&63,I[L++])):Qa(2);case 214:return Qa(4);case 215:return Qa(8);case 216:return Qa(16);case 217:return t=I[L++],Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):wie(t);case 218:return t=Da.getUint16(L),L+=2,Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):Tie(t);case 219:return t=Da.getUint32(L),L+=4,Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):Eie(t);case 220:return t=Da.getUint16(L),L+=2,Ga(t);case 221:return t=Da.getUint32(L),L+=4,Ga(t);case 222:return t=Da.getUint16(L),L+=2,Ka(t);case 223:return t=Da.getUint32(L),L+=4,Ka(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 Cie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ba(e,t){function n(){if(n.count++>Ma){let n=e.read=Function(`r`,`return function(){return `+(ya.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:Cie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(za);return e.highByte===0&&(e.read=Va(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]=za()}return ya.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Va(t,n):n}var Va=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=ba[r]||Ha()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=Ba(i,e),i.read()};function Ha(){let e=ao(()=>(I=null,ya.getStructures()));return ba=ya._mergeStructures(e,ba)}var Ua=Wa,wie=Wa,Tie=Wa,Eie=Wa;function Wa(e){let t;if(e<16&&(t=Ya(e)))return t;if(e>64&&ma)return ma.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+=qa.apply(String,r),r.length=0)}return r.length>0&&(t+=qa.apply(String,r)),t}function Ga(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=za();return ya.freezeData?Object.freeze(t):t}function Ka(e){if(ya.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=eo();e===`__proto__`&&(e=`__proto_`),t[e]=za()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(za(),za());return t}}var qa=String.fromCharCode;function Ja(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 qa.apply(String,n)}function Ya(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return qa(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return qa(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return qa(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 qa(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return qa(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 qa(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return qa(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 qa(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return qa(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 qa(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return qa(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 qa(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return qa(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 qa(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 qa(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Xa(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=Da.getUint16(L),L+=2;break;case 219:t=Da.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Wa(t)}function Za(e){return ya.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function Qa(e){let t=I[L++];if(Ea[t]){let n;return Ea[t](I.subarray(L,n=L+=e),e=>{L=e;try{return za()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var $a=Array(4096);function eo(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Ca>=L)return xa.slice(L-Sa,(L+=e)-Sa);if(!(Ca==0&&ha<180))return Ua(e)}else return L--,to(za());let t=(e<<5^(e>1?Da.getUint16(L):e>0?I[L]:0))&4095,n=$a[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=Da.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=[],$a[t]=n,n.bytes=e;r<i;)a=Da.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Ya(e):Ja(e);return s==null?n.string=Ua(e):n.string=s}function to(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(ya.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 no=(e,t)=>{let n=za().map(to),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=ba[e];return i&&(i.isShared||ja)&&((ba.restoreStructures||(ba.restoreStructures=[]))[e]=i),ba[e]=n,n.read=Ba(n,r),n.read()};Ea[0]=()=>{},Ea[0].noBuffer=!0,Ea[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 ro={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Ea[101]=()=>{let e=za();if(!ro[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return ro[e[0]](e[1],{cause:e[2]})},Ea[105]=e=>{if(ya.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Da.getUint32(L-4);Ta||=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};Ta.set(t,i);let a=za();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},Ea[112]=e=>{if(ya.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Da.getUint32(L-4),n=Ta.get(t);return n.used=!0,n.target},Ea[115]=()=>new Set(za());var io=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Die=typeof globalThis==`object`?globalThis:window;Ea[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=io[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 Die[r](n)},Ea[120]=()=>{let e=za();return new RegExp(e[0],e[1])};var Oie=[];Ea[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,wa=Oie,wa=[Xa(),Xa()],wa.position0=0,wa.position1=0,wa.postBundlePosition=L,L=n,za()},Ea[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 ao(e){Fa&&Fa();let t=ha,n=L,r=va,i=Sa,a=Ca,o=xa,s=_a,c=Ta,l=wa,u=new Uint8Array(I.slice(0,ha)),d=ba,f=ba.slice(0,ba.length),p=ya,m=ja,h=e();return ha=t,L=n,va=r,Sa=i,Ca=a,xa=o,_a=s,Ta=c,wa=l,I=u,ja=m,ba=d,ba.splice(0,ba.length,...f),ya=p,Da=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function oo(){I=null,Ta=null,ba=null}var so=Array(147);for(let e=0;e<256;e++)so[e]=+(`1e`+Math.floor(45.15-e*.30103));var co=new Ia({useRecords:!1});co.unpack,co.unpackMultiple,co.unpack;var kie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var lo;try{lo=new TextEncoder}catch{}var uo,fo,po=typeof Buffer<`u`,mo=po?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,ho=po?Buffer:Uint8Array,go=po?4294967296:2144337920,R,_o,vo,z=0,yo,bo=null,Aie,jie=21760,Mie=/[\u0080-\uFFFF]/,xo=Symbol(`record-id`),Nie=class extends Ia{constructor(e){super(e),this.offset=0;let t,n,r,i,a=ho.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:lo&&lo.encodeInto?function(e,t){return lo.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 mo(8192),vo=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),yo=R.length-10,yo-z<2048?(R=new mo(R.length),vo=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),yo=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`?(bo=[],bo.size=1/0):bo=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[xo]=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)&&!fo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=bo;if(bo&&To(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&&(vo.setUint32(n.position+t,vo.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&vo.setUint32(n.position+t,vo.getUint32(n.position+t)+a),z+=e.length*6,z>yo&&w(z),o.offset=z;let s=Pie(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=Fie(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][xo]=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,vo.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>yo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(bo&&n>=4&&n<4096){if((bo.size+=n)>jie){let e,n=(bo[0]?bo[0].length*3+bo[1].length:0)+10;z+n>yo&&(R=w(z+n));let r;bo.position?(r=bo,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,To(t,y,0),vo.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),bo=[``,``],bo.previous=r,bo.size=0,bo.position=e}let r=Mie.test(e);bo[+!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>yo&&(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,vo.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,vo.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,vo.setInt16(z,e),z+=2):(R[z++]=210,vo.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,vo.setFloat32(z,e);let n;if(t<4||(n=e*so[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,vo.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,vo.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,vo.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=uo.length;t<n;t++){let n=fo[t];if(e instanceof n){let n=uo[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=vo,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>yo&&w(z),{target:R,targetView:vo,position:z-e}),y)}finally{r&&(R=r,vo=i,z=a,yo=R.length-10)}o&&(o.length+z>yo&&w(o.length+z),z=wo(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,vo.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,vo.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,vo.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),po)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>yo&&w(n.length+z),z=wo(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,vo.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[xo];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[xo];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>go)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(go,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 mo(n);return vo=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,yo=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[xo]=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()[xo]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=yo,c=t;R=_o,z=0,t=0,R||(_o=R=new mo(8192)),yo=R.length-10,T(e,n,i),_o=R;let l=z;if(R=a,z=o,yo=s,t=c,l>1){let e=z+l-1;e>yo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(_o.slice(0,l),n),z=e}else R[r+t]=_o[0]},D=e=>{let i=Aie(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:vo,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)),vo=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};fo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ka],uo=[{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?So(e,16,t):Co(po?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==ho&&this.moreTypes?So(e,io.indexOf(n.name),t):Co(e,t)}},{pack(e,t){this.moreTypes?So(e,17,t):Co(po?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function So(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 Co(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 wo(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 Pie(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 To(e,t,n){if(bo.length>0){vo.setUint32(bo.position+e,z+n-bo.position-e),bo.stringsPosition=z-e;let r=bo;bo=null,t(r[0]),t(r[1])}}function Fie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var Eo=new Nie({useRecords:!1});Eo.pack,Eo.pack;var{NEVER:Iie,ALWAYS:Lie,DECIMAL_ROUND:Rie,DECIMAL_FIT:zie}=kie,Do=class extends yt()(`effect/rpc/RpcSerialization`){},Bie=Do.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)}}}),Oo=he(Do)(Bie),Vie=e=>At(()=>{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]),ct});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return ot(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(At(()=>i(e)),t)}return yield*iee(S,()=>(t.delete(e),r.delete(e),ct))})}}))}),Hie=BigInt(0),Uie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Hie++),o=yield*Ot(),s=at(o,Me),c=new Map,l=!1;yield*Bt(s,Pt(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`?Ft(n.queue):Pe(n.queue,e.cause):n.resume(e)}),f=e=>{let r=Mte(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?dn(s.headers):Tn,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):ut(`${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:ute(Ze(u,nte))}},m=(e,n,r,i,o,s,u)=>Pt(d=>{if(l)return St;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:En(d.getRef(jo),o)});if(u)return p;let m;return vt(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?Rt(r,{captureStackTrace:!1}):me,We(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),zt(aee(m),_(f,Array.from(e),s))))}),h=Xe(function*(e,r,o,s,d,f){if(l)return yield*St;let m=i?void 0:yield*mte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),h=Ce(),g=a(),v=Xee(h.context,Me);yield*u(v,e=>c.has(g)?(c.delete(g),_(g,Ct(e)?Array.from(Oee(e.cause)):[],f)):ct);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:En(h.getRef(jo),s)}).pipe(m?Rt(m,{captureStackTrace:!1}):me,Ge(e=>Pe(y,e)),ft,Nt(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(ct)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?ct:tee(i.queue,e.values).pipe(r?wt(()=>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),ct):e.exit._tag===`Success`?Ft(n.queue):Pe(n.queue,e.exit.cause)):ct}case`Defect`:return d(bee(e.defect));case`ClientEnd`:return ct}},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}}),Wie=0,ko=Xe(function*(e,t){let n=Wie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*Mo,s=new Map,{client:l,write:u}=yield*Uie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?gie():void 0,l=Ce(),u={rpc:r,context:a?ate(l.context,ca,a):l.context,schemas:Gie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Te(u.context),c,wt(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)}):ct;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):ct;case`Eof`:return ct}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=pa(e.requestId),n=s.get(t);return!n||g(n.schemas.decodeChunk)?ct:n.schemas.decodeChunk.value(e.values).pipe(Te(n.context),c,wt(t=>u({_tag:`Chunk`,clientId:0,requestId:pa(e.requestId),values:t})),v(t=>u({_tag:`Exit`,clientId:0,requestId:pa(e.requestId),exit:Ae(t)})))}case`Exit`:{let t=pa(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)})}))):ct}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Yie(e.defect)});case`ClientProtocolError`:{let t=wee(e.error);return jt(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return ct}}).pipe(Ge(ste),ft,tt),l}),Ao=new WeakMap,Gie=e=>{let t=Ao.get(e);if(t!==void 0)return t;let n=Vte(e.successSchema);return t={decodeChunk:be(n,e=>on(hn(hne(e.success)))),encodePayload:une(hn(e.payloadSchema)),decodeExit:on(hn(Bte(e)))},Ao.set(e,t),t},jo=$e(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Tn}),Mo=class extends yt()(`effect/rpc/RpcClient/Protocol`){static make=Vie},No=e=>Mo.make(Xe(function*(t,n){let i=yield*$i,a=yield*Do,o=yield*see(Jie),s=new Map,u=yield*i.writer,d=a.makeUnsafe(),f=yield*qie(u(d.encode(Sie))),p,m=At(()=>(p=void 0,_t(o)?o.value.onConnect:ct)),h=e=>jt(n,n=>t(n,e));return yield*At(()=>(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(),ct;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 fa({reason:new da({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(ee(wt(f.timeout,()=>r(new aa({reason:new na({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(wt(()=>r(new aa({reason:new ra({code:1e3})}))),_t(o)?Je(o.value.onDisconnect):me,Yee(t=>{let n=zee(t),r=$ee(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?ct:(p=new fa({reason:r?n.success.reason:new da({message:`Unknown socket error`,cause:Ie(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),_e(e?.retryPolicy??Kie),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?ct:c(u(n))},supportsAck:!0,supportsTransferables:!1}})),Kie=h(500,1.5).pipe(uee(ree(5e3))),qie=Xe(function*(e){let t=!0,n=0,r=mt();return yield*At(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(xee(`5 seconds`),Dt,et,ft,tt),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Jie=class extends yt()(`effect/rpc/RpcClient/ConnectionHooks`){},Yie=rr(Nn);function Po(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function Xie(e){return e?.target.wsBaseUrl??null}function Zie(e){return e?.target.httpBaseUrl??null}function Qie(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function $ie(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function eae(e){let t=$ie(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function tae(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 nae(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function rae(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Fo(e){let t=e.capabilities,n=t.runtime??eae(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??tae(n),tools:t.tools??nae(n),projects:t.projects??rae(t,n)}}function iae(e){return e?Fo(e).projects.cloudProjects:!1}function aae(e){return e?Fo(e).runtime.workspaceProxy??!1:!1}function Io(e,t){return{environmentId:e,projectId:t}}function Lo(e,t){return{environmentId:e,threadId:t}}var Ro=`scoped:v1:`;function zo(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Ro)?`${Ro}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Bo(e){return zo(e)}function Vo(e){return zo(e)}function oae(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 Ho(e){if(e.startsWith(Ro))return oae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Uo(e){let t=Ho(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Wo(e){let t=Ho(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var sae=1e3,cae=64e3;ko(Mn);function lae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(sae*2**e),cae)}var Go=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Ko(e){return Array.isArray(e)?e.map(Ko):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ko(t)])):e}function uae(e){let t=JSON.stringify(Ko(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var dae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function fae(e){return e._tag===`Ping`?dae:null}function pae(e){if(e.policy===null||e.policy.method!==e.method)throw new Go(`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 Go(`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 mae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new Go(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new Go(`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 Go(`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 Go(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var hae=[{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:qn.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:qn.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:qn.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:qn.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:qn.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:qn.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.getArchivedShellSnapshot,requiredScope:`thread.read`,deliveryClass:`read`},{method:qn.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.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:qn.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`}],gae=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,qn.dispatchCommand]),_ae=hae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?gae.has(e.method)?`frame`:`metadata-only`:`none`}}),vae=mae({registeredMethods:[...Mn.requests.keys()],policies:_ae}),qo={"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`}},yae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function bae(e){if(e.method!==qn.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!yae.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 Go(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Jo(e){let t=vae.get(e.method)??null,n=pae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==qn.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new Go(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in qo))throw new Go(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=qo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new Go(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Yo=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},Xo=class extends Yo{},Zo=class extends Yo{},Qo=class extends Yo{},xae=class extends Yo{},Sae=class extends Yo{},Cae=class extends Yo{},wae=class extends Yo{},Tae=class extends Yo{},Eae=class extends Yo{},Dae=class extends Yo{},$o=class extends Yo{},es=Oae(globalThis,{});function Oae(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 kae(){if(es!==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 $o(e)}}var ts=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await kae())}},ns={Base:0,Psk:1,Auth:2,AuthPsk:3},Aae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},rs={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},is={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},as=new Uint8Array,os=0n,ss=1n,cs=2n,jae=new Uint8Array([75,69,77,0,0]),ls=new Uint8Array([72,80,75,69,45,118,49]);function us(e){return new Uint8Array(ds(e))}function ds(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 Mae=class extends ts{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:rs.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:as}),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(ls,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(ls,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):ds(e);if(n.byteLength!==this.hashSize)throw new Xo(`The salt length must be the same as the hashSize`);let r=ds(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=ds(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=as,c=us(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=ds(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:ds(e),info:ds(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===as)throw Error(`Not initialized. Call init()`)}},Nae=class extends Mae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:rs.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}})}},fs=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function ps(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 ms(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function hs(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 Pae(){if(es!==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 Fae(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 Iae=new Uint8Array([101,97,101,95,112,114,107]),Lae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Rae(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 zae=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(jae);r.set(ps(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(ds(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(ds(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=ds(e);if(t.byteLength>8192)throw new Xo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():fs(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=fs(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=ms(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=ms(new Uint8Array(n),new Uint8Array(r));else{let t=fs(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Rae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new xae(e)}}async decap(e){let t=ds(e.enc),n=await this._prim.deserializePublicKey(t),r=fs(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=fs(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)):ms(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=ms(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 Sae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(Iae,e),r=this._kdf.buildLabeledInfo(Lae,t,this.secretSize);return await this._kdf.extractAndExpand(as,n,r,this.secretSize)}},gs=[`deriveBits`],Bae=new Uint8Array([100,107,112,95,112,114,107]),Vae=new Uint8Array([115,107]),_s=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=[])}},Hae=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 Zo(e))}}async deserializePublicKey(e){try{return await this._importRawKey(ds(e),!0)}catch(e){throw new Qo(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Zo(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(ds(e),!1)}catch(e){throw new Qo(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 Qo(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new _s(this._algName,e,`private`,gs);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new $o(e)}}async deriveKeyPair(e){try{let t=ds(e),n=await this._hkdf.labeledExtract(as.buffer,Bae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Vae,as,this._nSk),i=new _s(this._algName,new Uint8Array(r),`private`,gs);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Dae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new _s(this._algName,t,`public`))}catch(e){return Promise.reject(new Qo(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new Zo(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 _s(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:gs))})}_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 _s(this._algName,hs(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new _s(this._algName,hs(e.d),`private`,gs)))})}};function Uae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function vs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function ys(e,t,n=``){let r=Uae(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 bs(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 xs(e,t){ys(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function Wae(e){if(typeof e==`bigint`){if(!Ms(e))throw Error(`positive bigint expected, got `+e)}else vs(e);return e}function Ss(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Cs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Gae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ws(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ts(e,t){return e<<32-t|e>>>t}var Es=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Kae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),qae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Jae(e){if(ys(e),Es)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Kae[e[n]];return t}var Ds={_0:48,_9:57,A:65,F:70,a:97,f:102};function Os(e){if(e>=Ds._0&&e<=Ds._9)return e-Ds._0;if(e>=Ds.A&&e<=Ds.F)return e-(Ds.A-10);if(e>=Ds.a&&e<=Ds.f)return e-(Ds.a-10)}function Yae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Es)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=Os(e.charCodeAt(i)),a=Os(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 Xae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=os;for(let n=0;n<e.length;n++){let r=Os(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|qae[r]}return t}function ks(e){vs(e,`numberToBigint`);let t=e,n=os,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function As(e){return Xae(Jae(js(ys(e)).reverse()))}function Zae(e,t){vs(t),e=Wae(e);let n=Yae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function Qae(e,t){return Zae(e,t).reverse()}function js(e){return Uint8Array.from(e)}function Ms(e){return typeof e==`bigint`&&0n<=e}function $ae(e,t,n){return Ms(e)&&Ms(t)&&Ms(n)&&t<=e&&e<n}function Ns(e,t,n,r){if(!$ae(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function eoe(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 toe(e=32){let t=await Pae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function noe(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function roe(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);vs(e.outputLen),vs(e.blockLen)}function ioe(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 Ps=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}),roe(e),ys(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),Cs(r)}update(e){return bs(this),this.iHash.update(e),this}digestInto(e){bs(this),ys(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()}},Fs=(e,t,n)=>new Ps(e,t).update(n).digest();Fs.create=(e,t)=>new Ps(e,t);function aoe(e,t,n){return e&t^~e&n}function ooe(e,t,n){return e&t^e&n^t&n}var soe=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=ws(this.buffer)}update(e){bs(this),ys(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=ws(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){bs(this),xs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Cs(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,ks(this.length*8),i),this.process(n,0);let o=ws(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()}},Is=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),coe=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]),Ls=new Uint32Array(64),loe=class extends soe{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)Ls[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ls[e-15],n=Ls[e-2],r=Ts(t,7)^Ts(t,18)^t>>>3,i=Ts(n,17)^Ts(n,19)^n>>>10;Ls[e]=i+Ls[e-7]+r+Ls[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=Ts(o,6)^Ts(o,11)^Ts(o,25),u=l+t+aoe(o,s,c)+coe[e]+Ls[e]|0,d=(Ts(n,2)^Ts(n,13)^Ts(n,22))+ooe(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(){Cs(Ls)}destroy(){this.set(0,0,0,0,0,0,0,0),Cs(this.buffer)}},uoe=class extends loe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Is[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Is[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Is[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Is[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Is[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Is[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Is[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Is[7]|0})}},Rs=ioe(()=>new uoe,noe(1));function zs(e,t){let n=e%t;return n>=0n?n:t+n}function Bs(e,t,n){let r=e;for(;t-->os;)r*=r,r%=n;return r}function doe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function foe(e){return eoe(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function poe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=foe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||toe,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?cs**254n:cs**447n,p=f+(o?8n*cs**251n-ss:4n*cs**445n-ss)+ss,m=e=>zs(e,t),h=g(u);function g(e){return Qae(m(e),l)}function _(e){let t=js(ys(e,l,`uCoordinate`));return o&&(t[31]&=127),m(As(t))}function v(e){return As(r(js(ys(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){Ns(`u`,e,os,t),Ns(`scalar`,n,f,p);let r=n,a=e,o=ss,s=os,l=e,u=ss,h=os;for(let e=c-1n;e>=os;e--){let t=r>>e&ss;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)),ys(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:doe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Vs(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var moe=(e,t)=>{function n(n,...r){if(ys(n,void 0,`key`),!Gae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];ys(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&ys(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`);ys(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,ys(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(ys(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 hoe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function goe(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 Hs(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&&!voe(t))throw Error(`invalid output, must be aligned`);return t}function _oe(e,t,n){Vs(n);let r=new Uint8Array(16),i=ws(r);return i.setBigUint64(0,ks(t),n),i.setBigUint64(8,ks(e),n),r}function voe(e){return e.byteOffset%4==0}var Us=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),yoe=Us(`expand 16-byte k`),boe=Us(`expand 32-byte k`),xoe=Ss(yoe),Soe=Ss(boe);function Ws(e,t){return e<<t|e>>>32-t}function Gs(e){return e.byteOffset%4==0}var Ks=64,Coe=16,qs=2**32-1,Js=Uint32Array.of();function woe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Ks),u=Ss(l),d=Gs(i)&&Gs(a),f=d?Ss(i):Js,p=d?Ss(a):Js;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=qs)throw Error(`arx: counter overflow`);let h=Math.min(Ks,c-m);if(d&&h===Ks){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Coe;t++)n=e+t,p[n]=f[n]^u[t];m+=Ks;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function Toe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=hoe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return vs(i),vs(o),Vs(a),Vs(n),(t,s,c,l,u=0)=>{ys(t,void 0,`key`),ys(s,void 0,`nonce`),ys(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),ys(l,void 0,`output`),vs(u),u<0||u>=qs)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=js(t)),h=Soe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=xoe,f.push(m);else throw ys(t,32,`arx key`),Error(`invalid key size`);Gs(s)||f.push(s=js(s));let g=Ss(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,Ss(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=Ss(s);return woe(e,h,g,v,c,l,u,o),Cs(...f),l}}function Ys(e,t){return e[t++]&255|(e[t++]&255)<<8}var Eoe=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=js(ys(e,32,`key`));let t=Ys(e,0),n=Ys(e,2),r=Ys(e,4),i=Ys(e,6),a=Ys(e,8),o=Ys(e,10),s=Ys(e,12),c=Ys(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]=Ys(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=Ys(e,t+0),_=Ys(e,t+2),v=Ys(e,t+4),y=Ys(e,t+6),b=Ys(e,t+8),x=Ys(e,t+10),S=Ys(e,t+12),C=Ys(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;Cs(n)}update(e){bs(this),ys(e),e=js(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(){Cs(this.h,this.r,this.buffer,this.pad)}digestInto(e){bs(this),xs(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 Doe(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 Ooe=Doe(e=>new Eoe(e));function koe(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=Ws(A^S,16),ne=ne+A|0,E=Ws(E^ne,12),S=S+E|0,A=Ws(A^S,8),ne=ne+A|0,E=Ws(E^ne,7),C=C+D|0,ie=Ws(ie^C,16),O=O+ie|0,D=Ws(D^O,12),C=C+D|0,ie=Ws(ie^C,8),O=O+ie|0,D=Ws(D^O,7),w=w+ee|0,ae=Ws(ae^w,16),k=k+ae|0,ee=Ws(ee^k,12),w=w+ee|0,ae=Ws(ae^w,8),k=k+ae|0,ee=Ws(ee^k,7),T=T+te|0,oe=Ws(oe^T,16),re=re+oe|0,te=Ws(te^re,12),T=T+te|0,oe=Ws(oe^T,8),re=re+oe|0,te=Ws(te^re,7),S=S+D|0,oe=Ws(oe^S,16),k=k+oe|0,D=Ws(D^k,12),S=S+D|0,oe=Ws(oe^S,8),k=k+oe|0,D=Ws(D^k,7),C=C+ee|0,A=Ws(A^C,16),re=re+A|0,ee=Ws(ee^re,12),C=C+ee|0,A=Ws(A^C,8),re=re+A|0,ee=Ws(ee^re,7),w=w+te|0,ie=Ws(ie^w,16),ne=ne+ie|0,te=Ws(te^ne,12),w=w+te|0,ie=Ws(ie^w,8),ne=ne+ie|0,te=Ws(te^ne,7),T=T+E|0,ae=Ws(ae^T,16),O=O+ae|0,E=Ws(E^O,12),T=T+E|0,ae=Ws(ae^T,8),O=O+ae|0,E=Ws(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 Aoe=Toe(koe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),joe=new Uint8Array(16),Xs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(joe.subarray(n))},Moe=new Uint8Array(32);function Zs(e,t,n,r,i){i!==void 0&&ys(i,void 0,`AAD`);let a=e(t,n,Moe),o=_oe(r.length,i?i.length:0,!0),s=Ooe.create(a);i&&Xs(s,i),Xs(s,r),s.update(o);let c=s.digest();return Cs(a,o),c}var Qs=moe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=Hs(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Zs(e,t,n,s,r);return a.set(c,o),Cs(c),a},decrypt(i,a){a=Hs(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Zs(e,t,n,o,r);if(!goe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Cs(c),a}}))(Aoe)),Noe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(ds(e))}async seal(e,t,n){return await this._seal(ds(e),ds(t),ds(n))}async open(e,t,n){return await this._open(ds(e),ds(t),ds(n))}_seal(e,t,n){return new Promise(r=>{r(Qs(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(Qs(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},Poe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:is.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 Noe(e)}};function $s(){return new Promise((e,t)=>{t(new $o(`Not supported`))})}var Foe=new Uint8Array([115,101,99]),ec=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 $s()}async open(e,t){return await $s()}async export(e,t){let n=ds(e);if(n.byteLength>8192)throw new Xo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Foe,new Uint8Array(n),t)}catch(e){throw new Cae(e)}}},Ioe=class extends ec{},Loe=class extends ec{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}},tc=class extends ec{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=ps(e.seq,e.baseNonce.byteLength);return Fae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new Eae(`Message limit reached`);e.seq+=1}},Roe=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)},zoe=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,rc=class{constructor(){nc.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Roe(this,nc,`f`);return zoe(this,nc,t,`f`),await n,e}};nc=new WeakMap;var ic=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)},Boe=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},ac,Voe=class extends tc{constructor(){super(...arguments),ac.set(this,void 0)}async open(e,t=as.buffer){Boe(this,ac,ic(this,ac,`f`)??new rc,`f`);let n=await ic(this,ac,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),ds(e),ds(t))}catch(e){throw new Tae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};ac=new WeakMap;var oc=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},sc,Uoe=class extends tc{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),sc.set(this,void 0),this.enc=r}async seal(e,t=as.buffer){Hoe(this,sc,oc(this,sc,`f`)??new rc,`f`);let n=await oc(this,sc,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),ds(e),ds(t))}catch(e){throw new wae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};sc=new WeakMap;var Woe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Goe=new Uint8Array([101,120,112]),Koe=new Uint8Array([105,110,102,111,95,104,97,115,104]),qoe=new Uint8Array([107,101,121]),Joe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Yoe=new Uint8Array([115,101,99,114,101,116]),Xoe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Zoe=class extends ts{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 Xo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new Xo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new Xo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array(Xoe),this._suiteId.set(ps(this._kem.id,2),4),this._suiteId.set(ps(this._kdf.id,2),6),this._suiteId.set(ps(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?ns.Base:ns.Auth:e.senderKey===void 0?ns.Psk:ns.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?ns.Base:ns.Auth:e.senderPublicKey===void 0?ns.Psk:ns.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=as.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=as.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?as:us(n.psk.id),i=await this._kdf.labeledExtract(as,Joe,r),a=n.info===void 0?as:us(n.info),o=await this._kdf.labeledExtract(as,Koe,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?as:us(n.psk.key),l=this._kdf.buildLabeledIkm(Yoe,c),u=this._kdf.buildLabeledInfo(Goe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===is.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(qoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(Woe,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 Loe(this._api,this._kdf,i.exporterSecret,n):new Uoe(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 Ioe(this._api,this._kdf,r.exporterSecret):new Voe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new Xo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new Xo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new Xo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new Xo(`Too long psk.id`)}}},Qoe=class extends Zoe{},$oe=1n,cc=2n,ese=3n,tse=5n,lc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function nse(e){let t=10n,n=80n,r=lc,i=e*e%r*e%r,a=Bs(Bs(i,cc,r)*i%r,$oe,r)*e%r,o=Bs(a,tse,r)*a%r,s=Bs(o,t,r)*o%r,c=Bs(s,20n,r)*s%r,l=Bs(c,40n,r)*c%r;return{pow_p_5_8:Bs(Bs(Bs(Bs(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,cc,r)*e%r,b2:i}}function rse(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var ise=(()=>{let e=lc;return poe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=nse(t);return zs(Bs(n,ese,e)*r,e)},adjustScalarBytes:rse})})(),ase=class extends Hae{constructor(e){super(`X25519`,32,ise,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new Zo(e))}}},uc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,ose=2**31,sse=65536,cse=16,dc=32,fc=(1n<<255n)-19n,pc=new TextEncoder,mc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function hc(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 lse=new Set([0n,1n,hc(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),hc(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),fc-1n]),use=new Uint8Array,gc=class extends Nae{async extract(e,t){return ds(Fs(Rs,e.byteLength===0?new Uint8Array(this.hashSize):us(e),us(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=us(e),i=us(t),a=new Uint8Array(n),o=use;for(let e=1,t=0;t<a.byteLength;e+=1){let n=bc([o,i,Uint8Array.of(e)]);o=new Uint8Array(Fs(Rs,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 ds(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},_c=new Qoe({kem:new class extends zae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Aae.DhkemX25519HkdfSha256,new ase(e),e)}}(new gc),kdf:new gc,aead:new Poe}),vc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function yc(e){return new Uint8Array(e.slice(0))}function dse(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function bc(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 xc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new vc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function Sc(e){if(!Number.isSafeInteger(e)||e<0)throw new vc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function fse(e){return bc([xc(e.byteLength),e])}function Cc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function pse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function wc(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+=mc[o>>>18&63],t+=mc[o>>>12&63],n+1<e.byteLength&&(t+=mc[o>>>6&63]),n+2<e.byteLength&&(t+=mc[o&63])}return t}function Tc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new vc(`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=mc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(wc(t)!==e)throw new vc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function mse(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 lse.has(n%fc)}var hse={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new vc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return yc(await globalThis.crypto.subtle.digest(`SHA-256`,dse(e)))}},Ec={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new vc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function Dc(e,t){let n=pc.encode(e).byteLength;if(n===0||n>256)throw new vc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function gse(e){let t=pc.encode(e).byteLength;if(t===0||t>65536)throw new vc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${sse} UTF-8 bytes.`)}async function Oc(e,t=hse){gse(e.exactCompactTicket),Dc(e.channelId,`Channel ID`),Dc(e.runtimeId,`Runtime ID`),Sc(e.connectionEpoch);let n=await t.sha256(pc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new vc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function _se(e){return wc(e.ticketDigest)}async function vse(e=Ec){let t=new Uint8Array(await e.randomBytes(dc));if(t.byteLength!==dc)throw new vc(`endpoint_key_invalid`,`The endpoint random source must return ${dc} bytes.`);try{return wc(t)}finally{t.fill(0)}}function kc(e){return bc([pc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,Cc(e.direction)])}function Ac(e){return bc([pc.encode(`forge-relay`),xc(4),e.binding.ticketDigest,pc.encode(e.binding.channelId),Cc(e.binding.direction),pse(e.frameClass),Sc(e.sequence),pc.encode(e.binding.runtimeId),Sc(e.binding.connectionEpoch),xc(e.ciphertextLength)].map(fse))}async function yse(e=Ec){let t=new Uint8Array(await e.randomBytes(dc));if(t.byteLength!==dc)throw new vc(`endpoint_key_invalid`,`The endpoint random source must return ${dc} bytes.`);try{return await _c.kem.deriveKeyPair(t)}catch(e){throw new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function jc(e){try{return wc(yc(await _c.kem.serializePublicKey(e)))}catch(e){throw new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function bse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new vc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function xse(e){try{let t=Tc(e);if(t.byteLength!==dc)throw Error(`Invalid endpoint key length.`);if(mse(t))throw new vc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await _c.kem.deserializePublicKey(t)}catch(e){throw e instanceof vc?e:new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var Mc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Nc=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=ose||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new vc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function Sse(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 vc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var Cse=class{binding;context;encapsulatedKey;queue=new Mc;budget=new Nc;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=wc(yc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new vc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+cse;this.budget.assertAvailable(t);let n=this.sequence,r=Ac({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=yc(await this.context.seal(e.plaintext,r))}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new vc(`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:wc(i)}})}},wse=class{binding;context;queue=new Mc;budget=new Nc;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(Sse(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new vc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Tc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Ac({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=yc(await this.context.open(t,n))}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new vc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function Tse(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Ec).randomBytes(dc)),t.byteLength!==dc)throw Error(`The endpoint random source must return ${dc} bytes.`);let n=await _c.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:kc(e.binding),ekm:t});return new Cse(e.binding,n)}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function Ese(e){try{let t=await _c.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Tc(e.encapsulatedKey),info:kc(e.binding)});return new wse(e.binding,t)}catch(e){throw e instanceof vc?e:new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Dse=128,Ose=2097152,kse=864e5,Pc=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Fc(e){return typeof e==`string`&&e.length>0}function Ic(e){return Fc(e)&&Number.isFinite(Date.parse(e))}function Ase(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function jse(e){return Fc(e.transportRequestId)&&Fc(e.runtimeId)&&Fc(e.actorSessionId)&&Fc(e.durableRequestId)&&Fc(e.method)}function Mse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Nse(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Fc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function Pse(e){return!Ase(e.status)||e.errorCode!==null&&!Fc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Fc(e.errorCode):e.errorCode===null}function Fse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return jse(t)&&Mse(t)&&Nse(t)&&Pse(t)&&Ic(t.createdAt)&&Ic(t.updatedAt)}function Ise(e){try{return JSON.parse(e)}catch{throw new Pc(`Forge relay control journal is corrupt.`)}}function Lse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Fc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Fse)}function Rse(e){let t=new Set(e.map(Lc)),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 zse(e){let t=Ise(e);if(!Lse(t))throw new Pc(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Rse(n)||t.nextSequence<=r)throw new Pc(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Bse(){return crypto.randomUUID()}function Lc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Rc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Vse(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)=>Rc[t.status]>Rc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function zc(e){let t=e.randomUUID??Bse,n=e.now??(()=>new Date),r=e.maxRecords??Dse,i=e.maxBytes??Ose,a=e.maxReplayAgeMs??kse;if(r<1||i<1||a<1)throw new Pc(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?zse(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 Pc(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new Pc(`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=Lc(e);return{key:t,existing:c.records.find(e=>Lc(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 Pc(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new Pc(`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 Pc(`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 Pc(`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(Lc({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 Pc(`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(Lc({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 Pc(`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(Lc(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 Hse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Use=rn(dne),Wse=vn(mne),Gse=vn(ine),Kse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Bc(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 Vc(e,t){let n=JSON.parse(e),r=fae(n);if(r!==null)return{messageType:`request`,...r};let i=qse(n,t);if(i!==null)return i;let a=Jse(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function qse(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=Jo({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Bc(e.headers,$n.requestId)??e.id,method:e.tag,...n}}function Jse(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 Hc(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 Yse=new Set([`network`,`server`,`auth`,`permission`,`client`]),Xse=new Set([`network`,`server`]);function Zse(e){return e&&typeof e==`object`?e:{}}function Qse(e){return typeof e.code==`string`&&e.code.length>0?e.code:typeof e.kind==`string`&&Yse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function $se(e){if(e.retryable===!0||typeof e.kind==`string`&&Xse.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Uc(e){let t=Zse(e);return{code:Qse(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:$se(t)}}function Wc(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 ece(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values($n).includes(e[0])}function Gc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function tce(e){if(!Array.isArray(e))return null;for(let t of e){let e=Gc(t);if(e?._tag!==`Fail`)continue;let n=Gc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function nce(e){let t=Gc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:tce(t.cause)??`RELAY_RPC_FAILED`}function Kc(e){if(typeof e!=`string`)return null;try{let t=Use(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function rce(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 qc(e,t,n){if(typeof e==`string`)try{let r=Gc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=nce(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 ice(e){let t=Bc(e,$n.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function ace(e){return{issuedAt:Bc(e,$n.issuedAt)??new Date().toISOString(),expiresAt:Bc(e,$n.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function oce(e){if(e!==2&&e!==3&&e!==4)throw new Go(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function sce(e){let t=bae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=cce(e.context);if(e.acquire===void 0)throw new Go(`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 cce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new Go(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Jc(e.channelId),channelTicketDigest:Jc(e.channelTicketDigest),runtimeEndpointKeyId:Jc(e.runtimeEndpointKeyId),controlEndpointKeyId:Jc(e.controlEndpointKeyId)}}function Jc(e){if(typeof e==`string`&&e.length>0)return e;throw new Go(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function lce(e){return e===void 0?{}:{sequence:e}}function Yc(e){return e===void 0?{}:{actionGrant:e}}async function uce(e){let t=Vc(e.data,e.context.scopes),n=JSON.parse(e.data),r=ace(n.headers),i=ice(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await sce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=oce(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,...lce(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Yc(o)}:{protocolVersion:4,...c,...Yc(o)}}function Xc(e){return typeof e==`string`&&e.length>0}function dce(e){return[e.protocolVersion===4,Xc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===uc,Xc(e.channelId),Xc(e.runtimeEndpointKeyId),Xc(e.runtimeEndpointPublicKey),Xc(e.controlEndpointKeyId),Xc(e.controlEndpointPublicKey),Xc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function Zc(e){if(!dce(e))throw new Go(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function fce(e){if(await jc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new Go(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await xse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Oc({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Oc({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 Tse({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function Qc(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function pce(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 mce(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 hce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new Go(`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 Go(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await Ese({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var gce=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=Wc(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`,Wc(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=Vc(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=Uc(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`,Hc(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 uce({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 Go(`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 Cce({payload: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=>!ece(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&&qc(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=Uc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Hc(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 fce(Zc(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Kse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Uc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Hc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Kc(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`,Hc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=rce(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=Zc(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:_se(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=Zc(this.route);if(t===null||n===null||!Qc(e,r,`handshake`))throw new Go(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await hce({channel:t,route:r,message:e})).open(e),a=Wse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!pce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new Go(`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=Kc(e);if(t?.type!==`relay.encrypted-frame`)throw new Go(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!Qc(t,Zc(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new Go(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Gse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!mce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new Go(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);qc(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 _ce(e,t,n=$c,r=zc({storage:Hse(),randomUUID:n.randomUUID}),i={},a){return new gce(e,t,n,r,i,a).asWebSocket()}var vce=ko(pne);async function yce(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 $c={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:yce},el=`forge-relay-binding=`,bce=3e4;function xce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(el))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 Sce(e){let t=e.crypto??$c,n=e.bindingTtlMs??bce,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=`${el}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=xce(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?.(),_ce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}async function Cce(e){let t=e.issuedAt??new Date,n=e.crypto??$c;return{[$n.requestId]:e.requestId??n.randomUUID(),[$n.sequence]:String(e.sequence),[$n.issuedAt]:t.toISOString(),[$n.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[$n.payloadHash]:await n.sha256Base64Url(uae(e.payload))}}function wce(e,t){return Xte(tne,({rpc:t,request:n,next:r})=>ot(function*(){return Jo({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function Tce(e,t=$c){return vce.pipe(Se(wce(e,t)))}function Ece(e){let t=e.crypto??$c,n=Sce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=gt(n.acquireSocketUrl).pipe(c),i=he(oa,n.constructSocket),a=sa(r).pipe(E(i)),o=e.delayForRetry??lae,s=Lt(_(e.maxRetries??10),e=>rt(Ue(o(e)??0)));return ht(Mo,No({retryPolicy:s,retryTransientErrors:!0})).pipe(E(De(a,Oo)))}var tl=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Dce(e){let t=await yse(e),n=await jc(t.publicKey);return{keyPair:t,publicKey:n,keyId:bse(`control`,n),channelNonce:await vse(e)}}function Oce(e){return{hpkeSuite:uc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function kce(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 tl(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:uc,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 nl=`~effect/ManagedRuntime`,rl=(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=Pt(t=>(c||=f(Aee(o(e,n,i),e=>pt(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),Bee(ve(c)))),u={[nl]:nl,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:At(()=>(u.contextEffect=yee(`ManagedRuntime disposed`),u.cachedContext=void 0,He(u.scope,Tt))),runFork(e,t){return u.cachedContext===void 0?f(il(u,e),s(t)):We(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?cee(il(u,e),s(t)):hte(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Zee(il(u,e)):le(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?fe(il(u,e)):See(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?pee(il(u,e),s(t)):vee(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?A(il(u,e),s(t)):ne(u.cachedContext)(e,s(t))}};return u};function il(e,t){return wt(e.contextEffect,e=>Te(t,e))}function al(e,t=Cne){return`${e}\0${t}`}function Ace(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=al(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(al(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(al(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 ol={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function sl(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function jce(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?sl(t.keyframe):null}function Mce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?ol:t.streamGeneration>e.streamGeneration?sl(t.keyframe):null}function Nce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return sl(t.keyframe);if(t.sequence<=e.observedSequence)return ol;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function Pce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return ol;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?ol:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Fce(e,t){return jce(e,t)??Mce(e,t)??Nce(e,t)??Pce(e,t)}function Ice(e,t){let n=Fce(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}}vn(ane);var cl=O(),ll=`Forge`,Lce=`Alpha`,ul=ll,dl=`0.13.4`,fl=Zt(`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`),pl=`flex h-full min-w-0 items-center gap-1 md:gap-1.5`,ml=`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`,Rce={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`},zce=`forge-app-shell flex w-full min-w-0 flex-row`,hl=`forge-app-shell flex w-full min-w-0 flex-col`,Bce=`flex min-h-0 min-w-0 flex-1 flex-col`,Vce=`relative flex h-[var(--forge-content-height)] min-h-0 min-w-0 flex-1 overflow-hidden`;function gl(e){let t=(0,cl.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,Nr.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=Zt(`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,Nr.jsx)(`span`,{className:m,children:ll}),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,Nr.jsx)(`span`,{className:_,children:Lce}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Nr.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,Nr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":ul,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,Nr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":ul,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function _l(e){let t=(0,cl.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Zt(`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,Nr.jsx)(gl,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Nr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}function Hce(){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 vl=typeof window<`u`?window.localStorage:Hce(),Uce=(e,t)=>rr(Bn(e))(t),Wce=(e,t)=>Dte(Bn(e))(t),yl=(e,t)=>{let n=vl.getItem(e);return n?Uce(t,n):null},bl=(e,t,n)=>{let r=Wce(n,t);vl.setItem(e,r)},xl=e=>{vl.removeItem(e)},Sl=`forge:local_storage_change`;function Gce(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(Sl,{detail:{key:e}}))}function Cl(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return yl(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?xl(e):bl(e,i,n),queueMicrotask(()=>Gce(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=yl(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=yl(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(Sl,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(Sl,o)}},[e,t,n]),[r,a]}var wl=`cmmd-runtime:`;function Tl(e){return`${wl}${e}`}var Kce=/^env_[0-9a-f]{32}$/,qce=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,El={shape:`local`,isCloud:!1,legacyRuntimeId:null},Jce={shape:`cloud-project-placeholder`,isCloud:!0,legacyRuntimeId:null},Yce={shape:`durable-environment`,isCloud:!0,legacyRuntimeId:null};function Dl(e){if(typeof e!=`string`)return El;if(e.startsWith(`cmmd-runtime:`)){let t=e.slice(wl.length);return qce.test(t)?{shape:`legacy-runtime`,isCloud:!0,legacyRuntimeId:t}:El}return e.startsWith(`cmmd-cloud-project:`)?Jce:Kce.test(e)?Yce:El}var Ol=`forge:client-settings:v1`,Xce=`forge:saved-environment-registry:v1`,Zce=nr({environmentId:an,label:j,httpBaseUrl:j,wsBaseUrl:j,createdAt:j,lastConnectedAt:Kn(j),cmmdOrganizationId:cn(j),cmmdProjectId:cn(j),runtimeId:cn(j),runtimeTicketExpiresAt:cn(j),lastAuthenticatedPullRequestCapability:cn(Xn),bearerToken:cn(j)}),kl=nr({version:cn(Ln),records:cn(Jn(Zce))});function Al(){return typeof window<`u`}var Qce={uiFontSize:14,codeFontSize:15},$ce=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function ele(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function tle(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(Qce).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 nle(e){let t=$ce.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 jl(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[ele,tle,nle]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function rle(){if(!Al())return null;try{let e=window.localStorage.getItem(Ol);return e?vn(tr)(jl(JSON.parse(e))):null}catch{return null}}function ile(e){Al()&&bl(Ol,e,tr)}function Ml(){if(!Al())return{};try{return yl(`forge:saved-environment-registry:v1`,kl)??{}}catch{return{}}}function Nl(e){Al()&&bl(Xce,e,kl)}function Pl(){return Ml().records??[]}function ale(e){Nl({version:1,records:e})}function ole(){return Pl().map(e=>wn(e))}function sle(e){let t=new Map(Pl().map(e=>[e.environmentId,e]));ale(e.map(e=>{let n=Dl(e.environmentId).legacyRuntimeId===null?t.get(e.environmentId)?.bearerToken:void 0;return n?{...wn(e),bearerToken:n}:wn(e)}))}function cle(e){return Pl().find(t=>t.environmentId===e)?.bearerToken??null}function lle(e,t){let n=Ml(),r=n.records??[],i=!1;return Nl({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(wn(n),{bearerToken:t})):n)}),i}function ule(e){let t=Ml();Nl({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?wn(t):t)})}var dle=vn(tr);function fle(){return typeof window>`u`?void 0:window.desktopBridge}function Fl(e){let t=fle(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function Il(){let e=Fl(`getClientSettings`);if(e){let t=await e();return t?dle(t):null}return rle()}async function Ll(e){let t=Fl(`setClientSettings`);if(t)return t(e);ile(e)}async function Rl(){let e=Fl(`getSavedEnvironmentRegistry`);return e?e():ole()}async function zl(e){let t=Fl(`setSavedEnvironmentRegistry`);if(t)return t(e);sle(e)}async function Bl(e){let t=Fl(`getSavedEnvironmentSecret`);return t?t(e):cle(e)}async function Vl(e,t){let n=Fl(`setSavedEnvironmentSecret`);return n?n(e,t):lle(e,t)}async function Hl(e){let t=Fl(`removeSavedEnvironmentSecret`);if(t)return t(e);ule(e)}var Ul=`token`;function Wl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Gl(e){let t=Wl(e).get(Ul)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Ul)?.trim()??``;return n.length>0?n:null}function ple(e){let t=new URL(e.toString()),n=Wl(t);return n.has(Ul)&&(n.delete(Ul),t.hash=n.toString()),t.searchParams.delete(Ul),t}function Kl(e,t){let n=new URL(e.toString());return n.searchParams.delete(Ul),n.hash=new URLSearchParams([[Ul,t]]).toString(),n}function mle(e,t){let n=new URL(e);return n.pathname=`/login`,Kl(n,t).toString()}function hle(e){return Kl(new URL(`/login`,window.location.href),e).toString()}function gle(e){let t=new URL(e),n=Gl(t),r=new URL(`forge:///pair`);return r.searchParams.set(`serverUrl`,t.origin),n&&r.searchParams.set(Ul,n),r.toString()}function _le(e){return{_tag:`Value`,value:e}}function vle(e,t){return{_tag:`Record`,keys:e,value:t}}function yle(e,t){return{_tag:`Array`,length:e,value:t}}$t(`SourceError`);var ble=$e(`effect/ConfigProvider`,{defaultValue:()=>Cle()}),xle={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Sle(e,t,n){let r=Object.create(xle);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 Cle(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:`a3822a9b2aed0923a7289c64337048a09fc730fa`,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+a3822a9b2aed0923a7289c64337048a09fc730fa`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=wle(t);return Sle(e=>rt(Ele(n,t,e)))}function wle(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 Tle=/^(0|[1-9][0-9]*)$/;function Ele(e,t,n){let r=t[n.map(String).join(`_`)],i=Dle(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:_le(r):a.every(e=>Tle.test(e))?yle(Math.max(...a.map(e=>parseInt(e,10)))+1,r):vle(new Set(a),r)}function Dle(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 ql=`~effect/Config`,Ole=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},kle={...Ke,...Cee,[ql]:ql,asEffect(){return wt(ble.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Ale(e){let t=Object.create(kle);return t.parse=e,t}var Jl=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*Jl(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*Jl(e,[...t,i]));return r}}}),Yl=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*Yl(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=qte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*Yl(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*Yl(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Jl(t,n);case`Suspend`:return yield*Yl(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 Xl(e,t){let n=Ute(e),r=Pte(n),i=Yte(n.ast),a=typeof t==`string`?[t]:t??[];return Ale(e=>{let t=e.prefix?[...e.prefix,...a]:a;return Yl(i,e,a).pipe(tte(e=>r(e).pipe(It(e=>new Ote(t.length>0?new Fte(t,e):e)))),It(e=>new Ole(e)))})}var jle=(e,t,n)=>{let r=In(e,t),i=j.pipe(xn(In(j,j),Nte(n)),xn(r));return ir([r,i])},B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Zl=`10.74.0`;function Ql(){return $l(V),V}function $l(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.74.0`,t[Zl]=t[`10.74.0`]||{}}function eu(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Zl]=r[`10.74.0`]||{};return i[e]||(i[e]=t())}var tu=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],Mle=`Sentry Logger `,nu={};function ru(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys(nu);r.forEach(e=>{let r=nu[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Nle(){ou().enabled=!0}function Ple(){ou().enabled=!1}function iu(){return ou().enabled}function Fle(...e){au(`log`,...e)}function Ile(...e){au(`warn`,...e)}function Lle(...e){au(`error`,...e)}function au(e,...t){B&&iu()&&ru(()=>{V.console[e](`${Mle}[${e}]:`,...t)})}function ou(){return B?eu(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:Nle,disable:Ple,isEnabled:iu,log:Fle,warn:Ile,error:Lle},su=50,cu=/\(error: (.*)\)/,lu=/captureMessage|captureException/;function uu(...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 it,fi as at,fr as zee,ft as ot,gi as st,gn as ct,gt as lt,hn as ut,hr as dt,ht as ft,in as pt,it as Bee,j as mt,ja as Vee,jn as ht,jr as Hee,jt as gt,ki as _t,kr as Uee,kt as vt,li as yt,ln as Wee,m as Gee,mn as bt,mr as xt,mt as St,na as Kee,ni as qee,nr as Ct,nt as wt,oa as Jee,on as Yee,or as Tt,pi as Xee,pn as Et,pt as Dt,q as Ot,qn as kt,qt as Zee,r as Qee,ri as $ee,rn as At,rr as ete,rt as tte,s as nte,si as rte,sn as ite,st as jt,ui as ate,un as Mt,ut as Nt,vn as Pt,vr as ote,vt as ste,w as Ft,wn as cte,wr as lte,wt as It,x as ute,xi as dte,xn as Lt,y as fte,yi as pte,yn as Rt,yt as mte,z as zt,zn as Bt,zt as hte}from"./Stream-mUTFnSY9.js";import{i as gte,l as Vt,n as Ht,o as Ut,s as Wt}from"./atomRegistry-C1yW8tyM.js";import{En as _te,Fn as Gt,J as Kt,On as vte,Rn as yte,Tn as qt,an as Jt,cn as bte,dn as Yt,fn as Xt,gn as xte,hn as Zt,i as Ste,ln as Cte,on as wte,sn as Qt,un as Tte}from"./CompositeItem-BuglG3oi.js";import{$n as $t,$t as Ete,A as en,An as Dte,At as tn,Bn as Ote,Bt as kte,C as Ate,Ct as jte,D as nn,Dn as rn,Dt as an,En as on,Et as sn,Fn as cn,Ft as Mte,Gn as Nte,Gt as ln,H as un,Hn as Pte,Ht as dn,In as fn,It as pn,Jn as Fte,Jt as Ite,Kt as mn,L as Lte,Ln as hn,Lt as Rte,Mn as zte,Mt as gn,Nt as Bte,O as _n,On as vn,Pn as yn,Pt as Vte,Qt as Hte,Rn as Ute,Rt as Wte,St as bn,Tn as xn,Tt as Sn,U as Gte,Un as Kte,Ut as Cn,V as wn,Vn as qte,Vt as Tn,W as Jte,Wn as Yte,Wt as En,Xt as Dn,Y as Xte,Yt as Zte,Z as Qte,Zt as $te,_n as j,_t as On,a as ene,an as kn,b as An,bn as jn,c as Mn,cn as Nn,d as tne,dt as Pn,en as nne,et as rne,f as ine,fn as Fn,g as ane,gn as In,gt as one,hn as Ln,ht as Rn,i as sne,in as cne,j as zn,jn as Bn,jt as Vn,k as lne,kn as une,kt as Hn,l as Un,ln as Wn,lt as Gn,m as dne,mn as Kn,nn as fne,nt as qn,o as pne,on as Jn,p as mne,pn as hne,pt as gne,q as _ne,qt as Yn,rn as vne,s as M,sn as Xn,tn as Zn,tt as Qn,u as $n,ut as er,v as tr,vn as nr,w as yne,wn as rr,x as bne,xn as ir,yn as xne,yt as Sne,z as Cne,zt as ar}from"./src-DVtrA7UW.js";import{A as or,C as wne,D as sr,F as Tne,I as Ene,L as cr,M as lr,N as Dne,O as ur,S as One,T as dr,a as fr,b as kne,c as Ane,d as jne,j as pr,k as mr,l as Mne,n as hr,s as Nne,u as Pne,v as Fne,x as Ine,y as Lne}from"./cmmdAuthRedirect-BUli2MC4.js";import{t as N}from"./preload-helper-Czpn1I53.js";import{n as P,t as gr}from"./transport-CgH8pQK3.js";import{n as Rne,t as zne}from"./workspaceReadinessAtom-D6bgTvKb.js";function Bne(e){return e[e.length-1]}function Vne(e,t){return typeof e==`function`?e(t):e}var _r=Object.prototype.hasOwnProperty,Hne=Object.prototype.propertyIsEnumerable;function Une(e){for(let t in e)if(_r.call(e,t))return!0;return!1}var Wne=()=>Object.create(null),Gne=(e,t)=>vr(e,t,Wne);function vr(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Sr(e)&&Sr(i);if(!a&&!(br(e)&&br(i)))return i;let o=a?e:yr(e);if(!o)return i;let s=a?i:yr(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:_r.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=vr(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function yr(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(!Hne.call(e,r))return!1;t.push(r)}return t}function br(e){if(!xr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!xr(n)||!n.hasOwnProperty(`isPrototypeOf`))}function xr(e){return Object.prototype.toString.call(e)===`[object Object]`}function Sr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Cr(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(!Cr(e[r],t[r],n))return!1;return!0}if(br(e)&&br(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Cr(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||!Cr(e[o],t[o],n)))return!1;return i===a}return!1}var Kne=/[\x00-\x1f\x7f"<>`{}]/g;function qne(e){return e.replace(Kne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function wr(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 qne(t)}var Jne=[`http:`,`https:`,`mailto:`,`tel:`];function Yne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Xne(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+=wr(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=wr(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Zne(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Qne(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 Tr(){throw Error(`Invariant failed`)}var F=t(hee(),1),Er=F.createContext(null);function Dr(e){return F.useContext(Er)}var Or=F.createContext(void 0),$ne=F.createContext(void 0),ere=yte();function tre(e,t){return e===t}function kr(e,t,n=tre){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,ere.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Ar={};function jr(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=vr(n.current,i):i}}function Mr(e){let t=Dr(),n=F.useContext(e.from?$ne:Or),r=e.from??n,i=t.stores.getMatchStore(r),a=jr(e,t),o=kr(i,e=>e?a(e):Ar);if(o!==Ar)return o;(e.shouldThrow??!0)&&Tr()}function nre(e){return Mr({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 Nr=fee(),Pr=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Fr=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(){}},Ir=new class extends Fr{#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`}},rre={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Lr=new class{#e=rre;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 ire(e){setTimeout(e,0)}var are=typeof window>`u`||`Deno`in globalThis;function Rr(){}function ore(e,t){return typeof e==`function`?e(t):e}function zr(e){return typeof e==`number`&&e>=0&&e!==1/0}function Br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Vr(e,t){return typeof e==`function`?e(t):e}function Hr(e,t){return typeof e==`function`?e(t):e}function sre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Ur(o,t.options))return!1}else if(!Gr(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 cre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Wr(t.options.mutationKey)!==Wr(a))return!1}else if(!Gr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ur(e,t){return(t?.queryKeyHashFn||Wr)(e)}function Wr(e){return JSON.stringify(e,(e,t)=>Yr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Gr(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(!Gr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Gr(e[r],t[r]))return!1;return!0}return!1}var lre=Object.prototype.hasOwnProperty;function Kr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Jr(e)&&Jr(t);if(!r&&!(Yr(e)&&Yr(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:lre.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Kr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function qr(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 Jr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Yr(e){if(!Xr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Xr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Xr(e){return Object.prototype.toString.call(e)===`[object Object]`}function ure(e){return new Promise(t=>{Lr.setTimeout(t,e)})}function Zr(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Kr(e,t)}function dre(e){return e}function fre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function pre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Qr=Symbol();function $r(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Qr?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ei(e,t){return typeof e==`function`?e(...t):!!e}function mre(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 ti=(()=>{let e=()=>are;return{isServer(){return e()},setIsServer(t){e=t}}})();function ni(){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 hre=ire;function gre(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=hre,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 ri=gre(),ii=new class extends Fr{#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 _re(e){return Math.min(1e3*2**e,3e4)}function ai(e){return(e??`online`)!==`online`||ii.isOnline()}var oi=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function si(e){let t=!1,n=0,r,i=ni(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new oi(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Ir.isFocused()&&(e.networkMode===`always`||ii.isOnline())&&e.canRun(),u=()=>ai(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??(ti.isServer()?0:3),o=e.retryDelay??_re,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),ure(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 ci=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),zr(this.gcTime)&&(this.#e=Lr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ti.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Lr.clearTimeout(this.#e),this.#e=void 0)}};function vre(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=>{mre(e,()=>t.signal,()=>n=!0)},u=$r(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?pre:fre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?ui:li,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:li(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 li(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 ui(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function yre(e,t){return t?li(e,t)!=null:!1}function bre(e,t){return!t||!e.getPreviousPageParam?!1:ui(e,t)!=null}var xre=class extends ci{#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=pi(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=pi(this.options);e.data!==void 0&&(this.setState(fi(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Zr(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(Rr).catch(Rr):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=>Hr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qr||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Vr(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:!Br(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=$r(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`?vre(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=si({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof oi&&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 oi){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,...di(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...fi(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),ri.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function di(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ai(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function fi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function pi(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 mi=class extends Fr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ni(),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),hi(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return gi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return gi(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 Hr(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&&!qr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&_i(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Hr(this.options.enabled,this.#t)!==Hr(t.enabled,this.#t)||Vr(this.options.staleTime,this.#t)!==Vr(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Hr(this.options.enabled,this.#t)!==Hr(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 Cre(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(Rr)),t}#g(){this.#b();let e=Vr(this.options.staleTime,this.#t);if(ti.isServer()||this.#r.isStale||!zr(e))return;let t=Br(this.#r.dataUpdatedAt,e)+1;this.#d=Lr.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,!(ti.isServer()||Hr(this.options.enabled,this.#t)===!1||!zr(this.#p)||this.#p===0)&&(this.#f=Lr.setInterval(()=>{(this.options.refetchIntervalInBackground||Ir.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Lr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Lr.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&&hi(e,t),o=i&&_i(e,n,t,r);(a||o)&&(l={...l,...di(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=Zr(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=Zr(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:vi(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Hr(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=ni();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),!qr(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){ri.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Sre(e,t){return Hr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Hr(t.retryOnMount,e)!==!1)}function hi(e,t){return Sre(e,t)||e.state.data!==void 0&&gi(e,t,t.refetchOnMount)}function gi(e,t,n){if(Hr(t.enabled,e)!==!1&&Vr(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&vi(e,t)}return!1}function _i(e,t,n,r){return(e!==t||Hr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&vi(e,n)}function vi(e,t){return Hr(t.enabled,e)!==!1&&e.isStaleByTime(Vr(t.staleTime,e))}function Cre(e,t){return!qr(e.getCurrentResult(),t)}var yi=F.createContext(void 0),bi=e=>{let t=F.useContext(yi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},wre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Nr.jsx)(yi.Provider,{value:e,children:t})),xi=F.createContext(!1),Si=()=>F.useContext(xi);xi.Provider;function Tre(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ere=F.createContext(Tre()),Ci=()=>F.useContext(Ere),wi=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ei(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ti=e=>{F.useEffect(()=>{e.clearReset()},[e])},Ei=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ei(n,[e.error,r])),Di=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))}},Dre=(e,t)=>e.isLoading&&e.isFetching&&!t,Oi=(e,t)=>e?.suspense&&t.isPending,ki=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ai(e,t,n){let r=Si(),i=Ci(),a=bi(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,Di(o),wi(o,i,s),Ti(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(ri.batchCalls(e)):Rr;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Oi(o,d))throw ki(o,u,i);if(Ei({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&&!ti.isServer()&&Dre(d,r)&&(l?ki(o,u,i):s?.promise)?.catch(Rr).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function ji(e,t){return Ai(e,mi,t)}function Ore(e){return e}var kre={[Symbol.iterator](){return Are}},Are={next(){return{done:!0,value:void 0}}},jre=()=>kre,Mre=x,Mi=globalThis.Number,Nre=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=Mi(e);return Mi.isNaN(t)?Ee():T(t)},Pre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Ni=`~effect/http/HttpClientRequest`,Fre={[Ni]:Ni,...ke,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Jee(this.headers),body:this.body.toJSON()}},pipe(){return Ve(this,arguments)}};function Pi(e,t,n,r,i,a){let o=Object.create(Fre);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Ire=Pi(`GET`,``,$te,Ee(),Tn,Zte),Fi=e=>(t,n)=>Rre(Ire,{method:e,url:t,...n??void 0}),Lre=Fi(`POST`),Rre=w(2,(e,t)=>{let n=e;return t.method&&(n=zre(n,t.method)),t.url&&(n=Hre(n,t.url)),t.headers&&(n=Ii(n,t.headers)),t.urlParams&&(n=Ure(n,t.urlParams)),t.hash&&(n=Wre(n,t.hash)),t.body&&(n=Ri(n,t.body)),t.accept&&(n=Li(n,t.accept)),t.acceptJson&&(n=Vre(n)),n}),zre=w(2,(e,t)=>Pi(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Bre=w(3,(e,t,n)=>Pi(e.method,e.url,e.urlParams,e.hash,Yn(e.headers,t,n),e.body)),Ii=w(2,(e,t)=>Pi(e.method,e.url,e.urlParams,e.hash,Ite(e.headers,t),e.body)),Li=w(2,(e,t)=>Bre(e,`Accept`,t)),Vre=Li(`application/json`),Hre=w(2,(e,t)=>{if(typeof t==`string`)return Pi(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Hte(n.searchParams),i=dte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Pi(e.method,n.toString(),r,i,e.headers,e.body)}),Ure=w(2,(e,t)=>Pi(e.method,e.url,nne(e.urlParams,t),e.hash,e.headers,e.body)),Wre=w(2,(e,t)=>Pi(e.method,e.url,e.urlParams,T(t),e.headers,e.body)),Ri=w(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=mn(mn(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Yn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Yn(n,`content-length`,t.contentLength.toString()))),Pi(e.method,e.url,e.urlParams,e.hash,n,t)}),Gre=e=>Cn({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`}`}),zi=`~effect/http/HttpClient`,Bi=yt(`effect/HttpClient`),Vi=w(2,(e,t)=>Hi(n=>t(e.postprocess(n)),e.preprocess)),Kre=Vi(wt(Rte)),Hi=(e,t)=>{let n=Object.create(qre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},qre={[zi]:zi,pipe(){return Ve(this,arguments)},...ke,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Pre.map(([e,t])=>[t,function(t,n){return this.execute(Fi(e)(t,n))}]))},Jre=e=>Hi(t=>wt(t,t=>Pt(n=>{let i=Qre.get(t),a=i??new AbortController,o=Ete(t.url,t.urlParams,y(t.hash));if(qee(o))return r(new Zn({reason:new vne({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Uee)||n.getRef(Ui)(t)){let r=e(t,s,a.signal,n);return i?r:Et(e=>Le(e(r),{onSuccess(e){return Gi.register(e,a),rt(new Ki(e,a))},onFailure(e){return xt(e)&&a.abort(),it(e)}}))}return ut(n.getRef(Xre)(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(kte),l=ln(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Wi)?Ii(t,Gre(r)):t,Et(o=>o(e(t,s,a.signal,n)).pipe(Rt(r,{captureStackTrace:!1}),Le({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=ln(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?rt(e):(Gi.register(e,a),rt(new Ki(e,a)))},onFailure(e){return!i&&xt(e)&&a.abort(),it(e)}})))})})),rt),Yre=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 Vi(e,ie(r===`errors-only`?me:oe({schedule:o,times:s,while:Ji}),r===`response-only`?me:_e({while:n||t.while===void 0?qi:a(qi,t.while),schedule:i,times:s})))}),Ui=$e(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Vee}),Wi=$e(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:ye}),Xre=$e(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Zre=e=>ht(Bi)(se(t=>Ze(e,e=>Vi(e,bt(e=>st(t,e)))))),Gi=(()=>{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))}}})(),Qre=new WeakMap,Ki=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[pn]=pn;[ar]=ar;applyInterrupt(e){return At(()=>(Gi.unregister(this.original),vt(e,()=>pt(()=>{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(()=>(Gi.unregister(this.original),Qee(this.original.stream,pt(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[nt](){return this.original[nt]()}pipe(){return Ve(this,arguments)}},qi=e=>Mee(e)||$re(e),$re=e=>kn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Ji(e.reason.response)),Ji=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Yi=`~effect/FiberSet`,eie=e=>Ye(e,Yi),tie={[Yi]:Yi,[Symbol.iterator](){return this.state._tag===`Closed`?jre():this.state.backing[Symbol.iterator]()},...Ke,toJSON(){return{_id:`FiberMap`,state:this.state}}},nie=(e,t)=>{let n=Object.create(tie);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},rie=()=>je(pt(()=>nie(new Set,qe())),e=>At(()=>{let t=e.state;if(t._tag===`Closed`)return ct;e.state={_tag:`Closed`};let n=t.backing;return C(n).pipe(ce(e.deferred))})),Xi=-1,iie=ge(D(Iee,ae(Xi))),aie=w(e=>eie(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Xi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),Ct(r)&&(n?.propagateInterruption===!0?!iie(r.cause):!dt(r.cause))&&kt(e.deferred,r))}))}),oie=function(){let e;return()=>(e===void 0&&(e=f(St)),e)}(),sie=e=>()=>Ze(Ot(),t=>{let n=We(t);return(t,r)=>{if(e.state._tag===`Closed`)return oie();let i=n(t,r);return aie(e,i),i}}),Zi=e=>de(e.deferred),Qi=`~effect/socket/Socket`,$i=yt(`effect/socket/Socket`),cie=`~effect/socket/Socket/CloseEvent`,lie=e=>Ye(e,cie),ea=`~effect/socket/Socket/SocketError`,uie=e=>Ye(e,ea),ta=class extends Wn(`effect/socket/Socket/SocketReadError`)({_tag:fn(`SocketReadError`),cause:Nn}){message=`An error occurred during Read`},die=class extends Wn(`effect/socket/Socket/SocketWriteError`)({_tag:fn(`SocketWriteError`),cause:Nn}){message=`An error occurred during Write`},na=class extends Wn(`effect/socket/Socket/SocketOpenError`)({_tag:fn(`SocketOpenError`),kind:Fn([`Unknown`,`Timeout`]),cause:Nn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},ra=class extends Wn(`effect/socket/Socket/SocketCloseError`)({_tag:fn(`SocketCloseError`),code:Ln,closeReason:yn(j)}){static filterClean(e){return function(t){return aa.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?rte(t.reason):Lee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},ia=ir([ta,die,na,ra]),aa=class extends xne(ea)(`SocketError`,{_tag:fn(`SocketError`),reason:ia}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[ea]=ea;static is(e){return uie(e)}message=this.reason.message},fie=e=>!0,pie=class extends yt()(`~effect/socket/Socket/WebSocket`){},oa=class extends yt()(`@effect/platform/Socket/WebSocketConstructor`){},mie=(e,t)=>oa.use(n=>hie(je((typeof e==`string`?rt(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>pt(()=>e.close(1e3))),t)),hie=(e,t)=>Pt(n=>{let i,a=mt(!1),o=n.context,s=t?.closeCodeIsError??fie,c=(n,c)=>Tee(Xe(function*(o){let l=yield*rie().pipe(te(o)),u=yield*te(e,o),d=yield*Oe(sie(l)(),pie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=wt(gt(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return lt(t)?t:ct});return d(t)}let t=n(e.data);lt(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),kt(l.deferred,r(new aa({reason:f?new ta({cause:e}):new na({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),kt(l.deferred,r(new aa({reason:new ra({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,kt(e,ct)},{once:!0}),yield*de(e).pipe(Mt({duration:t?.openTimeout??1e4,orElse:()=>r(new aa({reason:new na({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),ee(Zi(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ue(Zi(l),ra.filterClean(e=>!s(e)),()=>ct)})).pipe(bt(e=>st(o,e)),Je(pt(()=>{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(pt(()=>{let t=i;lie(e)?t.close(e.code,e.reason):t.send(e)})));return rt($i.of({[Qi]:Qi,run:u,runRaw:c,writer:d}))}),sa=ie(mie,ht($i)),ca=class extends yt()(`effect/workers/Transferable/Collector`){},gie=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ca.of({addAllUnsafe:t,addAll:e=>pt(()=>t(e)),readUnsafe:n,read:pt(n),clearUnsafe:r,clear:pt(r)})},_ie=`~effect/workers/WorkerError`,vie=class extends Wn(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:fn(`WorkerSpawnError`),message:j,cause:yn(Nn)}){},yie=class extends Wn(`effect/workers/WorkerError/WorkerSendError`)({_tag:fn(`WorkerSendError`),message:j,cause:yn(Nn)}){},bie=class extends Wn(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:fn(`WorkerReceiveError`),message:j,cause:yn(Nn)}){},xie=class extends Wn(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:fn(`WorkerUnknownError`),message:j,cause:yn(Nn)}){},la=ir([vie,yie,bie,xie]);Wn(_ie)({_tag:fn(`WorkerError`),reason:la});var ua=`~effect/rpc/RpcClientError`,da=class extends Wn(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:fn(`RpcClientDefect`),message:j,cause:Nn}){},fa=class extends Wn(ua)({_tag:fn(`RpcClientError`),reason:ir([la,ia,fne,da])}){[ua]=ua;get message(){return`${this.reason._tag}: ${this.reason.message}`}},pa=e=>typeof e==`bigint`?e:BigInt(e),Sie={_tag:`Ping`},ma;try{ma=new TextDecoder}catch{}var I,ha,L=0,ga=[],_a=ga,va=0,ya={},ba,xa,Sa=0,Ca=0,wa,Ta,Ea=[],Da,Oa={useRecords:!1,mapsAsObjects:!0},ka=class{},Aa=new ka;Aa.name=`MessagePack 0xC1`;var ja=!1,Ma=2,Na,Pa,Fa;try{Function(``)}catch{Ma=1/0}var Ia=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 ao(()=>(oo(),this?this.unpack(t,n):e.prototype.unpack.call(Oa,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(ha=n.end||t.length,L=n.start||0):(L=0,ha=n>-1?n:t.length),va=0,Ca=0,xa=null,_a=ga,wa=null,I=t;try{Da=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(ya=this,this.structures)return ba=this.structures,La(n);(!ba||ba.length>0)&&(ba=[])}else ya=Oa,(!ba||ba.length>0)&&(ba=[]);return La(n)}unpackMultiple(e,t){let n,r=0;try{ja=!0;let i=e.length,a=this?this.unpack(e,i):co.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(La(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(La());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{ja=!1,oo()}}_mergeStructures(e,t){Pa&&(e=Pa.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 La(e){try{if(!ya.trusted&&!ja){let e=ba.sharedLength||0;e<ba.length&&(ba.length=e)}let t;if(ya.randomAccessStructure&&I[L]<64&&I[L]>=32&&Na?(t=Na(I,L,ha,ya),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=ha):t=za(),wa&&=(L=wa.postBundlePosition,null),ja&&(ba.restoreStructures=null),L==ha)ba&&ba.restoreStructures&&Ra(),ba=null,I=null,Ta&&=null;else if(L>ha)throw Error(`Unexpected end of MessagePack data`);else if(!ja){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 ba&&ba.restoreStructures&&Ra(),oo(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>ha)&&(e.incomplete=!0),e}}function Ra(){for(let e in ba.restoreStructures)ba[e]=ba.restoreStructures[e];ba.restoreStructures=null}function za(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=ba[e&63]||ya.getStructures&&Ha()[e&63];return t?(t.read||=Ba(t,e&63),t.read()):e}}else if(e<144){if(e-=128,ya.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=eo();e===`__proto__`&&(e=`__proto_`),t[e]=za()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(za(),za());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=za();return ya.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Ca>=L)return xa.slice(L-Sa,(L+=t)-Sa);if(Ca==0&&ha<140){let e=t<16?Ya(t):Ja(t);if(e!=null)return e}return Ua(t)}{let t;switch(e){case 192:return null;case 193:return wa?(t=za(),t>0?wa[1].slice(wa.position1,wa.position1+=t):wa[0].slice(wa.position0,wa.position0-=t)):Aa;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return Za(t);case 197:return t=Da.getUint16(L),L+=2,Za(t);case 198:return t=Da.getUint32(L),L+=4,Za(t);case 199:return Qa(I[L++]);case 200:return t=Da.getUint16(L),L+=2,Qa(t);case 201:return t=Da.getUint32(L),L+=4,Qa(t);case 202:if(t=Da.getFloat32(L),ya.useFloat32>2){let e=so[(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=Da.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=Da.getUint16(L),L+=2,t;case 206:return t=Da.getUint32(L),L+=4,t;case 207:return ya.int64AsType===`number`?(t=Da.getUint32(L)*4294967296,t+=Da.getUint32(L+4)):ya.int64AsType===`string`?t=Da.getBigUint64(L).toString():ya.int64AsType===`auto`?(t=Da.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Da.getBigUint64(L),L+=8,t;case 208:return Da.getInt8(L++);case 209:return t=Da.getInt16(L),L+=2,t;case 210:return t=Da.getInt32(L),L+=4,t;case 211:return ya.int64AsType===`number`?(t=Da.getInt32(L)*4294967296,t+=Da.getUint32(L+4)):ya.int64AsType===`string`?t=Da.getBigInt64(L).toString():ya.int64AsType===`auto`?(t=Da.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Da.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return no(I[L++]&63);{let e=Ea[t];if(e)return e.read?(L++,e.read(za())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,no(I[L++]&63,I[L++])):Qa(2);case 214:return Qa(4);case 215:return Qa(8);case 216:return Qa(16);case 217:return t=I[L++],Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):wie(t);case 218:return t=Da.getUint16(L),L+=2,Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):Tie(t);case 219:return t=Da.getUint32(L),L+=4,Ca>=L?xa.slice(L-Sa,(L+=t)-Sa):Eie(t);case 220:return t=Da.getUint16(L),L+=2,Ga(t);case 221:return t=Da.getUint32(L),L+=4,Ga(t);case 222:return t=Da.getUint16(L),L+=2,Ka(t);case 223:return t=Da.getUint32(L),L+=4,Ka(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 Cie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ba(e,t){function n(){if(n.count++>Ma){let n=e.read=Function(`r`,`return function(){return `+(ya.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:Cie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(za);return e.highByte===0&&(e.read=Va(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]=za()}return ya.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Va(t,n):n}var Va=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=ba[r]||Ha()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=Ba(i,e),i.read()};function Ha(){let e=ao(()=>(I=null,ya.getStructures()));return ba=ya._mergeStructures(e,ba)}var Ua=Wa,wie=Wa,Tie=Wa,Eie=Wa;function Wa(e){let t;if(e<16&&(t=Ya(e)))return t;if(e>64&&ma)return ma.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+=qa.apply(String,r),r.length=0)}return r.length>0&&(t+=qa.apply(String,r)),t}function Ga(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=za();return ya.freezeData?Object.freeze(t):t}function Ka(e){if(ya.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=eo();e===`__proto__`&&(e=`__proto_`),t[e]=za()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(za(),za());return t}}var qa=String.fromCharCode;function Ja(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 qa.apply(String,n)}function Ya(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return qa(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return qa(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return qa(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 qa(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return qa(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 qa(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return qa(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 qa(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return qa(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 qa(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return qa(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 qa(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return qa(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 qa(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 qa(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Xa(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=Da.getUint16(L),L+=2;break;case 219:t=Da.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Wa(t)}function Za(e){return ya.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function Qa(e){let t=I[L++];if(Ea[t]){let n;return Ea[t](I.subarray(L,n=L+=e),e=>{L=e;try{return za()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var $a=Array(4096);function eo(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Ca>=L)return xa.slice(L-Sa,(L+=e)-Sa);if(!(Ca==0&&ha<180))return Ua(e)}else return L--,to(za());let t=(e<<5^(e>1?Da.getUint16(L):e>0?I[L]:0))&4095,n=$a[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=Da.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=[],$a[t]=n,n.bytes=e;r<i;)a=Da.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Ya(e):Ja(e);return s==null?n.string=Ua(e):n.string=s}function to(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(ya.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 no=(e,t)=>{let n=za().map(to),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=ba[e];return i&&(i.isShared||ja)&&((ba.restoreStructures||(ba.restoreStructures=[]))[e]=i),ba[e]=n,n.read=Ba(n,r),n.read()};Ea[0]=()=>{},Ea[0].noBuffer=!0,Ea[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 ro={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Ea[101]=()=>{let e=za();if(!ro[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return ro[e[0]](e[1],{cause:e[2]})},Ea[105]=e=>{if(ya.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Da.getUint32(L-4);Ta||=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};Ta.set(t,i);let a=za();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},Ea[112]=e=>{if(ya.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=Da.getUint32(L-4),n=Ta.get(t);return n.used=!0,n.target},Ea[115]=()=>new Set(za());var io=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Die=typeof globalThis==`object`?globalThis:window;Ea[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=io[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 Die[r](n)},Ea[120]=()=>{let e=za();return new RegExp(e[0],e[1])};var Oie=[];Ea[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,wa=Oie,wa=[Xa(),Xa()],wa.position0=0,wa.position1=0,wa.postBundlePosition=L,L=n,za()},Ea[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 ao(e){Fa&&Fa();let t=ha,n=L,r=va,i=Sa,a=Ca,o=xa,s=_a,c=Ta,l=wa,u=new Uint8Array(I.slice(0,ha)),d=ba,f=ba.slice(0,ba.length),p=ya,m=ja,h=e();return ha=t,L=n,va=r,Sa=i,Ca=a,xa=o,_a=s,Ta=c,wa=l,I=u,ja=m,ba=d,ba.splice(0,ba.length,...f),ya=p,Da=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function oo(){I=null,Ta=null,ba=null}var so=Array(147);for(let e=0;e<256;e++)so[e]=+(`1e`+Math.floor(45.15-e*.30103));var co=new Ia({useRecords:!1});co.unpack,co.unpackMultiple,co.unpack;var kie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var lo;try{lo=new TextEncoder}catch{}var uo,fo,po=typeof Buffer<`u`,mo=po?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,ho=po?Buffer:Uint8Array,go=po?4294967296:2144337920,R,_o,vo,z=0,yo,bo=null,Aie,jie=21760,Mie=/[\u0080-\uFFFF]/,xo=Symbol(`record-id`),Nie=class extends Ia{constructor(e){super(e),this.offset=0;let t,n,r,i,a=ho.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:lo&&lo.encodeInto?function(e,t){return lo.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 mo(8192),vo=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),yo=R.length-10,yo-z<2048?(R=new mo(R.length),vo=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),yo=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`?(bo=[],bo.size=1/0):bo=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[xo]=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)&&!fo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=bo;if(bo&&To(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&&(vo.setUint32(n.position+t,vo.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&vo.setUint32(n.position+t,vo.getUint32(n.position+t)+a),z+=e.length*6,z>yo&&w(z),o.offset=z;let s=Pie(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=Fie(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][xo]=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,vo.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>yo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(bo&&n>=4&&n<4096){if((bo.size+=n)>jie){let e,n=(bo[0]?bo[0].length*3+bo[1].length:0)+10;z+n>yo&&(R=w(z+n));let r;bo.position?(r=bo,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,To(t,y,0),vo.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),bo=[``,``],bo.previous=r,bo.size=0,bo.position=e}let r=Mie.test(e);bo[+!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>yo&&(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,vo.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,vo.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,vo.setInt16(z,e),z+=2):(R[z++]=210,vo.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,vo.setFloat32(z,e);let n;if(t<4||(n=e*so[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,vo.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,vo.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,vo.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=uo.length;t<n;t++){let n=fo[t];if(e instanceof n){let n=uo[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=vo,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>yo&&w(z),{target:R,targetView:vo,position:z-e}),y)}finally{r&&(R=r,vo=i,z=a,yo=R.length-10)}o&&(o.length+z>yo&&w(o.length+z),z=wo(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,vo.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,vo.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,vo.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),po)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>yo&&w(n.length+z),z=wo(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,vo.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[xo];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[xo];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>go)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(go,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 mo(n);return vo=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,yo=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[xo]=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()[xo]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=yo,c=t;R=_o,z=0,t=0,R||(_o=R=new mo(8192)),yo=R.length-10,T(e,n,i),_o=R;let l=z;if(R=a,z=o,yo=s,t=c,l>1){let e=z+l-1;e>yo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(_o.slice(0,l),n),z=e}else R[r+t]=_o[0]},D=e=>{let i=Aie(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:vo,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)),vo=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};fo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ka],uo=[{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?So(e,16,t):Co(po?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==ho&&this.moreTypes?So(e,io.indexOf(n.name),t):Co(e,t)}},{pack(e,t){this.moreTypes?So(e,17,t):Co(po?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function So(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 Co(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 wo(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 Pie(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 To(e,t,n){if(bo.length>0){vo.setUint32(bo.position+e,z+n-bo.position-e),bo.stringsPosition=z-e;let r=bo;bo=null,t(r[0]),t(r[1])}}function Fie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var Eo=new Nie({useRecords:!1});Eo.pack,Eo.pack;var{NEVER:Iie,ALWAYS:Lie,DECIMAL_ROUND:Rie,DECIMAL_FIT:zie}=kie,Do=class extends yt()(`effect/rpc/RpcSerialization`){},Bie=Do.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)}}}),Oo=he(Do)(Bie),Vie=e=>At(()=>{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]),ct});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return ot(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(At(()=>i(e)),t)}return yield*iee(S,()=>(t.delete(e),r.delete(e),ct))})}}))}),Hie=BigInt(0),Uie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Hie++),o=yield*Ot(),s=at(o,Me),c=new Map,l=!1;yield*Bt(s,Pt(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`?Ft(n.queue):Pe(n.queue,e.cause):n.resume(e)}),f=e=>{let r=Mte(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?dn(s.headers):Tn,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):ut(`${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:ute(Ze(u,nte))}},m=(e,n,r,i,o,s,u)=>Pt(d=>{if(l)return St;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:En(d.getRef(jo),o)});if(u)return p;let m;return vt(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?Rt(r,{captureStackTrace:!1}):me,We(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),zt(aee(m),_(f,Array.from(e),s))))}),h=Xe(function*(e,r,o,s,d,f){if(l)return yield*St;let m=i?void 0:yield*mte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),h=Ce(),g=a(),v=Xee(h.context,Me);yield*u(v,e=>c.has(g)?(c.delete(g),_(g,Ct(e)?Array.from(Oee(e.cause)):[],f)):ct);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:En(h.getRef(jo),s)}).pipe(m?Rt(m,{captureStackTrace:!1}):me,Ge(e=>Pe(y,e)),ft,Nt(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(ct)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?ct:tee(i.queue,e.values).pipe(r?wt(()=>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),ct):e.exit._tag===`Success`?Ft(n.queue):Pe(n.queue,e.exit.cause)):ct}case`Defect`:return d(bee(e.defect));case`ClientEnd`:return ct}},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}}),Wie=0,ko=Xe(function*(e,t){let n=Wie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*Mo,s=new Map,{client:l,write:u}=yield*Uie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?gie():void 0,l=Ce(),u={rpc:r,context:a?ate(l.context,ca,a):l.context,schemas:Gie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Te(u.context),c,wt(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)}):ct;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):ct;case`Eof`:return ct}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=pa(e.requestId),n=s.get(t);return!n||g(n.schemas.decodeChunk)?ct:n.schemas.decodeChunk.value(e.values).pipe(Te(n.context),c,wt(t=>u({_tag:`Chunk`,clientId:0,requestId:pa(e.requestId),values:t})),v(t=>u({_tag:`Exit`,clientId:0,requestId:pa(e.requestId),exit:Ae(t)})))}case`Exit`:{let t=pa(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)})}))):ct}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Yie(e.defect)});case`ClientProtocolError`:{let t=wee(e.error);return jt(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return ct}}).pipe(Ge(ste),ft,tt),l}),Ao=new WeakMap,Gie=e=>{let t=Ao.get(e);if(t!==void 0)return t;let n=Vte(e.successSchema);return t={decodeChunk:be(n,e=>on(hn(hne(e.success)))),encodePayload:une(hn(e.payloadSchema)),decodeExit:on(hn(Bte(e)))},Ao.set(e,t),t},jo=$e(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Tn}),Mo=class extends yt()(`effect/rpc/RpcClient/Protocol`){static make=Vie},No=e=>Mo.make(Xe(function*(t,n){let i=yield*$i,a=yield*Do,o=yield*see(Jie),s=new Map,u=yield*i.writer,d=a.makeUnsafe(),f=yield*qie(u(d.encode(Sie))),p,m=At(()=>(p=void 0,_t(o)?o.value.onConnect:ct)),h=e=>jt(n,n=>t(n,e));return yield*At(()=>(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(),ct;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 fa({reason:new da({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(ee(wt(f.timeout,()=>r(new aa({reason:new na({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(wt(()=>r(new aa({reason:new ra({code:1e3})}))),_t(o)?Je(o.value.onDisconnect):me,Yee(t=>{let n=zee(t),r=$ee(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?ct:(p=new fa({reason:r?n.success.reason:new da({message:`Unknown socket error`,cause:Ie(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),_e(e?.retryPolicy??Kie),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?ct:c(u(n))},supportsAck:!0,supportsTransferables:!1}})),Kie=h(500,1.5).pipe(uee(ree(5e3))),qie=Xe(function*(e){let t=!0,n=0,r=mt();return yield*At(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(xee(`5 seconds`),Dt,et,ft,tt),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Jie=class extends yt()(`effect/rpc/RpcClient/ConnectionHooks`){},Yie=rr(Nn);function Po(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function Xie(e){return e?.target.wsBaseUrl??null}function Zie(e){return e?.target.httpBaseUrl??null}function Qie(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function $ie(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function eae(e){let t=$ie(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function tae(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 nae(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function rae(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Fo(e){let t=e.capabilities,n=t.runtime??eae(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??tae(n),tools:t.tools??nae(n),projects:t.projects??rae(t,n)}}function iae(e){return e?Fo(e).projects.cloudProjects:!1}function aae(e){return e?Fo(e).runtime.workspaceProxy??!1:!1}function Io(e,t){return{environmentId:e,projectId:t}}function Lo(e,t){return{environmentId:e,threadId:t}}var Ro=`scoped:v1:`;function zo(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Ro)?`${Ro}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Bo(e){return zo(e)}function Vo(e){return zo(e)}function oae(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 Ho(e){if(e.startsWith(Ro))return oae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Uo(e){let t=Ho(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Wo(e){let t=Ho(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var sae=1e3,cae=64e3;ko(Mn);function lae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(sae*2**e),cae)}var Go=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Ko(e){return Array.isArray(e)?e.map(Ko):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ko(t)])):e}function uae(e){let t=JSON.stringify(Ko(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var dae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function fae(e){return e._tag===`Ping`?dae:null}function pae(e){if(e.policy===null||e.policy.method!==e.method)throw new Go(`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 Go(`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 mae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new Go(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new Go(`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 Go(`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 Go(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var hae=[{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:qn.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:qn.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:qn.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:qn.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:qn.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:qn.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.getArchivedShellSnapshot,requiredScope:`thread.read`,deliveryClass:`read`},{method:qn.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:qn.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:qn.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`}],gae=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,qn.dispatchCommand]),_ae=hae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?gae.has(e.method)?`frame`:`metadata-only`:`none`}}),vae=mae({registeredMethods:[...Mn.requests.keys()],policies:_ae}),qo={"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`}},yae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function bae(e){if(e.method!==qn.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!yae.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 Go(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Jo(e){let t=vae.get(e.method)??null,n=pae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==qn.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new Go(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in qo))throw new Go(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=qo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new Go(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Yo=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},Xo=class extends Yo{},Zo=class extends Yo{},Qo=class extends Yo{},xae=class extends Yo{},Sae=class extends Yo{},Cae=class extends Yo{},wae=class extends Yo{},Tae=class extends Yo{},Eae=class extends Yo{},Dae=class extends Yo{},$o=class extends Yo{},es=Oae(globalThis,{});function Oae(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 kae(){if(es!==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 $o(e)}}var ts=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await kae())}},ns={Base:0,Psk:1,Auth:2,AuthPsk:3},Aae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},rs={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},is={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},as=new Uint8Array,os=0n,ss=1n,cs=2n,jae=new Uint8Array([75,69,77,0,0]),ls=new Uint8Array([72,80,75,69,45,118,49]);function us(e){return new Uint8Array(ds(e))}function ds(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 Mae=class extends ts{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:rs.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:as}),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(ls,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(ls,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):ds(e);if(n.byteLength!==this.hashSize)throw new Xo(`The salt length must be the same as the hashSize`);let r=ds(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=ds(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=as,c=us(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=ds(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:ds(e),info:ds(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===as)throw Error(`Not initialized. Call init()`)}},Nae=class extends Mae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:rs.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}})}},fs=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function ps(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 ms(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function hs(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 Pae(){if(es!==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 Fae(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 Iae=new Uint8Array([101,97,101,95,112,114,107]),Lae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Rae(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 zae=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(jae);r.set(ps(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(ds(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(ds(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=ds(e);if(t.byteLength>8192)throw new Xo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():fs(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=fs(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=ms(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=ms(new Uint8Array(n),new Uint8Array(r));else{let t=fs(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Rae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new xae(e)}}async decap(e){let t=ds(e.enc),n=await this._prim.deserializePublicKey(t),r=fs(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=fs(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)):ms(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=ms(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 Sae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(Iae,e),r=this._kdf.buildLabeledInfo(Lae,t,this.secretSize);return await this._kdf.extractAndExpand(as,n,r,this.secretSize)}},gs=[`deriveBits`],Bae=new Uint8Array([100,107,112,95,112,114,107]),Vae=new Uint8Array([115,107]),_s=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=[])}},Hae=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 Zo(e))}}async deserializePublicKey(e){try{return await this._importRawKey(ds(e),!0)}catch(e){throw new Qo(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new Zo(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(ds(e),!1)}catch(e){throw new Qo(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 Qo(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new _s(this._algName,e,`private`,gs);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new $o(e)}}async deriveKeyPair(e){try{let t=ds(e),n=await this._hkdf.labeledExtract(as.buffer,Bae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Vae,as,this._nSk),i=new _s(this._algName,new Uint8Array(r),`private`,gs);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Dae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new _s(this._algName,t,`public`))}catch(e){return Promise.reject(new Qo(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new Zo(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 _s(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:gs))})}_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 _s(this._algName,hs(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new _s(this._algName,hs(e.d),`private`,gs)))})}};function Uae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function vs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function ys(e,t,n=``){let r=Uae(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 bs(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 xs(e,t){ys(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function Wae(e){if(typeof e==`bigint`){if(!Ms(e))throw Error(`positive bigint expected, got `+e)}else vs(e);return e}function Ss(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Cs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Gae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ws(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ts(e,t){return e<<32-t|e>>>t}var Es=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Kae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),qae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Jae(e){if(ys(e),Es)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Kae[e[n]];return t}var Ds={_0:48,_9:57,A:65,F:70,a:97,f:102};function Os(e){if(e>=Ds._0&&e<=Ds._9)return e-Ds._0;if(e>=Ds.A&&e<=Ds.F)return e-(Ds.A-10);if(e>=Ds.a&&e<=Ds.f)return e-(Ds.a-10)}function Yae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Es)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=Os(e.charCodeAt(i)),a=Os(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 Xae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=os;for(let n=0;n<e.length;n++){let r=Os(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|qae[r]}return t}function ks(e){vs(e,`numberToBigint`);let t=e,n=os,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function As(e){return Xae(Jae(js(ys(e)).reverse()))}function Zae(e,t){vs(t),e=Wae(e);let n=Yae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function Qae(e,t){return Zae(e,t).reverse()}function js(e){return Uint8Array.from(e)}function Ms(e){return typeof e==`bigint`&&0n<=e}function $ae(e,t,n){return Ms(e)&&Ms(t)&&Ms(n)&&t<=e&&e<n}function Ns(e,t,n,r){if(!$ae(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function eoe(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 toe(e=32){let t=await Pae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function noe(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function roe(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);vs(e.outputLen),vs(e.blockLen)}function ioe(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 Ps=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}),roe(e),ys(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),Cs(r)}update(e){return bs(this),this.iHash.update(e),this}digestInto(e){bs(this),ys(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()}},Fs=(e,t,n)=>new Ps(e,t).update(n).digest();Fs.create=(e,t)=>new Ps(e,t);function aoe(e,t,n){return e&t^~e&n}function ooe(e,t,n){return e&t^e&n^t&n}var soe=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=ws(this.buffer)}update(e){bs(this),ys(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=ws(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){bs(this),xs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Cs(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,ks(this.length*8),i),this.process(n,0);let o=ws(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()}},Is=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),coe=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]),Ls=new Uint32Array(64),loe=class extends soe{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)Ls[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ls[e-15],n=Ls[e-2],r=Ts(t,7)^Ts(t,18)^t>>>3,i=Ts(n,17)^Ts(n,19)^n>>>10;Ls[e]=i+Ls[e-7]+r+Ls[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=Ts(o,6)^Ts(o,11)^Ts(o,25),u=l+t+aoe(o,s,c)+coe[e]+Ls[e]|0,d=(Ts(n,2)^Ts(n,13)^Ts(n,22))+ooe(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(){Cs(Ls)}destroy(){this.set(0,0,0,0,0,0,0,0),Cs(this.buffer)}},uoe=class extends loe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Is[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Is[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Is[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Is[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Is[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Is[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Is[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Is[7]|0})}},Rs=ioe(()=>new uoe,noe(1));function zs(e,t){let n=e%t;return n>=0n?n:t+n}function Bs(e,t,n){let r=e;for(;t-->os;)r*=r,r%=n;return r}function doe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function foe(e){return eoe(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function poe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=foe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||toe,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?cs**254n:cs**447n,p=f+(o?8n*cs**251n-ss:4n*cs**445n-ss)+ss,m=e=>zs(e,t),h=g(u);function g(e){return Qae(m(e),l)}function _(e){let t=js(ys(e,l,`uCoordinate`));return o&&(t[31]&=127),m(As(t))}function v(e){return As(r(js(ys(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){Ns(`u`,e,os,t),Ns(`scalar`,n,f,p);let r=n,a=e,o=ss,s=os,l=e,u=ss,h=os;for(let e=c-1n;e>=os;e--){let t=r>>e&ss;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)),ys(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:doe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Vs(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var moe=(e,t)=>{function n(n,...r){if(ys(n,void 0,`key`),!Gae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];ys(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&ys(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`);ys(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,ys(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(ys(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 hoe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function goe(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 Hs(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&&!voe(t))throw Error(`invalid output, must be aligned`);return t}function _oe(e,t,n){Vs(n);let r=new Uint8Array(16),i=ws(r);return i.setBigUint64(0,ks(t),n),i.setBigUint64(8,ks(e),n),r}function voe(e){return e.byteOffset%4==0}var Us=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),yoe=Us(`expand 16-byte k`),boe=Us(`expand 32-byte k`),xoe=Ss(yoe),Soe=Ss(boe);function Ws(e,t){return e<<t|e>>>32-t}function Gs(e){return e.byteOffset%4==0}var Ks=64,Coe=16,qs=2**32-1,Js=Uint32Array.of();function woe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Ks),u=Ss(l),d=Gs(i)&&Gs(a),f=d?Ss(i):Js,p=d?Ss(a):Js;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=qs)throw Error(`arx: counter overflow`);let h=Math.min(Ks,c-m);if(d&&h===Ks){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Coe;t++)n=e+t,p[n]=f[n]^u[t];m+=Ks;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function Toe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=hoe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return vs(i),vs(o),Vs(a),Vs(n),(t,s,c,l,u=0)=>{ys(t,void 0,`key`),ys(s,void 0,`nonce`),ys(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),ys(l,void 0,`output`),vs(u),u<0||u>=qs)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=js(t)),h=Soe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=xoe,f.push(m);else throw ys(t,32,`arx key`),Error(`invalid key size`);Gs(s)||f.push(s=js(s));let g=Ss(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,Ss(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=Ss(s);return woe(e,h,g,v,c,l,u,o),Cs(...f),l}}function Ys(e,t){return e[t++]&255|(e[t++]&255)<<8}var Eoe=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=js(ys(e,32,`key`));let t=Ys(e,0),n=Ys(e,2),r=Ys(e,4),i=Ys(e,6),a=Ys(e,8),o=Ys(e,10),s=Ys(e,12),c=Ys(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]=Ys(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=Ys(e,t+0),_=Ys(e,t+2),v=Ys(e,t+4),y=Ys(e,t+6),b=Ys(e,t+8),x=Ys(e,t+10),S=Ys(e,t+12),C=Ys(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;Cs(n)}update(e){bs(this),ys(e),e=js(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(){Cs(this.h,this.r,this.buffer,this.pad)}digestInto(e){bs(this),xs(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 Doe(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 Ooe=Doe(e=>new Eoe(e));function koe(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=Ws(A^S,16),ne=ne+A|0,E=Ws(E^ne,12),S=S+E|0,A=Ws(A^S,8),ne=ne+A|0,E=Ws(E^ne,7),C=C+D|0,ie=Ws(ie^C,16),O=O+ie|0,D=Ws(D^O,12),C=C+D|0,ie=Ws(ie^C,8),O=O+ie|0,D=Ws(D^O,7),w=w+ee|0,ae=Ws(ae^w,16),k=k+ae|0,ee=Ws(ee^k,12),w=w+ee|0,ae=Ws(ae^w,8),k=k+ae|0,ee=Ws(ee^k,7),T=T+te|0,oe=Ws(oe^T,16),re=re+oe|0,te=Ws(te^re,12),T=T+te|0,oe=Ws(oe^T,8),re=re+oe|0,te=Ws(te^re,7),S=S+D|0,oe=Ws(oe^S,16),k=k+oe|0,D=Ws(D^k,12),S=S+D|0,oe=Ws(oe^S,8),k=k+oe|0,D=Ws(D^k,7),C=C+ee|0,A=Ws(A^C,16),re=re+A|0,ee=Ws(ee^re,12),C=C+ee|0,A=Ws(A^C,8),re=re+A|0,ee=Ws(ee^re,7),w=w+te|0,ie=Ws(ie^w,16),ne=ne+ie|0,te=Ws(te^ne,12),w=w+te|0,ie=Ws(ie^w,8),ne=ne+ie|0,te=Ws(te^ne,7),T=T+E|0,ae=Ws(ae^T,16),O=O+ae|0,E=Ws(E^O,12),T=T+E|0,ae=Ws(ae^T,8),O=O+ae|0,E=Ws(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 Aoe=Toe(koe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),joe=new Uint8Array(16),Xs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(joe.subarray(n))},Moe=new Uint8Array(32);function Zs(e,t,n,r,i){i!==void 0&&ys(i,void 0,`AAD`);let a=e(t,n,Moe),o=_oe(r.length,i?i.length:0,!0),s=Ooe.create(a);i&&Xs(s,i),Xs(s,r),s.update(o);let c=s.digest();return Cs(a,o),c}var Qs=moe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=Hs(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Zs(e,t,n,s,r);return a.set(c,o),Cs(c),a},decrypt(i,a){a=Hs(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Zs(e,t,n,o,r);if(!goe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Cs(c),a}}))(Aoe)),Noe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(ds(e))}async seal(e,t,n){return await this._seal(ds(e),ds(t),ds(n))}async open(e,t,n){return await this._open(ds(e),ds(t),ds(n))}_seal(e,t,n){return new Promise(r=>{r(Qs(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(Qs(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},Poe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:is.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 Noe(e)}};function $s(){return new Promise((e,t)=>{t(new $o(`Not supported`))})}var Foe=new Uint8Array([115,101,99]),ec=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 $s()}async open(e,t){return await $s()}async export(e,t){let n=ds(e);if(n.byteLength>8192)throw new Xo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Foe,new Uint8Array(n),t)}catch(e){throw new Cae(e)}}},Ioe=class extends ec{},Loe=class extends ec{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}},tc=class extends ec{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=ps(e.seq,e.baseNonce.byteLength);return Fae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new Eae(`Message limit reached`);e.seq+=1}},Roe=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)},zoe=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,rc=class{constructor(){nc.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Roe(this,nc,`f`);return zoe(this,nc,t,`f`),await n,e}};nc=new WeakMap;var ic=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)},Boe=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},ac,Voe=class extends tc{constructor(){super(...arguments),ac.set(this,void 0)}async open(e,t=as.buffer){Boe(this,ac,ic(this,ac,`f`)??new rc,`f`);let n=await ic(this,ac,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),ds(e),ds(t))}catch(e){throw new Tae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};ac=new WeakMap;var oc=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},sc,Uoe=class extends tc{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),sc.set(this,void 0),this.enc=r}async seal(e,t=as.buffer){Hoe(this,sc,oc(this,sc,`f`)??new rc,`f`);let n=await oc(this,sc,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),ds(e),ds(t))}catch(e){throw new wae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};sc=new WeakMap;var Woe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Goe=new Uint8Array([101,120,112]),Koe=new Uint8Array([105,110,102,111,95,104,97,115,104]),qoe=new Uint8Array([107,101,121]),Joe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Yoe=new Uint8Array([115,101,99,114,101,116]),Xoe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Zoe=class extends ts{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 Xo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new Xo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new Xo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array(Xoe),this._suiteId.set(ps(this._kem.id,2),4),this._suiteId.set(ps(this._kdf.id,2),6),this._suiteId.set(ps(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?ns.Base:ns.Auth:e.senderKey===void 0?ns.Psk:ns.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?ns.Base:ns.Auth:e.senderPublicKey===void 0?ns.Psk:ns.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=as.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=as.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?as:us(n.psk.id),i=await this._kdf.labeledExtract(as,Joe,r),a=n.info===void 0?as:us(n.info),o=await this._kdf.labeledExtract(as,Koe,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?as:us(n.psk.key),l=this._kdf.buildLabeledIkm(Yoe,c),u=this._kdf.buildLabeledInfo(Goe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===is.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(qoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(Woe,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 Loe(this._api,this._kdf,i.exporterSecret,n):new Uoe(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 Ioe(this._api,this._kdf,r.exporterSecret):new Voe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new Xo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new Xo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new Xo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new Xo(`Too long psk.id`)}}},Qoe=class extends Zoe{},$oe=1n,cc=2n,ese=3n,tse=5n,lc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function nse(e){let t=10n,n=80n,r=lc,i=e*e%r*e%r,a=Bs(Bs(i,cc,r)*i%r,$oe,r)*e%r,o=Bs(a,tse,r)*a%r,s=Bs(o,t,r)*o%r,c=Bs(s,20n,r)*s%r,l=Bs(c,40n,r)*c%r;return{pow_p_5_8:Bs(Bs(Bs(Bs(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,cc,r)*e%r,b2:i}}function rse(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var ise=(()=>{let e=lc;return poe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=nse(t);return zs(Bs(n,ese,e)*r,e)},adjustScalarBytes:rse})})(),ase=class extends Hae{constructor(e){super(`X25519`,32,ise,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new Zo(e))}}},uc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,ose=2**31,sse=65536,cse=16,dc=32,fc=(1n<<255n)-19n,pc=new TextEncoder,mc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function hc(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 lse=new Set([0n,1n,hc(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),hc(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),fc-1n]),use=new Uint8Array,gc=class extends Nae{async extract(e,t){return ds(Fs(Rs,e.byteLength===0?new Uint8Array(this.hashSize):us(e),us(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=us(e),i=us(t),a=new Uint8Array(n),o=use;for(let e=1,t=0;t<a.byteLength;e+=1){let n=bc([o,i,Uint8Array.of(e)]);o=new Uint8Array(Fs(Rs,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 ds(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},_c=new Qoe({kem:new class extends zae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Aae.DhkemX25519HkdfSha256,new ase(e),e)}}(new gc),kdf:new gc,aead:new Poe}),vc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function yc(e){return new Uint8Array(e.slice(0))}function dse(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function bc(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 xc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new vc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function Sc(e){if(!Number.isSafeInteger(e)||e<0)throw new vc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function fse(e){return bc([xc(e.byteLength),e])}function Cc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function pse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function wc(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+=mc[o>>>18&63],t+=mc[o>>>12&63],n+1<e.byteLength&&(t+=mc[o>>>6&63]),n+2<e.byteLength&&(t+=mc[o&63])}return t}function Tc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new vc(`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=mc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(wc(t)!==e)throw new vc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function mse(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 lse.has(n%fc)}var hse={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new vc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return yc(await globalThis.crypto.subtle.digest(`SHA-256`,dse(e)))}},Ec={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new vc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function Dc(e,t){let n=pc.encode(e).byteLength;if(n===0||n>256)throw new vc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function gse(e){let t=pc.encode(e).byteLength;if(t===0||t>65536)throw new vc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${sse} UTF-8 bytes.`)}async function Oc(e,t=hse){gse(e.exactCompactTicket),Dc(e.channelId,`Channel ID`),Dc(e.runtimeId,`Runtime ID`),Sc(e.connectionEpoch);let n=await t.sha256(pc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new vc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function _se(e){return wc(e.ticketDigest)}async function vse(e=Ec){let t=new Uint8Array(await e.randomBytes(dc));if(t.byteLength!==dc)throw new vc(`endpoint_key_invalid`,`The endpoint random source must return ${dc} bytes.`);try{return wc(t)}finally{t.fill(0)}}function kc(e){return bc([pc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,Cc(e.direction)])}function Ac(e){return bc([pc.encode(`forge-relay`),xc(4),e.binding.ticketDigest,pc.encode(e.binding.channelId),Cc(e.binding.direction),pse(e.frameClass),Sc(e.sequence),pc.encode(e.binding.runtimeId),Sc(e.binding.connectionEpoch),xc(e.ciphertextLength)].map(fse))}async function yse(e=Ec){let t=new Uint8Array(await e.randomBytes(dc));if(t.byteLength!==dc)throw new vc(`endpoint_key_invalid`,`The endpoint random source must return ${dc} bytes.`);try{return await _c.kem.deriveKeyPair(t)}catch(e){throw new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function jc(e){try{return wc(yc(await _c.kem.serializePublicKey(e)))}catch(e){throw new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function bse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new vc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function xse(e){try{let t=Tc(e);if(t.byteLength!==dc)throw Error(`Invalid endpoint key length.`);if(mse(t))throw new vc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await _c.kem.deserializePublicKey(t)}catch(e){throw e instanceof vc?e:new vc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var Mc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Nc=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=ose||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new vc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function Sse(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 vc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var Cse=class{binding;context;encapsulatedKey;queue=new Mc;budget=new Nc;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=wc(yc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new vc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+cse;this.budget.assertAvailable(t);let n=this.sequence,r=Ac({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=yc(await this.context.seal(e.plaintext,r))}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new vc(`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:wc(i)}})}},wse=class{binding;context;queue=new Mc;budget=new Nc;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(Sse(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new vc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Tc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Ac({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=yc(await this.context.open(t,n))}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new vc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function Tse(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Ec).randomBytes(dc)),t.byteLength!==dc)throw Error(`The endpoint random source must return ${dc} bytes.`);let n=await _c.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:kc(e.binding),ekm:t});return new Cse(e.binding,n)}catch(e){throw new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function Ese(e){try{let t=await _c.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Tc(e.encapsulatedKey),info:kc(e.binding)});return new wse(e.binding,t)}catch(e){throw e instanceof vc?e:new vc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Dse=128,Ose=2097152,kse=864e5,Pc=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Fc(e){return typeof e==`string`&&e.length>0}function Ic(e){return Fc(e)&&Number.isFinite(Date.parse(e))}function Ase(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function jse(e){return Fc(e.transportRequestId)&&Fc(e.runtimeId)&&Fc(e.actorSessionId)&&Fc(e.durableRequestId)&&Fc(e.method)}function Mse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Nse(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Fc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function Pse(e){return!Ase(e.status)||e.errorCode!==null&&!Fc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Fc(e.errorCode):e.errorCode===null}function Fse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return jse(t)&&Mse(t)&&Nse(t)&&Pse(t)&&Ic(t.createdAt)&&Ic(t.updatedAt)}function Ise(e){try{return JSON.parse(e)}catch{throw new Pc(`Forge relay control journal is corrupt.`)}}function Lse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Fc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Fse)}function Rse(e){let t=new Set(e.map(Lc)),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 zse(e){let t=Ise(e);if(!Lse(t))throw new Pc(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Rse(n)||t.nextSequence<=r)throw new Pc(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Bse(){return crypto.randomUUID()}function Lc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Rc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Vse(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)=>Rc[t.status]>Rc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function zc(e){let t=e.randomUUID??Bse,n=e.now??(()=>new Date),r=e.maxRecords??Dse,i=e.maxBytes??Ose,a=e.maxReplayAgeMs??kse;if(r<1||i<1||a<1)throw new Pc(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?zse(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 Pc(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new Pc(`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=Lc(e);return{key:t,existing:c.records.find(e=>Lc(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 Pc(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new Pc(`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 Pc(`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 Pc(`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(Lc({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 Pc(`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(Lc({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 Pc(`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(Lc(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 Hse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Use=rn(dne),Wse=vn(mne),Gse=vn(ine),Kse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Bc(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 Vc(e,t){let n=JSON.parse(e),r=fae(n);if(r!==null)return{messageType:`request`,...r};let i=qse(n,t);if(i!==null)return i;let a=Jse(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function qse(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=Jo({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Bc(e.headers,$n.requestId)??e.id,method:e.tag,...n}}function Jse(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 Hc(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 Yse=new Set([`network`,`server`,`auth`,`permission`,`client`]),Xse=new Set([`network`,`server`]);function Zse(e){return e&&typeof e==`object`?e:{}}function Qse(e){return typeof e.code==`string`&&e.code.length>0?e.code:typeof e.kind==`string`&&Yse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function $se(e){if(e.retryable===!0||typeof e.kind==`string`&&Xse.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Uc(e){let t=Zse(e);return{code:Qse(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:$se(t)}}function Wc(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 ece(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values($n).includes(e[0])}function Gc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function tce(e){if(!Array.isArray(e))return null;for(let t of e){let e=Gc(t);if(e?._tag!==`Fail`)continue;let n=Gc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function nce(e){let t=Gc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:tce(t.cause)??`RELAY_RPC_FAILED`}function Kc(e){if(typeof e!=`string`)return null;try{let t=Use(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function rce(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 qc(e,t,n){if(typeof e==`string`)try{let r=Gc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=nce(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 ice(e){let t=Bc(e,$n.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function ace(e){return{issuedAt:Bc(e,$n.issuedAt)??new Date().toISOString(),expiresAt:Bc(e,$n.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function oce(e){if(e!==2&&e!==3&&e!==4)throw new Go(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function sce(e){let t=bae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=cce(e.context);if(e.acquire===void 0)throw new Go(`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 cce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new Go(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Jc(e.channelId),channelTicketDigest:Jc(e.channelTicketDigest),runtimeEndpointKeyId:Jc(e.runtimeEndpointKeyId),controlEndpointKeyId:Jc(e.controlEndpointKeyId)}}function Jc(e){if(typeof e==`string`&&e.length>0)return e;throw new Go(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function lce(e){return e===void 0?{}:{sequence:e}}function Yc(e){return e===void 0?{}:{actionGrant:e}}async function uce(e){let t=Vc(e.data,e.context.scopes),n=JSON.parse(e.data),r=ace(n.headers),i=ice(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await sce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=oce(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,...lce(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Yc(o)}:{protocolVersion:4,...c,...Yc(o)}}function Xc(e){return typeof e==`string`&&e.length>0}function dce(e){return[e.protocolVersion===4,Xc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===uc,Xc(e.channelId),Xc(e.runtimeEndpointKeyId),Xc(e.runtimeEndpointPublicKey),Xc(e.controlEndpointKeyId),Xc(e.controlEndpointPublicKey),Xc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function Zc(e){if(!dce(e))throw new Go(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function fce(e){if(await jc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new Go(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await xse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Oc({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Oc({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 Tse({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function Qc(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function pce(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 mce(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 hce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new Go(`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 Go(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await Ese({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var gce=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=Wc(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`,Wc(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=Vc(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=Uc(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`,Hc(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 uce({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 Go(`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 Cce({payload: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=>!ece(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&&qc(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=Uc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Hc(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 fce(Zc(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Kse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Uc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Hc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Kc(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`,Hc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=rce(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=Zc(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:_se(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=Zc(this.route);if(t===null||n===null||!Qc(e,r,`handshake`))throw new Go(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await hce({channel:t,route:r,message:e})).open(e),a=Wse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!pce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new Go(`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=Kc(e);if(t?.type!==`relay.encrypted-frame`)throw new Go(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!Qc(t,Zc(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new Go(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Gse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!mce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new Go(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);qc(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 _ce(e,t,n=$c,r=zc({storage:Hse(),randomUUID:n.randomUUID}),i={},a){return new gce(e,t,n,r,i,a).asWebSocket()}var vce=ko(pne);async function yce(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 $c={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:yce},el=`forge-relay-binding=`,bce=3e4;function xce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(el))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 Sce(e){let t=e.crypto??$c,n=e.bindingTtlMs??bce,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=`${el}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=xce(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?.(),_ce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}async function Cce(e){let t=e.issuedAt??new Date,n=e.crypto??$c;return{[$n.requestId]:e.requestId??n.randomUUID(),[$n.sequence]:String(e.sequence),[$n.issuedAt]:t.toISOString(),[$n.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[$n.payloadHash]:await n.sha256Base64Url(uae(e.payload))}}function wce(e,t){return Xte(tne,({rpc:t,request:n,next:r})=>ot(function*(){return Jo({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function Tce(e,t=$c){return vce.pipe(Se(wce(e,t)))}function Ece(e){let t=e.crypto??$c,n=Sce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=gt(n.acquireSocketUrl).pipe(c),i=he(oa,n.constructSocket),a=sa(r).pipe(E(i)),o=e.delayForRetry??lae,s=Lt(_(e.maxRetries??10),e=>rt(Ue(o(e)??0)));return ht(Mo,No({retryPolicy:s,retryTransientErrors:!0})).pipe(E(De(a,Oo)))}var tl=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Dce(e){let t=await yse(e),n=await jc(t.publicKey);return{keyPair:t,publicKey:n,keyId:bse(`control`,n),channelNonce:await vse(e)}}function Oce(e){return{hpkeSuite:uc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function kce(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 tl(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:uc,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 nl=`~effect/ManagedRuntime`,rl=(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=Pt(t=>(c||=f(Aee(o(e,n,i),e=>pt(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),Bee(ve(c)))),u={[nl]:nl,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:At(()=>(u.contextEffect=yee(`ManagedRuntime disposed`),u.cachedContext=void 0,He(u.scope,Tt))),runFork(e,t){return u.cachedContext===void 0?f(il(u,e),s(t)):We(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?cee(il(u,e),s(t)):hte(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Zee(il(u,e)):le(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?fe(il(u,e)):See(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?pee(il(u,e),s(t)):vee(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?A(il(u,e),s(t)):ne(u.cachedContext)(e,s(t))}};return u};function il(e,t){return wt(e.contextEffect,e=>Te(t,e))}function al(e,t=Cne){return`${e}\0${t}`}function Ace(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=al(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(al(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(al(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 ol={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function sl(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function jce(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?sl(t.keyframe):null}function Mce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?ol:t.streamGeneration>e.streamGeneration?sl(t.keyframe):null}function Nce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return sl(t.keyframe);if(t.sequence<=e.observedSequence)return ol;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function Pce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return ol;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?ol:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Fce(e,t){return jce(e,t)??Mce(e,t)??Nce(e,t)??Pce(e,t)}function Ice(e,t){let n=Fce(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}}vn(ane);var cl=O(),ll=`Forge`,Lce=`Alpha`,ul=ll,dl=`0.13.4`,fl=Zt(`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`),pl=`flex h-full min-w-0 items-center gap-1 md:gap-1.5`,ml=`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`,Rce={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`},zce=`forge-app-shell flex w-full min-w-0 flex-row`,hl=`forge-app-shell flex w-full min-w-0 flex-col`,Bce=`flex min-h-0 min-w-0 flex-1 flex-col`,Vce=`relative flex h-[var(--forge-content-height)] min-h-0 min-w-0 flex-1 overflow-hidden`;function gl(e){let t=(0,cl.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,Nr.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=Zt(`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,Nr.jsx)(`span`,{className:m,children:ll}),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,Nr.jsx)(`span`,{className:_,children:Lce}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Nr.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,Nr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":ul,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,Nr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":ul,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function _l(e){let t=(0,cl.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Zt(`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,Nr.jsx)(gl,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Nr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}function Hce(){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 vl=typeof window<`u`?window.localStorage:Hce(),Uce=(e,t)=>rr(Bn(e))(t),Wce=(e,t)=>Dte(Bn(e))(t),yl=(e,t)=>{let n=vl.getItem(e);return n?Uce(t,n):null},bl=(e,t,n)=>{let r=Wce(n,t);vl.setItem(e,r)},xl=e=>{vl.removeItem(e)},Sl=`forge:local_storage_change`;function Gce(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(Sl,{detail:{key:e}}))}function Cl(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return yl(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?xl(e):bl(e,i,n),queueMicrotask(()=>Gce(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=yl(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=yl(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(Sl,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(Sl,o)}},[e,t,n]),[r,a]}var wl=`cmmd-runtime:`;function Tl(e){return`${wl}${e}`}var Kce=/^env_[0-9a-f]{32}$/,qce=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,El={shape:`local`,isCloud:!1,legacyRuntimeId:null},Jce={shape:`cloud-project-placeholder`,isCloud:!0,legacyRuntimeId:null},Yce={shape:`durable-environment`,isCloud:!0,legacyRuntimeId:null};function Dl(e){if(typeof e!=`string`)return El;if(e.startsWith(`cmmd-runtime:`)){let t=e.slice(wl.length);return qce.test(t)?{shape:`legacy-runtime`,isCloud:!0,legacyRuntimeId:t}:El}return e.startsWith(`cmmd-cloud-project:`)?Jce:Kce.test(e)?Yce:El}var Ol=`forge:client-settings:v1`,Xce=`forge:saved-environment-registry:v1`,Zce=nr({environmentId:an,label:j,httpBaseUrl:j,wsBaseUrl:j,createdAt:j,lastConnectedAt:Kn(j),cmmdOrganizationId:cn(j),cmmdProjectId:cn(j),runtimeId:cn(j),runtimeTicketExpiresAt:cn(j),lastAuthenticatedPullRequestCapability:cn(Xn),bearerToken:cn(j)}),kl=nr({version:cn(Ln),records:cn(Jn(Zce))});function Al(){return typeof window<`u`}var Qce={uiFontSize:14,codeFontSize:15},$ce=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function ele(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function tle(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(Qce).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 nle(e){let t=$ce.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 jl(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[ele,tle,nle]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function rle(){if(!Al())return null;try{let e=window.localStorage.getItem(Ol);return e?vn(tr)(jl(JSON.parse(e))):null}catch{return null}}function ile(e){Al()&&bl(Ol,e,tr)}function Ml(){if(!Al())return{};try{return yl(`forge:saved-environment-registry:v1`,kl)??{}}catch{return{}}}function Nl(e){Al()&&bl(Xce,e,kl)}function Pl(){return Ml().records??[]}function ale(e){Nl({version:1,records:e})}function ole(){return Pl().map(e=>wn(e))}function sle(e){let t=new Map(Pl().map(e=>[e.environmentId,e]));ale(e.map(e=>{let n=Dl(e.environmentId).legacyRuntimeId===null?t.get(e.environmentId)?.bearerToken:void 0;return n?{...wn(e),bearerToken:n}:wn(e)}))}function cle(e){return Pl().find(t=>t.environmentId===e)?.bearerToken??null}function lle(e,t){let n=Ml(),r=n.records??[],i=!1;return Nl({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(wn(n),{bearerToken:t})):n)}),i}function ule(e){let t=Ml();Nl({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?wn(t):t)})}var dle=vn(tr);function fle(){return typeof window>`u`?void 0:window.desktopBridge}function Fl(e){let t=fle(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function Il(){let e=Fl(`getClientSettings`);if(e){let t=await e();return t?dle(t):null}return rle()}async function Ll(e){let t=Fl(`setClientSettings`);if(t)return t(e);ile(e)}async function Rl(){let e=Fl(`getSavedEnvironmentRegistry`);return e?e():ole()}async function zl(e){let t=Fl(`setSavedEnvironmentRegistry`);if(t)return t(e);sle(e)}async function Bl(e){let t=Fl(`getSavedEnvironmentSecret`);return t?t(e):cle(e)}async function Vl(e,t){let n=Fl(`setSavedEnvironmentSecret`);return n?n(e,t):lle(e,t)}async function Hl(e){let t=Fl(`removeSavedEnvironmentSecret`);if(t)return t(e);ule(e)}var Ul=`token`;function Wl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Gl(e){let t=Wl(e).get(Ul)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Ul)?.trim()??``;return n.length>0?n:null}function ple(e){let t=new URL(e.toString()),n=Wl(t);return n.has(Ul)&&(n.delete(Ul),t.hash=n.toString()),t.searchParams.delete(Ul),t}function Kl(e,t){let n=new URL(e.toString());return n.searchParams.delete(Ul),n.hash=new URLSearchParams([[Ul,t]]).toString(),n}function mle(e,t){let n=new URL(e);return n.pathname=`/login`,Kl(n,t).toString()}function hle(e){return Kl(new URL(`/login`,window.location.href),e).toString()}function gle(e){let t=new URL(e),n=Gl(t),r=new URL(`forge:///pair`);return r.searchParams.set(`serverUrl`,t.origin),n&&r.searchParams.set(Ul,n),r.toString()}function _le(e){return{_tag:`Value`,value:e}}function vle(e,t){return{_tag:`Record`,keys:e,value:t}}function yle(e,t){return{_tag:`Array`,length:e,value:t}}$t(`SourceError`);var ble=$e(`effect/ConfigProvider`,{defaultValue:()=>Cle()}),xle={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Sle(e,t,n){let r=Object.create(xle);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 Cle(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:`490879f4e6247cf933d524a1e84b36966d2d3111`,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+490879f4e6247cf933d524a1e84b36966d2d3111`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=wle(t);return Sle(e=>rt(Ele(n,t,e)))}function wle(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 Tle=/^(0|[1-9][0-9]*)$/;function Ele(e,t,n){let r=t[n.map(String).join(`_`)],i=Dle(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:_le(r):a.every(e=>Tle.test(e))?yle(Math.max(...a.map(e=>parseInt(e,10)))+1,r):vle(new Set(a),r)}function Dle(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 ql=`~effect/Config`,Ole=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},kle={...Ke,...Cee,[ql]:ql,asEffect(){return wt(ble.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Ale(e){let t=Object.create(kle);return t.parse=e,t}var Jl=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*Jl(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*Jl(e,[...t,i]));return r}}}),Yl=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*Yl(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=qte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*Yl(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*Yl(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Jl(t,n);case`Suspend`:return yield*Yl(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 Xl(e,t){let n=Ute(e),r=Pte(n),i=Yte(n.ast),a=typeof t==`string`?[t]:t??[];return Ale(e=>{let t=e.prefix?[...e.prefix,...a]:a;return Yl(i,e,a).pipe(tte(e=>r(e).pipe(It(e=>new Ote(t.length>0?new Fte(t,e):e)))),It(e=>new Ole(e)))})}var jle=(e,t,n)=>{let r=In(e,t),i=j.pipe(xn(In(j,j),Nte(n)),xn(r));return ir([r,i])},B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Zl=`10.74.0`;function Ql(){return $l(V),V}function $l(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.74.0`,t[Zl]=t[`10.74.0`]||{}}function eu(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Zl]=r[`10.74.0`]||{};return i[e]||(i[e]=t())}var tu=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],Mle=`Sentry Logger `,nu={};function ru(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys(nu);r.forEach(e=>{let r=nu[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Nle(){ou().enabled=!0}function Ple(){ou().enabled=!1}function iu(){return ou().enabled}function Fle(...e){au(`log`,...e)}function Ile(...e){au(`warn`,...e)}function Lle(...e){au(`error`,...e)}function au(e,...t){B&&iu()&&ru(()=>{V.console[e](`${Mle}[${e}]:`,...t)})}function ou(){return B?eu(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:Nle,disable:Ple,isEnabled:iu,log:Fle,warn:Ile,error:Lle},su=50,cu=/\(error: (.*)\)/,lu=/captureMessage|captureException/;function uu(...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=cu.test(n)?n.replace(cu,`$1`):n;if(!o.includes(`Error: `)){for(let e of t){let t=e(o);if(t){i.push(t);break}}if(i.length>=su+r)break}}return zle(i.slice(r))}}function Rle(e){return Array.isArray(e)?uu(...e):e}function zle(e){if(!e.length)return[];let t=Array.from(e);return/sentryWrapped/.test(du(t).function||``)&&t.pop(),t.reverse(),lu.test(du(t).function||``)&&(t.pop(),lu.test(du(t).function||``)&&t.pop()),t.slice(0,su).map(e=>({...e,filename:e.filename||du(t).filename,function:e.function||`?`}))}function du(e){return e[e.length-1]||{}}var fu=`<anonymous>`;function pu(e){try{return!e||typeof e!=`function`?fu:e.name||fu}catch{return fu}}function mu(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 Ble(e){let t=e?.startsWith(`file://`)?e.slice(7):e;return t?.match(/\/[A-Z]:/)&&(t=t.slice(1)),t}var hu={},gu={};function _u(e,t){return hu[e]=hu[e]||[],hu[e].push(t),()=>{let n=hu[e];if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}function vu(e,t){if(!gu[e]){gu[e]=!0;try{t()}catch(t){B&&H.error(`Error while instrumenting ${e}`,t)}}}function yu(e,t){let n=e&&hu[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: ${pu(r)}
@@ -1002,35 +1002,35 @@ or you can use record.mirror to access the mirror instance during recording.`,vV
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.`,MU={map:{},getId(){return console.error(jU),-1},getNode(){return console.error(jU),null},removeNodeFromMap(){console.error(jU)},has(){return console.error(jU),!1},reset(){console.error(jU)}};typeof window<`u`&&window.Proxy&&window.Reflect&&(MU=new Proxy(MU,{get(e,t,n){return t===`map`&&console.error(jU),Reflect.get(e,t,n)}}));function NU(e,t,n,r,i=window){let a=i.Object.getOwnPropertyDescriptor(e,t);return i.Object.defineProperty(e,t,r?n:{set(e){zU(()=>{n.set.call(this,e)},0),a&&a.set&&a.set.call(this,e)}}),()=>NU(e,t,a||{},!0)}function PU(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 QWe(e){if(!e)return null;try{return e.nodeType===e.ELEMENT_NODE?e:e.parentElement}catch{return null}}function FU(e,t,n,r,i){if(!e)return!1;let a=QWe(e);if(!a)return!1;let o=AU(t,n);if(!i){let e=r&&a.matches(r);return o(a)&&!e}let s=kU(a,o),c=-1;return s<0?!1:(r&&(c=kU(a,AU(null,r))),s>-1&&c<0||s<c)}var IU={};function LU(e){let t=IU[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 IU[e]=r.bind(window)}function RU(...e){return LU(`requestAnimationFrame`)(...e)}function zU(...e){return LU(`setTimeout`)(...e)}var BU=(e=>(e[e[`2D`]=0]=`2D`,e[e.WebGL=1]=`WebGL`,e[e.WebGL2=2]=`WebGL2`,e))(BU||{}),VU;function $We(e){VU=e}for(var HU=e=>VU?((...t)=>{try{return e(...t)}catch(e){if(VU&&VU(e)===!0)return()=>{};throw e}}):e,UU=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,eGe=typeof Uint8Array>`u`?[]:new Uint8Array(256),WU=0;WU<UU.length;WU++)eGe[UU.charCodeAt(WU)]=WU;var tGe=function(e){var t=new Uint8Array(e),n,r=t.length,i=``;for(n=0;n<r;n+=3)i+=UU[t[n]>>2],i+=UU[(t[n]&3)<<4|t[n+1]>>4],i+=UU[(t[n+1]&15)<<2|t[n+2]>>6],i+=UU[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},GU=new Map;function nGe(e,t){let n=GU.get(e);return n||(n=new Map,GU.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}var KU=(e,t,n)=>{if(!e||!(YU(e,t)||typeof e==`object`))return;let r=e.constructor.name,i=nGe(n,r),a=i.indexOf(e);return a===-1&&(a=i.length,i.push(e)),a};function qU(e,t,n){if(e instanceof Array)return e.map(e=>qU(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:tGe(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[qU(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:[qU(e.data,t,n),e.width,e.height]}:YU(e,t)||typeof e==`object`?{rr_type:e.constructor.name,index:KU(e,t,n)}:e}var JU=(e,t,n)=>e.map(e=>qU(e,t,n)),YU=(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 rGe(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=PU(t.CanvasRenderingContext2D.prototype,s,function(a){return function(...o){return FU(this.canvas,n,r,i,!0)||zU(()=>{let n=JU(o,t,this);e(this.canvas,{type:BU[`2D`],property:s,args:n})},0),a.apply(this,o)}});a.push(o)}catch{let n=NU(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:BU[`2D`],property:s,args:[t],setter:!0})}});a.push(n)}return()=>{a.forEach(e=>e())}}function iGe(e){return e===`experimental-webgl`?`webgl`:e}function XU(e,t,n,r,i){let a=[];try{let o=PU(e.HTMLCanvasElement.prototype,`getContext`,function(e){return function(a,...o){if(!FU(this,t,n,r,!0)){let e=iGe(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 ZU(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=PU(e,o,function(e){return function(...c){let l=e.apply(this,c);if(KU(l,s,this),`tagName`in this.canvas&&!FU(this.canvas,r,i,a,!0)){let e=JU(c,s,this),r={type:t,property:o,args:e};n(this.canvas,r)}return l}});c.push(l)}catch{let r=NU(e,o,{set(e){n(this.canvas,{type:t,property:o,args:[e],setter:!0})}});c.push(r)}return c}function aGe(e,t,n,r,i,a){let o=[];return o.push(...ZU(t.WebGLRenderingContext.prototype,BU.WebGL,e,n,r,i,a,t)),t.WebGL2RenderingContext!==void 0&&o.push(...ZU(t.WebGL2RenderingContext.prototype,BU.WebGL2,e,n,r,i,a,t)),()=>{o.forEach(e=>e())}}var oGe=`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 sGe(){let e=new Blob([oGe]);return URL.createObjectURL(e)}var cGe=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&&$We(a),(i&&typeof n==`number`||t)&&(this.worker=this.initFPSWorker()),this.addWindow(r),!t&&HU(()=>{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}HU(()=>{if(a&&t===`all`&&this.initCanvasMutationObserver(e,n,r,i),a&&typeof t==`number`){let t=XU(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}RU(t=>this.takeSnapshot(t,!0,e))}initFPSWorker(){let e=new Worker(sGe());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:BU[`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=RU(t)};e=RU(t),this.restoreHandlers.push(()=>{e&&cancelAnimationFrame(e)})}initCanvasMutationObserver(e,t,n,r){let i=XU(e,t,n,r,!1),a=rGe(this.processMutation.bind(this),e,t,n,r),o=aGe(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=>{FU(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=>{HU(()=>{throw this.snapshotInProgressMap.delete(n),e})()})}}),!0)}startPendingCanvasMutationFlusher(){RU(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){let e=t=>{this.rafStamps.latestId=t,RU(e)};RU(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{let n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),RU(()=>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)}XWe();var lGe;(function(e){e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`})(lGe||={});var QU={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}}},uGe=`ReplayCanvas`,$U=1280,dGe=QM(((e={})=>{let[t,n]=e.maxCanvasSize||[],r={quality:e.quality||`medium`,enableManualSnapshot:e.enableManualSnapshot,maxCanvasSize:[t?Math.min(t,$U):$U,n?Math.min(n,$U):$U]},i,a,o=new Promise(e=>a=e);return{name:uGe,getOptions(){let{quality:e,enableManualSnapshot:t,maxCanvasSize:n}=r;return{enableManualSnapshot:t,recordCanvas:!0,getCanvasManager:e=>{let r=new cGe({...e,enableManualSnapshot:t,maxCanvasSize:n,errorHandler:e=>{try{typeof e==`object`&&(e.__rrweb__=!0)}catch{}}});return i=r,a(r),r},...QU[e]||QU.medium}},async snapshot(e,t){(i||await o).snapshot(e,t)}}}));function fGe(e){return e.split(`,`).some(e=>e.trim().startsWith(`sentry-`))}function eW(e){try{return new URL(e,Z.location.origin).href}catch{return}}function pGe(e){return e.entryType===`resource`&&`initiatorType`in e&&typeof e.nextHopProtocol==`string`&&(e.initiatorType===`fetch`||e.initiatorType===`xmlhttprequest`)}function tW(e){try{return new Headers(e)}catch{return}}var nW={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function rW(e,t){let{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:i,enableHTTPTimings:a,tracePropagationTargets:o,onRequestSpanStart:s,onRequestSpanEnd:c}={...nW,...t},l=typeof i==`function`?i:e=>!0,u=e=>hGe(e,o),d={},f=e.getOptions().propagateTraceparent;n&&wI(t=>{let n=BNe(t,l,u,d,{propagateTraceparent:f,onRequestSpanEnd:c});if(n){let r=eW(t.fetchData.url),i=r?GN(r).host:void 0,o=r?qN(r):void 0;n.setAttributes({"http.url":o,"url.full":o,"server.address":i}),a&&iW(n,e),s?.(n,{headers:t.headers})}}),r&&qz(t=>{let n=gGe(t,l,u,d,f,c);n&&(a&&iW(n,e),s?.(n,{headers:tW(t.xhr.__sentry_xhr_v3__?.request_headers)}))})}var mGe=300;function iW(e,t){let{url:n}=$A(e).data;if(!n||typeof n!=`string`)return;let r=()=>void setTimeout(i);if(Uj(t)){let t=e.end.bind(e);e.end=e=>{let n=e??Hk(),a=!1,o=()=>{a||(a=!0,setTimeout(i),t(n),clearTimeout(s))};r=o;let s=setTimeout(o,mGe)}}let i=sz(`resource`,({entries:t})=>{t.forEach(t=>{pGe(t)&&t.name.endsWith(n)&&(e.setAttributes(wz(t)),r())})})}function hGe(e,t){let n=AI();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?Mk(r.toString(),t)||a&&Mk(r.pathname,t):a}{let n=!!e.match(/^\/(?!\/)/);return t?Mk(e,t):n}}function gGe(e,t,n,r,i,a){let o=e.xhr,s=o?.[Kz];if(!o||o.__sentry_own_request__||!s)return;let{url:c,method:l}=s,u=yj()&&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&&(DA(n,s.status_code),n.end(),a?.(n,{headers:tW(Zz(o)),error:e.error})),delete r[t]);return}let d=eW(c),f=GN(d||c),p=d?qN(d):void 0,m=qN(KN(c)),h=X(),g=!!hj(),_=g||!!h&&Uj(h),v=u&&_?Qj({name:`${l} ${m}`,attributes:{url:qN(c),type:`xhr`,"http.method":l,"http.url":p,"url.full":p,"server.address":f?.host,[yA]:`auto.http.browser`,[vA]:`http.client`,...f?.search&&{"http.query":f?.search},...f?.hash&&{"http.fragment":f?.hash}}}):new Cj,y=lM(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)&&_Ge(o,yj()&&_?y:void 0,i),h&&h.emit(`beforeOutgoingRequestSpan`,v,e),v}function _Ge(e,t,n){let{"sentry-trace":r,baggage:i,traceparent:a}=ZN({span:t,propagateTraceparent:n});r&&vGe(e,r,i,a)}function vGe(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||!fGe(t))&&e.setRequestHeader(`baggage`,n)}}catch{}}var aW=new WeakMap,oW=new WeakMap,yGe=9e4,bGe=[`text/event-stream`,`application/x-ndjson`,`application/stream+json`],sW=QM(()=>({name:`FetchStreamPerformance`,setup(){cIe(e=>{if(e.response){let t=aW.get(e.response);if(t&&e.endTimestamp){t.end(e.endTimestamp);let n=oW.get(e.response);n&&clearTimeout(n)}}}),wI(e=>{if(e.endTimestamp&&e.response){let t=e.response.headers?.get(`content-type`)||``;if(e.response.headers?.get(`content-length`)||!bGe.some(e=>t.startsWith(e)))return;let n=e.fetchData?.url||``,r=e.fetchData?.method||`GET`,i=UN(n),a=Qj({name:`${r} ${n.startsWith(`data:`)?qN(n):i?WN(i):n}`,startTime:e.endTimestamp,attributes:{url:qN(n),"http.method":r,type:`fetch`,[vA]:`http.client.stream`,[yA]:`auto.http.browser.stream`}});aW.set(e.response,a);let o=setTimeout(()=>{a.isRecording()&&a.end()},yGe);oW.set(e.response,o)}})}})),xGe=`WebVitals`,cW=QM((e={})=>{let t=new Set(e.ignore??[]);return{name:xGe,setup(n){let r=Uj(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=qRe({recordClsStandaloneSpans:o,recordLcpStandaloneSpans:s,client:n}),l=new WeakSet;n.on(`afterStartPageLoadSpan`,e=>{l.add(e)}),n.on(`spanEnd`,e=>{l.delete(e)&&(c(),nze(e,{recordClsOnPageloadSpan:o===!1,recordLcpOnPageloadSpan:s===!1,spanStreamingEnabled:r}))}),r?(t.has(`lcp`)||xze(n),t.has(`cls`)||Cze(n),t.has(`inp`)||Tze()):t.has(`inp`)||gze()},afterAllSetup(){t.has(`inp`)||bze()}}});function SGe(){Z.document?Z.document.addEventListener(`visibilitychange`,()=>{let e=hj();if(!e)return;let t=pj(e);if(Z.document.hidden&&t){let e=`cancelled`,{op:n,status:r}=$A(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 lW=`sentry_previous_trace`,CGe=`sentry.previous_trace`;function wGe(e,{linkPreviousTrace:t,consistentTraceSampling:n}){let r=t===`session-storage`,i=r?DGe():void 0;e.on(`spanStart`,e=>{if(pj(e)!==e)return;let t=dA().getPropagationContext();i=TGe(i,e,t),r&&EGe(i)});let a=!0;n&&e.on(`beforeSampling`,e=>{if(!i)return;let t=dA(),n=t.getPropagationContext();if(a&&n.parentSpanId){a=!1;return}t.setPropagationContext({...n,dsc:{...n.dsc,sample_rate:String(i.sampleRate),sampled:String(uW(i.spanContext))},sampleRand:i.sampleRand}),e.parentSampled=uW(i.spanContext),e.parentSampleRate=i.sampleRate,e.spanAttributes={...e.spanAttributes,[Mke]:i.sampleRate}})}function TGe(e,t,n){let r=$A(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:{[Vke]:`previous_trace`}}),t.setAttribute(CGe,`${o.traceId}-${o.spanId}-${+!!uW(o)}`)),a)}function EGe(e){try{Z.sessionStorage.setItem(lW,JSON.stringify(e))}catch(e){Q&&Y.warn(`Could not store previous trace in sessionStorage`,e)}}function DGe(){try{let e=Z.sessionStorage?.getItem(lW);return JSON.parse(e)}catch{return}}function uW(e){return e.traceFlags===1}var OGe=`BrowserTracing`,kGe=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function dW(){let e=Z.navigator;return e?.userAgent?kGe.test(e.userAgent):!1}var AGe={...uM,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:`in-memory`,consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...nW},fW=((e={})=>{`enableElementTiming`in e&&OO(()=>{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}={...AGe,...e},te=dW(),ne,O;function k(e,r,i=!0,a){let o=r.op===`pageload`,s=r.name,c=l?l(r):r,p=UN(a||AI()),m={...p?.pathname&&{"url.path":p.pathname},...p&&!HN(p)&&{"url.full":p.href},...c.attributes};if(s!==c.name&&(m[gA]=`custom`),c.attributes=m,!i){let e=Vk();Qj({...c,startTime:e}).end(e);return}t.name=c.name,t.source=m[gA];let h=dM(c,{idleTimeout:u,finalTimeout:d,childSpanTimeout:f,disableAutoFinish:o,beforeSpanEnd:t=>{tze(t,{ignoreResourceSpans:y,ignorePerformanceApiSpans:b,spanStreamingEnabled:Uj(e)}),yW(e,void 0);let n=dA(),r=n.getPropagationContext();n.setPropagationContext({...r,traceId:h.spanContext().traceId,sampled:aj(h),dsc:kj(t)}),o&&(O=void 0)},trimIdleSpanEndTimestamp:!E});o&&E&&(O=h),yW(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:OGe,setup(e){if(te){Q&&Y.log(`[Tracing] Skipping browserTracingIntegration setup for bot user agent.`);return}if(vj(),a&&J.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes(`long-animation-frame`)?YRe():i&&JRe(),o&&XRe(),C&&n){let e=()=>{ne=Hk()};addEventListener(`click`,e,{capture:!0}),addEventListener(`keydown`,e,{capture:!0,passive:!0})}function t(){let t=vW(e);t&&!$A(t).timestamp&&(Q&&Y.log(`[Tracing] Finishing current active span with op: ${$A(t).op}`),t.setAttribute(bA,`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(),fA().setPropagationContext({traceId:qk(),sampleRand:Math.random(),propagationSpanId:yj()?void 0:Jk()});let i=dA();i.setPropagationContext({traceId:qk(),sampleRand:Math.random(),propagationSpanId:yj()?void 0:Jk()}),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=WA(r.sentryTrace||hW(`sentry-trace`)||gW(`sentry-trace`),r.baggage||hW(`baggage`)||gW(`baggage`)),a=dA();a.setPropagationContext(i),yj()||(a.getPropagationContext().propagationSpanId=Jk()),a.setSDKProcessingMetadata({normalizedRequest:mR()}),k(e,{op:`pageload`,...n})}),e.on(`endPageloadSpan`,()=>{E&&O&&(O.setAttribute(bA,`reportPageLoaded`),O.end())})},afterAllSetup(e){if(te)return;e.addIntegration&&!e.getIntegrationByName?.(`WebVitals`)&&e.addIntegration(cW({ignore:r?[]:[`inp`],_experiments:{enableStandaloneClsSpans:s,enableStandaloneLcpSpans:c}}));let n=AI();if(w!==`off`&&wGe(e,{linkPreviousTrace:w,consistentTraceSampling:T}),Z.location){if(x){let t=Wk();pW(e,{name:Z.location.pathname,startTime:t?t/1e3:void 0,attributes:{[gA]:`url`,[yA]:`auto.pageload.browser`}})}S&&Hz(({to:t,from:r})=>{if(r===void 0&&n?.indexOf(t)!==-1){n=void 0;return}n=void 0;let i=UN(t),a=vW(e),o=a&&C&&MGe(a,ne);mW(e,{name:i?.pathname||Z.location.pathname,attributes:{[gA]:`url`,[yA]:`auto.navigation.browser`}},{url:t,isRedirect:o})})}p&&SGe(),o&&jGe(e,u,d,f,t),rW(e,{traceFetch:m,traceXHR:h,tracePropagationTargets:e.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:_,enableHTTPTimings:v,onRequestSpanStart:D,onRequestSpanEnd:ee}),g&&e.addIntegration(sW())}}});function pW(e,t,n){e.emit(`startPageLoadSpan`,t,n),dA().setTransactionName(t.name);let r=vW(e);return r&&e.emit(`afterStartPageLoadSpan`,r),r}function mW(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=dA();return a.setTransactionName(t.name),r&&!i&&a.setSDKProcessingMetadata({normalizedRequest:{...mR(),url:r}}),vW(e)}function hW(e){return(Z.document?.querySelector(`meta[name=${e}]`))?.getAttribute(`content`)||void 0}function gW(e){return(Z.performance?.getEntriesByType?.(`navigation`)[0])?.serverTiming?.find(t=>t.name===e)?.description}function jGe(e,t,n,r,i){let a=Z.document,o;a&&addEventListener(`click`,()=>{let a=`ui.action.click`,s=vW(e);if(s){let e=$A(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(bA,`interactionInterrupted`),o.end(),void 0),!i.name){Q&&Y.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`);return}o=dM({name:i.name,op:a,attributes:{[gA]:i.source||`url`}},{idleTimeout:t,finalTimeout:n,childSpanTimeout:r})},{capture:!0})}var _W=`_sentry_idleSpan`;function vW(e){return e[_W]}function yW(e,t){fk(e,_W,t)}var bW=1.5;function MGe(e,t){let n=$A(e),r=Vk();return!(r-n.start_timestamp>bW||t&&r-t<=bW)}function NGe(e=X()){e?.emit(`endPageloadSpan`)}function PGe(e){let t=hj();if(t===e)return;let n=dA();e.end=new Proxy(e.end,{apply(e,r,i){return Qk(n,t),Reflect.apply(e,r,i)}}),Qk(n,e)}var FGe=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(!Uj(e)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} \`traceLifecycle\` to be set to "stream"! ${n}`);return}let i=r.beforeSendSpan;if(i&&!Aj(i)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} a beforeSendSpan callback using \`withStreamedSpan\`! ${n}`);return}let a=new iIe(e);e.on(`afterSpanEnd`,t=>{aj(t)&&a.add(nje(t,e))}),e.on(`afterSegmentSpanEnd`,e=>{let t=e.spanContext().traceId;setTimeout(()=>{a.flush(t)},500)})}})),xW=1e6,IGe=`window`in J&&J.window===J&&typeof importScripts>`u`,SW=`0`,CW=IGe?`main`:`worker`,wW=Z.navigator,TW=``,EW=``,DW=``,OW=wW?.userAgent||``,kW=``,LGe=wW?.language||wW?.languages?.[0]||``;function RGe(e){return typeof e==`object`&&!!e&&`getHighEntropyValues`in e}var AW=wW?.userAgentData;RGe(AW)&&AW.getHighEntropyValues([`architecture`,`model`,`platform`,`platformVersion`,`fullVersionList`]).then(e=>{if(TW=e.platform||``,DW=e.architecture||``,kW=e.model||``,EW=e.platformVersion||``,e.fullVersionList?.length){let t=e.fullVersionList[e.fullVersionList.length-1];OW=`${t.brand} ${t.version}`}}).catch(e=>void 0);function zGe(e){return!(`thread_metadata`in e)}function BGe(e){return zGe(e)?KGe(e):e}function VGe(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 HGe(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=VGe(r),a=BGe(n),o=t||(typeof r.start_timestamp==`number`?r.start_timestamp*1e3:Hk()*1e3),s=typeof r.timestamp==`number`?r.timestamp*1e3:Hk()*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:TW,version:EW,build_number:OW},device:{locale:LGe,model:kW,manufacturer:OW,architecture:DW,is_emulator:!1},debug_meta:{images:MW(n.resources)},profile:a,transactions:[{name:r.transaction||``,id:r.event_id||Pk(),trace_id:i,active_thread_id:SW,relative_start_ns:`0`,relative_end_ns:((s-o)*1e6).toFixed(0)}]}}function UGe(e,t,n){if(e==null)throw TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${e} instead.`);let r=GGe(e),i=t.getOptions(),a=t.getSdkMetadata?.()?.sdk;return{chunk_id:Pk(),client_sdk:{name:a?.name??`sentry.javascript.browser`,version:a?.version??`0.0.0`},profiler_id:n||Pk(),platform:`javascript`,version:`2`,release:i.release??``,environment:i.environment??`production`,debug_meta:{images:MW(e.resources)},profile:r}}function WGe(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 GGe(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=Wk(),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:SW,timestamp:r}}return{frames:t,stacks:n,samples:o,thread_metadata:{[SW]:{name:CW}}}}function jW(e){return $A(e).op===`pageload`}function KGe(e){let t,n=0,r={samples:[],stacks:[],frames:[],thread_metadata:{[SW]:{name:CW}}},i=e.samples[0];if(!i)return r;let a=i.timestamp,o=Wk(),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)*xW).toFixed(0),stack_id:t,thread_id:SW};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)*xW).toFixed(0),stack_id:n,thread_id:SW};r.stacks[n]=l,r.samples[o]=u,n++}),r}function qGe(e,t){if(!t.length)return e;for(let n of t)e[1].push([{type:`profile`},n]);return e}function JGe(e){let t=[];return Nj(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 MW(e){let t=X()?.getOptions()?.stackParser;return t?cje(t,e):[]}function NW(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 YGe(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 PW=!1,FW=3e4;function XGe(e){return typeof e==`function`}function IW(){let e=Z.Profiler;if(!XGe(e)){Q&&Y.log(`[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.`);return}let t=Math.floor(FW/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.`)),PW=!0}}function LW(e){if(PW)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 NW(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 ZGe(e){if(PW)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 NW(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 RW(e){return e.profilesSampleRate!==void 0}function QGe(e,t,n,r){return YGe(n)?HGe(e,t,n,r):null}var zW=new Map;function $Ge(){return zW.size}function eKe(e){let t=zW.get(e);return t&&zW.delete(e),t}function tKe(e,t){if(zW.set(e,t),zW.size>30){let e=zW.keys().next().value;e!==void 0&&zW.delete(e)}}var BW=new WeakSet;function VW(e){e.setAttribute(`thread.id`,SW),e.setAttribute(`thread.name`,CW)}function HW(e){let t;jW(e)&&(t=Hk()*1e3);let n=IW();if(!n)return;Q&&Y.log(`[Profiling] started profiling span: ${$A(e).description}`);let r=Pk(),i=null;dA().setContext(`profile`,{profile_id:r,start_timestamp:t}),BW.add(e),VW(e);async function a(){if(e&&n){if(i){Q&&Y.log(`[Profiling] profile for:`,$A(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: ${$A(e).description}`),!t){Q&&Y.log(`[Profiling] profiler returned null profile for: ${$A(e).description}`,`this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started`);return}i=t,tKe(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:`,$A(e).description),a()},FW),s=e.end.bind(e);function c(){return e?(a().then(()=>{s()},()=>{s()}),e):s()}e.end=c}var nKe=6e4,rKe=3e5,iKe=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=ZGe(e.getOptions());Q&&Y.log(`[Profiling] Initializing profiler (lifecycle='${t}').`),n||Q&&Y.log(`[Profiling] Session not sampled. Skipping lifecycle profiler initialization.`),this._profilerId=Pk(),this._client=e,this._sessionSampled=n,this._lifecycleMode=t,t===`trace`&&this._setupTraceLifecycleListeners(e),e.on(`spanStart`,e=>{this._isRunning&&VW(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&&VW(e)}_beginProfiling(){if(!this._isRunning){if(this._isRunning=!0,Q&&Y.log(`[Profiling] Started profiling with profiler ID:`,this._profilerId),pA().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`&&pA().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!==pj(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,pA().setContext(`profile`,{})}_clearAllRootSpanTimeouts(){this._rootSpanTimeouts.forEach(e=>clearTimeout(e)),this._rootSpanTimeouts.clear()}_registerTraceRootSpan(e){this._activeRootSpanIds.add(e);let t=setTimeout(()=>this._onRootSpanTimeout(e),rKe);this._rootSpanTimeouts.set(e,t)}_startProfilerInstance(){if(this._profiler?.stopped===!1)return;let e=IW();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()}},nKe))}_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=UGe(await e.stop(),this._client,this._profilerId),n=WGe(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=Rj(t.getSdkMetadata?.()),r=t.getDsn(),i=t.getOptions().tunnel,a=jj({event_id:Pk(),sent_at:new Date().toISOString(),...n&&{sdk:n},...!!i&&r&&{dsn:RA(r)}},[[{type:`profile_chunk`,platform:`javascript`},e]]);t.sendEnvelope(a).then(null,e=>{Q&&Y.error(`Error while sending profile chunk envelope:`,e)})}},aKe=`BrowserProfiling`,oKe=QM((()=>({name:aKe,setup(e){let t=e.getOptions(),n=new iKe;if(!RW(t)&&!t.profileLifecycle&&(t.profileLifecycle=`manual`),RW(t)&&!t.profilesSampleRate){Q&&Y.log(`[Profiling] Profiling disabled, no profiling options found.`);return}let r=hj(),i=r&&pj(r);if(RW(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."),RW(t))i&&jW(i)&&LW(i)&&HW(i),e.on(`spanStart`,e=>{let t=pj(e);e===t?LW(e)&&HW(e):BW.has(t)&&VW(e)}),e.on(`beforeEnvelope`,e=>{if(!$Ge())return;let t=JGe(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=eKe(r);if(!a){Q&&Y.log(`[Profiling] Could not retrieve profile for span: ${r}`);continue}let o=QGe(r,i,a,e);o&&n.push(o)}qGe(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(!yj(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=hj(),t=e&&pj(e);t&&n.notifyRootSpanActive(t)},0)}}}}))),sKe=`SpotlightBrowser`,cKe=[{op:`ui.interaction.click`,name:`#sentry-spotlight`}],lKe=((e={})=>{let t=e.sidecarUrl||`http://localhost:8969/stream`;return{name:sKe,setup:()=>{Q&&Y.log(`Using Sidecar URL`,t)},beforeSetup(e){let t=e.getOptions();t.ignoreSpans=[...t.ignoreSpans||[],...cKe]},afterAllSetup:e=>{uKe(e,t)}}});function uKe(e,t){let n=Wz(`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:Fj(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 dKe=QM(lKe),fKe=QM(()=>({name:`LaunchDarkly`,processEvent(e,t,n){return NP(e)}}));function pKe(){return{name:`sentry-flag-auditor`,type:`flag-used`,synchronous:!0,method:(e,t,n)=>{PP(e,t.value),FP(e,t.value)}}}var mKe=QM(()=>({name:`OpenFeature`,processEvent(e,t,n){return NP(e)}})),hKe=class{after(e,t){PP(t.flagKey,t.value),FP(t.flagKey,t.value)}error(e,t,n){PP(e.flagKey,e.defaultValue),FP(e.flagKey,e.defaultValue)}},gKe=QM(({featureFlagClientClass:e})=>({name:`Unleash`,setupOnce(){let t=e.prototype;dk(t,`isEnabled`,_Ke)},processEvent(e,t,n){return NP(e)}}));function _Ke(e){return function(...t){let n=t[0],r=e.apply(this,t);return typeof n==`string`&&typeof r==`boolean`?(PP(n,r),FP(n,r)):Q&&Y.error(`[Feature Flags] UnleashClient.isEnabled does not match expected signature. arg0: ${n} (${typeof n}), result: ${r} (${typeof r})`),r}}var vKe=(({growthbookClass:e})=>LNe({growthbookClass:e})),yKe=QM(({featureFlagClient:e})=>({name:`Statsig`,setup(t){e.on(`gate_evaluation`,e=>{PP(e.gate.name,e.gate.value),FP(e.gate.name,e.gate.value)})},processEvent(e,t,n){return NP(e)}})),bKe=`WebWorker`,xKe=QM(({worker:e})=>({name:bKe,setupOnce:()=>{(Array.isArray(e)?e:[e]).forEach(e=>UW(e))},addWorker:e=>UW(e)}));function UW(e){e.addEventListener(`message`,e=>{if(wKe(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=>ak(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),SKe(e.data._sentryWorkerError))}})}function SKe(e){let t=X();if(!t)return;let n=t.getOptions().stackParser,r=t.getOptions().attachStacktrace,i=e.reason,a=ik(i)?lB(i):CR(n,i,void 0,r,!0);a.level=`error`,e.filename&&(a.contexts={...a.contexts,worker:{filename:e.filename}}),IM(a,{originalException:i,mechanism:{handled:!1,type:`auto.browser.web_worker.onunhandledrejection`}}),Q&&Y.log(`Captured worker unhandled rejection`,i)}function CKe({self:e}){e.postMessage({_sentryMessage:!0,_sentryDebugIds:e._sentryDebugIds??void 0,_sentryModuleMetadata:e._sentryModuleMetadata??void 0}),e.addEventListener(`unhandledrejection`,t=>{let n={reason:cB(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 wKe(e){if(!ak(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&&!(ak(e._sentryDebugIds)||e._sentryDebugIds===void 0)||n&&!(ak(e._sentryModuleMetadata)||e._sentryModuleMetadata===void 0)||r&&!ak(e._sentryWorkerError)||i&&(!Array.isArray(e._sentryWasmImages)||!e._sentryWasmImages.every(e=>ak(e)&&typeof e.code_file==`string`)))}var TKe=50,[,EKe]=$z,[,DKe]=hIe(),WW=(e,t=0)=>{let n=[];for(let r of e.split(`
1004
1004
  `).slice(t)){let e=EKe(r),t=DKe(r);if(e&&t?.in_app!==!1?n.push(e):t&&(t.module===void 0&&delete t.module,n.push(t)),n.length>=TKe)break}return IO(n)},OKe=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=NI(r);a.sendStatus({status:document.visibilityState,config:i}),setInterval(()=>{a.sendStatus({status:`alive`,config:i})},i.pollInterval)}}});function GW(){let e=pA().getScopeData(),t=fA().getScopeData(),n=dA().getScopeData();return _M(e,t),_M(e,n),e.eventProcessors=[],e}function kKe(e){fA().addScopeListener(t=>{e(GW(),t)}),dA().addScopeListener(t=>{e(GW(),t)}),pA().addScopeListener(t=>{e(GW(),t)})}var KW=QM(()=>({name:`ScopeToMain`,setup(e){let t=NI(e);kKe((e,n)=>{t.sendScope(JSON.stringify(Ck(e,20,2e3))),n.clearBreadcrumbs(),n.clearAttachments()})}}));function qW(e){let t;return yN(e,async e=>(t||=NI(),t.sendEnvelope(e.body),{statusCode:200}))}function JW(e){return[...hB(e).filter(e=>e.name!==`BrowserSession`&&e.name!==`CultureContext`),KW()]}function YW(e={},t=jBe){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=JW(e)),e.stackParser===void 0&&(e.stackParser=WW),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=qW),delete e.initialScope,t(e)}var XW=e({BrowserClient:()=>TR,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>gMe,OpenFeatureIntegrationHook:()=>hKe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>vA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>yA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>_A,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>gA,Scope:()=>eA,addBreadcrumb:()=>QN,addEventProcessor:()=>VM,addIntegration:()=>ZM,bindScopeToEmitter:()=>WAe,breadcrumbsIntegration:()=>nB,browserApiErrorsIntegration:()=>rB,browserProfilingIntegration:()=>oKe,browserSessionIntegration:()=>aB,browserTracingIntegration:()=>fW,buildLaunchDarklyFlagUsedHandler:()=>pKe,captureConsoleIntegration:()=>GMe,captureEvent:()=>IM,captureException:()=>PM,captureFeedback:()=>zP,captureMessage:()=>FM,captureSession:()=>GM,chromeStackLineParser:()=>$z,consoleLoggingIntegration:()=>YNe,contextLinesIntegration:()=>XBe,continueTrace:()=>jAe,createConsolaReporter:()=>QNe,createLangChainCallbackHandler:()=>pI,createTransport:()=>yN,createUserFeedbackEnvelope:()=>eBe,dedupeIntegration:()=>vP,defaultRequestInstrumentationOptions:()=>nW,defaultStackParser:()=>WW,elementTimingIntegration:()=>hze,endSession:()=>UM,eventFiltersIntegration:()=>tP,eventFromException:()=>xR,eventFromMessage:()=>SR,eventLoopBlockIntegration:()=>OKe,exceptionFromError:()=>_R,extraErrorDataIntegration:()=>QMe,featureFlagsIntegration:()=>INe,feedbackAsyncIntegration:()=>QLe,feedbackIntegration:()=>gR,feedbackSyncIntegration:()=>gR,fetchStreamPerformanceIntegration:()=>sW,forceLoad:()=>MBe,functionToStringIntegration:()=>eP,getAbsoluteUrl:()=>zze,getActiveSpan:()=>hj,getClient:()=>X,getCurrentScope:()=>dA,getDefaultIntegrations:()=>JW,getFeedback:()=>aLe,getGlobalScope:()=>pA,getIsolationScope:()=>fA,getReplay:()=>KWe,getRootSpan:()=>pj,getSpanDescendants:()=>fj,getSpanStatusFromHttpCode:()=>EA,getTraceData:()=>ZN,globalHandlersIntegration:()=>sB,graphqlClientIntegration:()=>iVe,growthbookIntegration:()=>vKe,httpClientIntegration:()=>RBe,httpContextIntegration:()=>fB,inboundFiltersIntegration:()=>nP,init:()=>YW,instrumentAnthropicAiClient:()=>mFe,instrumentCreateReactAgent:()=>QFe,instrumentGoogleGenAIClient:()=>EFe,instrumentLangChainEmbeddings:()=>VFe,instrumentLangGraph:()=>$Fe,instrumentOpenAiClient:()=>YPe,instrumentOutgoingRequests:()=>rW,instrumentSupabaseClient:()=>AP,isBotUserAgent:()=>dW,isEnabled:()=>BM,isInitialized:()=>Eje,lastEventId:()=>zM,launchDarklyIntegration:()=>fKe,linkedErrorsIntegration:()=>pB,logger:()=>xIe,makeRendererTransport:()=>qW,metrics:()=>OIe,moduleMetadataIntegration:()=>HMe,normalizeStringifyValue:()=>mB,onLoad:()=>NBe,openFeatureIntegration:()=>mKe,parameterize:()=>XN,registerSpanErrorInstrumentation:()=>vj,registerWebWorker:()=>CKe,replayCanvasIntegration:()=>dGe,replayIntegration:()=>EU,reportPageLoaded:()=>NGe,reportingObserverIntegration:()=>IBe,rewriteFramesIntegration:()=>oNe,scopeToMainIntegration:()=>KW,sendFeedback:()=>qI,setActiveSpanInBrowser:()=>PGe,setAttribute:()=>wje,setAttributes:()=>Cje,setContext:()=>LM,setConversationId:()=>Tje,setCurrentClient:()=>RN,setExtra:()=>bje,setExtras:()=>yje,setHttpStatus:()=>DA,setMeasurement:()=>Bj,setTag:()=>Sje,setTags:()=>xje,setUser:()=>RM,showReportDialog:()=>gB,spanStreamingIntegration:()=>FGe,spanToBaggageHeader:()=>pAe,spanToJSON:()=>$A,spanToTraceHeader:()=>JA,spotlightBrowserIntegration:()=>dKe,startBrowserTracingNavigationSpan:()=>mW,startBrowserTracingPageLoadSpan:()=>pW,startInactiveSpan:()=>Qj,startNewTrace:()=>tM,startSession:()=>HM,startSpan:()=>Xj,startSpanManual:()=>Zj,statsigIntegration:()=>yKe,supabaseIntegration:()=>bNe,suppressTracing:()=>MAe,thirdPartyErrorFilterIntegration:()=>kNe,uiProfiler:()=>Wze,unleashIntegration:()=>gKe,updateSpanName:()=>cAe,viewHierarchyIntegration:()=>aVe,webVitalsIntegration:()=>cW,webWorkerIntegration:()=>xKe,withActiveSpan:()=>$j,withIsolationScope:()=>jke,withScope:()=>mA,withStreamedSpan:()=>mAe,zodErrorsIntegration:()=>ONe}),AKe=100,jKe=5,MKe=[`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 ZW(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function NKe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),ZW(e.extra),ZW(e.tags)}function PKe(e){let t=$W(e.version)??`0.0.0`,n=$W(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function QW(e,t){for(let n of t){let t=$W(e[n]);if(t)return t}}function FKe(e){return eG(e.enabled)??e.defaultEnabled??!1}function IKe(e){let t=$W(e.dsn);return!t||FKe(e)===!1?null:{dsn:t,environment:$W(e.environment)??$W(e.defaultEnvironment)??`production`,release:$W(e.release)??$W(e.defaultRelease)??void 0,debug:eG(e.debug)??e.defaultDebug??!1,tracesSampleRate:nG(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:tG(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:tG(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:tG(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:AKe,normalizeDepth:jKe,tags:LKe(e)}}function LKe(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=$W(r);e&&(t[n]=e)}return t}function $W(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function eG(e){if(typeof e==`boolean`)return e;let t=$W(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function tG(e,t){if(t!==void 0||e!==void 0)return nG(e,t??0)}function nG(e,t){let n=RKe(e);return n===null||n<0||n>1?t:n}function RKe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=$W(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}function zKe(e){let t=(0,cl.c)(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=Zt(hl,`bg-background text-foreground`),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=Zt(pl,`pl-1 md:pl-2.5`),t[1]=r):r=t[1];let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Nr.jsx)(_l,{}),t[2]=i):i=t[2];let a;t[3]===e.onGoToNewChat?a=t[4]:(a=(0,Nr.jsx)(`div`,{className:r,children:(0,Nr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:e.onGoToNewChat,className:`${ml} 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,Nr.jsx)(`div`,{}),t[5]=o):o=t[5];let s;t[6]===a?s=t[7]:(s=(0,Nr.jsxs)(`header`,{className:fl,children:[a,o]}),t[6]=a,t[7]=s);let c;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Nr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Nr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Nr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Nr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Nr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:BKe,type:`button`,children:`Reload app`})]})}),t[8]=c):c=t[8];let l;return t[9]===s?l=t[10]:(l=(0,Nr.jsxs)(`div`,{className:n,children:[s,c]}),t[9]=s,t[10]=l),l}function BKe(){return window.location.reload()}var VKe=[/\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],HKe=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function rG(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 UKe(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 WKe(e){if(!e)return null;let t=e.toLowerCase(),n=UKe(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.`:rG(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 GKe(e){return e?VKe.some(t=>t.test(e)):!1}function iG(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:GKe(n)?WKe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var KKe=[/\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 aG(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&KKe.some(e=>e.test(t))}function oG(e){return aG(e)?null:iG(e,{fallback:HKe})}var sG=`forge-web`,cG=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],lG=[`VITE_SENTRY_RELEASE`],qKe=[`VITE_SENTRY_DSN`],JKe=[`VITE_SENTRY_DEBUG`],YKe=[`VITE_SENTRY_ENABLED`],XKe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],ZKe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],QKe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],$Ke=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],eqe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],uG=!1,dG={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 tqe(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 nqe(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 rqe(e){return tqe(e).some(aG)||nqe(e)}function iqe(){let e=new URL(window.location.href);Pr?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function aqe(){let e=Pr?`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:`a3822a9b2aed0923a7289c64337048a09fc730fa`,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+a3822a9b2aed0923a7289c64337048a09fc730fa`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=QW(t,[...lG])??PKe({appName:sG,version:`0.13.4`,commitHash:QW(t,[...eqe])});return IKe({appName:sG,runtime:e,defaultEnvironment:QW(t,[...cG])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:QW(t,[...YKe]),dsn:QW(t,[...qKe]),environment:QW(t,[...cG]),release:QW(t,[...lG]),debug:QW(t,[...JKe]),tracesSampleRate:QW(t,[...XKe]),profilesSampleRate:QW(t,[...ZKe]),replaysSessionSampleRate:QW(t,[...QKe]),replaysOnErrorSampleRate:QW(t,[...$Ke]),tags:{platform:Pr?`desktop`:`web`}})}function fG(e){return NKe(e),rqe(e)?null:e}function oqe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function pG(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...MKe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...oqe(e)}}function sqe(e){let t=[];e.tracesSampleRate>0&&t.push(fW()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(EU());let n=gR(dG);t.push(n);try{YW({...pG(e),beforeSend:e=>fG(e),integrations:t})}catch{return null}return uG=!0,XW}function cqe(e){let t=[];e.tracesSampleRate>0&&t.push(pE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(DT());let n=ub(dG);t.push(n);try{qE({...pG(e),beforeSend:e=>fG(e),integrations:t})}catch{return null}return uG=!0,xO}function mG(){if(uG)return Pr?XW:xO;let e=aqe();return e?Pr?sqe(e):cqe(e):null}function hG(e){if(mG()){if(Pr){RM(e);return}Em(e)}}function gG(e,t,n){if(!mG())return;let r=lqe(e);if(Pr){mA(e=>{t&&e.setTags(t);let i=PM(r);n?.showReportDialog&&gB({eventId:i})});return}Ud(e=>{t&&e.setTags(t);let i=Sm(r);n?.showReportDialog&&gS({eventId:i})})}function lqe(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 uqe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){gG(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Nr.jsx)(zKe,{onGoToNewChat:iqe}):this.props.children}},_G=!1,vG=!1,yG=null,bG=null,xG=null,SG=!1,CG=new Set;function dqe(e){if(_G||vG)return;if(!e.publicKey||!e.host){vG=!0;return}if(yG)return;if(typeof window>`u`||typeof location>`u`){vG=!0;return}let t=e.publicKey,n=e.host;yG=N(async()=>{let{default:e}=await import(`./module-CPO4cjSm.js`);return{default:e}},[]).then(({default:e})=>{bG=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{_G=!0,xG&&wG(xG),TG(),CG.forEach(e=>e())}})}).catch(()=>{vG=!0,bG=null})}function wG(e){if(xG=e,!_G||!bG)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),bG.identify(e.cmmdUserId,t)}function fqe(e){return!_G||!bG?!1:bG.isFeatureEnabled(e)===!0}function TG(){!bG||SG||(SG=!0,bG.onFeatureFlags(()=>{CG.forEach(e=>e())}))}function pqe(e){return CG.add(e),_G&&bG&&(TG(),e()),()=>{CG.delete(e)}}var EG=`/api/cmmd/auth-runtime`;function mqe(e){return P({method:`POST`,path:EG},e)}function hqe(e){return P({method:`GET`,path:EG},e)}function gqe(e){return P({method:`DELETE`,path:EG},e)}function _qe(e){return P({method:`POST`,path:`${EG}/connect`},e)}function vqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing`,...t?.organizationId===void 0?{}:{query:{orgId:t.organizationId}}},e)}function yqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:t.timeZone}},e)}var DG=`/api/cmmd/providers/codex/credential`,OG=`/api/cmmd/providers/claude/credential`;function bqe(e){return P({method:`GET`,path:DG},e)}function xqe(e){return P({method:`DELETE`,path:DG},e)}function Sqe(e){return P({method:`GET`,path:OG},e)}function Cqe(e){return P({method:`DELETE`,path:OG},e)}function wqe(e,t){return P({method:`DELETE`,path:`/api/cmmd/providers/accounts/${encodeURIComponent(String(t))}`},e)}function Tqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/disposition`}function Eqe(e,t,n,r,i){return P({method:`PUT`,path:Tqe(t,n,r),body:i},e)}function Dqe(e){return(t,n,r,i)=>Eqe(e,t,n,r,i)}function Oqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/archive`}function kqe(e,t,n,r,i){return P({method:`POST`,path:Oqe(t,n,r),body:i},e)}function Aqe(e){return(t,n,r,i)=>kqe(e,t,n,r,i)}function jqe(e){return typeof e==`object`&&!!e&&`status`in e&&e.status===409}async function Mqe(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(!jqe(n))throw n;let r=await e.refresh();return e.submit({...t,expectedRevision:r.revision})}}function Nqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/forge-runtimes/${encodeURIComponent(t)}/rename`,body:{displayName:n}},e)}function Pqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/rename`,body:{displayName:n}},e)}function Fqe(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/revoke`},e)}function kG(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var Iqe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},Lqe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},AG=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function jG(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 MG(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 NG(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 PG(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 Rqe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function FG(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 IG(e){let t=`${PG(e,`firstName`)??``} ${PG(e,`lastName`)??``}`.trim()||PG(e,`username`)||PG(e,`email`)||`Unknown`;return{id:FG(e,`userId`)??FG(e,`id`)??t,name:t,email:PG(e,`email`),role:PG(e,`role`),avatarUrl:PG(e,`profileImage`)??PG(e,`avatar`)}}function zqe(e){let t=RG(e,`user`)??e;return IG({...typeof t==`object`&&t?t:{},userId:FG(e,`userId`)??FG(t,`id`),role:PG(e,`role`)})}function LG(e){let t=PG(e,`authorFirstName`)??``,n=PG(e,`authorLastName`)??``,r=PG(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:FG(e,`id`)??``,status:i,body:PG(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:PG(e,`authorProfileImage`)??null,createdAt:PG(e,`createdAt`)??``,updatedAt:PG(e,`updatedAt`)??PG(e,`createdAt`)??``,canEdit:Rqe(e,`canEdit`)??!1}}function Bqe(e,t,n){let r=Array.isArray(e.data)?e.data.map(LG):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function RG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var Vqe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function zG(e,t){let n=RG(e,t);if(!n)return null;for(let e of Vqe){let t=PG(n,e);if(t)return t}return null}function BG(e,t){let n=RG(e,t);return n?FG(n,`id`):null}function VG(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function Hqe(e){let t={...e,id:FG(e,`id`)??e.id,title:e.title??PG(e,`name`)??``},n=FG(e,`workspaceId`)??FG(e,`workspace_id`)??BG(e,`workspace`)??e.workspaceId??null;return n!==null||VG(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??PG(e,`start_date`)??null,endDate:e.endDate??PG(e,`end_date`)??null}:t}function HG(e){let t=e.ownerAvatarUrl??PG(e,`owner_avatar_url`)??PG(e,`ownerProfileImage`)??PG(e,`owner_profile_image`)??PG(e,`ownerImage`)??PG(e,`owner_image`)??PG(e,`ownerImageUrl`)??PG(e,`owner_image_url`)??PG(e,`createdByAvatarUrl`)??PG(e,`created_by_avatar_url`)??PG(e,`createdByProfileImage`)??PG(e,`created_by_profile_image`)??zG(e,`owner`)??zG(e,`createdBy`)??zG(e,`created_by`)??null,n={...e,id:FG(e,`id`)??e.id},r=FG(e,`campaignId`)??FG(e,`campaign_id`)??BG(e,`campaign`)??e.campaignId??null;(r!==null||VG(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??PG(e,`campaignTitle`)??PG(e,`campaign_title`)??PG(RG(e,`campaign`),`title`)??PG(RG(e,`campaign`),`name`)??null;(i!==null||VG(e,`campaignTitle`))&&(n.campaignTitle=i);let a=FG(e,`workspaceId`)??FG(e,`workspace_id`)??BG(e,`workspace`)??e.workspaceId??null;(a!==null||VG(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??PG(e,`workspace_name`)??PG(RG(e,`workspace`),`name`)??null;(o!==null||VG(e,`workspaceName`))&&(n.workspaceName=o);let s=PG(e,`workspaceIconUrl`)??PG(e,`workspace_icon_url`)??PG(RG(e,`workspace`),`iconUrl`)??null;(s!==null||VG(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=FG(e,`ownerId`)??FG(e,`owner_id`)??BG(e,`owner`)??e.ownerId??null;(c!==null||VG(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??PG(e,`owner_name`)??PG(RG(e,`owner`),`name`)??null;(l!==null||VG(e,`ownerName`))&&(n.ownerName=l),(t!==null||VG(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=FG(e,`teamId`)??FG(e,`team_id`)??BG(e,`team`)??e.teamId??null;(u!==null||VG(e,`teamId`))&&(n.teamId=u);let d=e.teamName??PG(e,`team_name`)??PG(RG(e,`team`),`name`)??null;(d!==null||VG(e,`teamName`))&&(n.teamName=d);let f=e.startDate??PG(e,`start_date`)??null;(f!==null||VG(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??PG(e,`target_end_date`)??null;return(p!==null||VG(e,`targetEndDate`))&&(n.targetEndDate=p),n}function UG(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 Uqe(e){return UG(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 Wqe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function WG(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function GG(e){try{return await e}catch(e){throw e instanceof gr?e.kind===`auth`?new Iqe(e.message):new Lqe(e.message,e.status??502):e}}var KG=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?or:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??hr,...t?{resolveBearerToken:()=>mr()?.bearerToken??null}:{}},this.putThreadDisposition=Dqe(this.cfg),this.postThreadArchive=Aqe(this.cfg)}async getTask(e){return GG(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 GG(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await GG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await GG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return GG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return GG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await GG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return GG(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=rn(_ne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return UG(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return Uqe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return UG(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),GG(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return GG(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 GG(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 GG(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 gr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of ene){let r=t[e];r!==void 0&&(n[e]=sne[e]===`nullableId`?WG(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),GG(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 vqe(this.cfg,e)}getBillingSeries(e){return yqe(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 mqe(this.cfg)}getAuthRuntimeState(){return hqe(this.cfg)}destroyAuthRuntime(){return gqe(this.cfg)}connectAuthRuntime(){return _qe(this.cfg)}getUserCodexCredential(){return bqe(this.cfg)}disconnectUserCodexCredential(){return xqe(this.cfg)}getUserClaudeCredential(){return Sqe(this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(e){return wqe(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 Cqe(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 Nqe(this.cfg,e,t)}renameDevice(e,t){return Pqe(this.cfg,e,t)}revokeDevice(e){return Fqe(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`),jG(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map(Hqe)}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`),jG(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(HG)}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 HG(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(IG):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map(zqe):[]}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 Bqe(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 LG(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return LG(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 MG(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return MG(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 MG(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=NG(t);return MG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=NG(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=NG(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=NG(t,t?.taskId);return MG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=NG(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=NG(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=NG(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=NG(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=NG(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=NG(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 spawnForgeThreadFromBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/spawn-forge-thread`,body:{}},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:kG(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:kG(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new AG(`createSubtask`)}async createBoardTask(e){throw new AG(`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=WG(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=WG(e.organizationId)),Wqe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:WG(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=WG(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 AG(`uploadBrainDoc`)}};function qG(e){return new KG(e)}var JG=new KG({onAuthExpired:hr}),YG=class extends $t(`BootstrapHttpError`){},XG=e=>nee(e,`BootstrapHttpError`);function ZG(e){return typeof e!=`object`||!e?!1:!!(XG(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof gr&&e.kind===`auth`)}function Gqe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function QG(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new YG({message:`${t} returned a non-JSON response (${Gqe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function $G(e={resolveUrl:or}){let t=mr()?.bearerToken;return t?{...e,bearerToken:t}:e}var eK=null,tK=null,nK=null,rK=new Set,iK=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function Kqe(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();hG({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),wG({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function aK(){if(typeof window>`u`||nK)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(nK=e(e=>{eK=null,tK=null,e.sessionLifecycle.status!==`ready`&&hG(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&Ane().catch(e=>{gG(e,{route:`desktop-auth-session-expired`})})}))}function qqe(){return Gl(new URL(window.location.href))}function oK(){let e=new URL(window.location.href),t=ple(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function Jqe(){return hK(async()=>{let e=or(`/api/auth/session`),t=async()=>{let t=await fetch(e,ur({credentials:`include`}));if(!t.ok)throw new YG({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return QG(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 Mne()?t():n})}async function Yqe(e,t){return await e.text()||t}var sK=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function Xqe(e){return hK(async()=>{let t={credential:e},n=or(`/api/auth/bootstrap`),r=await fetch(n,ur({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new YG({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return QG(r,n)})}function cK(e){return new URL(e,window.location.origin).toString()}function lK(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function uK(){return typeof window>`u`?null:lK(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function Zqe(){return typeof window>`u`?!1:Nne()===`session-expired`}function dK(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(iK),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function fK(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(iK);return}window.sessionStorage.setItem(iK,JSON.stringify([...e]))}catch{}}function Qqe(){let e=uK();if(!e)return;let t=new Set(dK());t.add(e),fK(t)}function $qe(e){return dK().has(e)}function pK(){let e=uK();if(!e){fK(new Set);return}let t=new Set(dK());t.delete(e),fK(t)}async function mK(){let e=cK(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?QG(t,e):null}async function eJe(e){if(typeof window>`u`)return;let t=lK(e);if(!t||Zqe()||rK.has(t)||$qe(t))return;if((await mK().catch(()=>null))?.authenticated){rK.add(t);return}let n=cK(`/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 YG({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await QG(r,n),rK.add(t)}async function tJe(){let e=await Jqe();if(e.authenticated)return e;let t=mr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await mK().catch(()=>null);return n?.authenticated?n:e}var nJe=new Set([404,502,503,504]),rJe=15e3,iJe=500;function aJe(e){mr()?.source===`paired-bearer`&&ZG(e)&&dr(`http`)}async function hK(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(aJe(e),!sJe(e))throw e;if(Date.now()-t>=rJe)throw gG(e,{route:`bootstrap-retry-exhausted`}),e;await oJe(iJe)}}function oJe(e){return new Promise(t=>{setTimeout(t,e)})}function sJe(e){return XG(e)?nJe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function cJe(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 lJe(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return cJe(await t(),e)}catch(e){return gG(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function uJe(e,t){return hG(null),jne(t),await sr().catch(e=>{gG(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Pne(t)??`Forge Desktop requires CMMD authentication.`}}async function dJe(){let e=await tJe();if(e.authenticated){if(e.cmmdIdentity){let t=await lJe(e.cmmdIdentity);return t?(fr(),uJe(e,t)):(fr(),Kqe(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function fJe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);tK=null,pK(),await Xqe(t),eK=null,oK()}function gK(){pK(),tK=null,eK=null}async function _K(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=or(`/api/auth/bootstrap/command`),s=await fetch(o,ur({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 YG({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await QG(s,o),gK()}async function pJe(){let e=or(`/api/auth/ws-token`),t=await fetch(e,ur({credentials:`include`,method:`POST`}));if(!t.ok)throw new YG({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return QG(t,e)}async function mJe(e){let t=await pJe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function hJe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=or(`/api/auth/pairing-token`),a=await fetch(i,ur({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await Yqe(a,`Failed to create pairing credential (${a.status}).`));return QG(a,i)}async function gJe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new YG({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return _Je(await QG(t,e))}function _Je(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=vJe(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 vJe(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 yJe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},$G())}catch(e){throw e instanceof gr&&e.kind!==`auth`&&e.code!==null&&sK.has(e.code)?new gr({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 bJe(e={}){return yJe(e.forceFresh===!0)}async function vK(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},$G())}catch(e){throw e instanceof gr&&e.kind!==`auth`&&e.code!==null&&sK.has(e.code)?new gr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function xJe(e){try{return await vK(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof gr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof gr||t instanceof Error)return vK(`/api/command/tasks/update`,e);throw t}}async function SJe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function CJe(){let e=await Promise.allSettled([sr(),SJe()]);hG(null),Qqe(),eK=null,tK=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function wJe(){if(aK(),tK?.status===`authenticated`)return fr(),tK;if(eK)return eK;let e=yK();return eK=e,e.then(e=>(e.status===`authenticated`&&(tK=e),e)).finally(()=>{eK===e&&(eK=null)})}async function yK(){return lr().then(e=>eJe(e)).then(()=>dJe())}async function TJe(){aK(),eK=null,tK=null;let e=await yK();return e.status===`authenticated`&&(tK=e,fr()),e}async function EJe(e){let t=e.email.trim();if(!t||!e.password)throw Error(`Enter your CMMD email and password.`);let n=or(`/api/auth/cmmd-password/token`),r=await fetch(n,ur({body:JSON.stringify({email:t,password:e.password}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new YG({message:await r.text()||`CMMD login failed (${r.status}).`,status:r.status});let i=await QG(r,n);if(i.authenticated===!0)return gK(),{serverEstablishedSession:!0};if(typeof i.access_token!=`string`||i.access_token.trim().length===0)throw Error(`CMMD login did not return an access token.`);return await _K(i.access_token,i.user,{refreshToken:typeof i.refresh_token==`string`?i.refresh_token:void 0,mcpToken:typeof i.mcp_token==`string`?i.mcp_token:void 0}),{serverEstablishedSession:!1}}var DJe=`/.well-known/forge/environment`,bK=Xt()(e=>({descriptor:null,setDescriptor:t=>e({descriptor:t}),reset:()=>e({descriptor:null})})),xK=null;function OJe(e){let t=SK();return t?Qie(Po({id:t.environmentId,label:t.label,source:e.source,target:e.target}),t):null}async function kJe(){return hK(async()=>{await lr();let e=mr()?.bearerToken,t=or(DJe),n=e?await fetch(t,{headers:{Authorization:`Bearer ${e}`}}):await fetch(t);if(!n.ok)throw new YG({message:`Failed to load server environment descriptor (${n.status}).`,status:n.status});let r=await QG(n,t);return CK(r),r})}function SK(){return bK.getState().descriptor}function AJe(){return bK(jJe)}function jJe(e){return e.descriptor?.environmentId??null}function MJe(){return bK(NJe)}function NJe(e){return e.descriptor}function PJe(){return bK(FJe)}function FJe(e){return e.descriptor?.deviceRuntimeId??null}function IJe(){return SK()?.deviceRuntimeId??null}function LJe(){return bK(RJe)}function RJe(e){return iae(e.descriptor)}function zJe(){return bK(BJe)}function BJe(e){return aae(e.descriptor)}function CK(e){bK.getState().setDescriptor(e)}function VJe(e,t){return t?.primaryMode!==`cloud`||e.environmentId===t.environmentId}function wK(){let e=mr();return e?OJe({source:e.source,target:e.target}):null}function HJe(){return UJe()}async function UJe(){let e=await lr(),t=SK();if(t&&VJe(t,e))return Promise.resolve(t);if(t&&CK(null),xK)return xK;let n=kJe();return xK=n,n.finally(()=>{xK===n&&(xK=null)})}var TK=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 EK(e){return{match:t=>t.present({target:e})}}function DK(){return{match:e=>e.provablyAbsent()}}function WJe(e){return{match:t=>t.unprovable(e)}}var GJe=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?DK():EK(TK.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 EK(TK.namedByCatalog(t))}if(this.#e.length===0)return DK();let t=e.runtimeId??e.cmmdEnvironmentId;return WJe(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 OK(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(KJe))throw Error(`Forge Cloud returned a project catalog this version cannot read (invalid project entry).`);if(!i.every(qJe))throw Error(`Forge Cloud returned an Environment catalog this version cannot read (invalid Environment entry).`);return GJe.fromValidatedBody(r,i,n?.capacity??null)}function KJe(e){return!AK(e)||typeof e.organizationId!=`number`||typeof e.projectId!=`number`?!1:e.runtime===void 0||e.runtime===null||kK(e.runtime)}function qJe(e){return AK(e)&&typeof e.organizationId==`number`&&typeof e.userId==`number`&&kK(e.runtime)}function kK(e){return AK(e)&&typeof e.runtimeId==`string`&&typeof e.status==`string`}function AK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JJe(e,t){let n=new URL(e);return n.pathname=t,n.search=``,n.hash=``,n.toString()}function jK(e){return e.accessToken??e.resolveAccessToken?.()}function MK(e,t,n=t=>JJe(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:()=>jK(e)})}function YJe(e,t){return MK(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 XJe(e,t){return MK(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 NK(e,t=``){return`/api/forge/context/runtimes/${encodeURIComponent(e)}${t}`}async function ZJe(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 PK=class{config;constructor(e){this.config=e}async ensureRuntime(e){return(await MK(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 MK(this.config,{method:`POST`,path:NK(e.runtimeId,`/connect`),...e.organizationId===void 0?{}:{body:{organizationId:e.organizationId}},...e.signal===void 0?{}:{signal:e.signal}})}async getRuntime(e){return(await MK(this.config,{method:`GET`,path:NK(e.runtimeId),...e.signal===void 0?{}:{signal:e.signal}})).runtime}async destroyRuntime(e){return(await MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`GET`,path:NK(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=jK(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 ZJe(n),OK(await n.json())}return OK(await MK(this.config,{method:`GET`,path:`/api/forge/context/cloud-projects`,...e?.signal===void 0?{}:{signal:e.signal}}))}async previewCloudProjectRemoval(e){return YJe(this.config,e)}async requestCloudProjectRemoval(e){return XJe(this.config,e)}async getCloudProjectRemoval(e){return(await MK(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}},FK=`/api/attachments/upload/`;function QJe(e){if(!e.relativeUrl.startsWith(FK))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}${FK}`,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 IK=!1,LK=null;function RK(e){return Object.values(e)}function zK(e){return e.map(e=>wn(e))}function BK(e){try{zl(zK(RK(e))).catch(e=>{console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)})}catch(e){console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)}}function $Je(e){let t=VK.getState().byId,n=Object.fromEntries(e.map(e=>[e.environmentId,e]));VK.setState({byId:{...n,...t}})}async function eYe(){if(IK)return;if(LK)return LK;let e=(async()=>{try{$Je(await Rl())}catch(e){console.error(`[SAVED_ENVIRONMENTS] hydrate failed`,e)}finally{IK=!0,VK.setState({hydrated:!0})}})().finally(()=>{LK===e&&(LK=null)});return LK=e,LK}var VK=Xt()(e=>({byId:{},hydrated:IK,upsert:t=>e(e=>{let n={...e.byId,[t.environmentId]:t};return BK(n),{byId:n}}),remove:t=>e(e=>{let{[t]:n,...r}=e.byId;return BK(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 BK(i),{byId:i}}),reset:()=>{BK({}),e({byId:{}})}}));function HK(){return IK}function UK(){return HK()?Promise.resolve():eYe()}function WK(){return Object.values(VK.getState().byId).toSorted((e,t)=>e.label.localeCompare(t.label))}function tYe(){return WK().filter(e=>e.lastAuthenticatedPullRequestCapability===!0)}function GK(e){return VK.getState().byId[e]??null}function KK(e){let t=wK();return t?.environmentId===e?Zie(t):GK(e)?.httpBaseUrl??null}function qK(e){let t=KK(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 JK(e){if(!KK(e))throw Error(`Unable to resolve HTTP base URL for environment ${e}.`)}function nYe(e){return JK(e.environmentId),QJe({httpBaseUrl:KK(e.environmentId),relativeUrl:e.relativeUrl})}async function YK(e){await zl(zK(RK({...VK.getState().byId,[e.environmentId]:e})))}async function rYe(e,t){let{[e]:n,...r}=VK.getState().byId,i={...r,[t.environmentId]:t};await zl(zK(RK(i))),VK.setState({byId:i})}async function XK(e){return Bl(e)}async function iYe(e,t){return Vl(e,t)}async function ZK(e){await Hl(e)}var aYe=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function QK(e){let t=e?.trim();return t&&t.length>0?t:null}function oYe(e){return QK(e)??`Project`}function sYe(e,t=`safe`){let n=QK(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function $K(e,t=`Something went wrong. Try again.`){let n=iG(e instanceof Error?e.message:typeof e==`string`?e:String(e),{fallback:t});return!n||aYe.some(e=>e.test(n))?t:n}function cYe(e,t){return e.reasoningEffortLevels.some(e=>e.value===t)}function eq(e){return e.reasoningEffortLevels.find(e=>e.isDefault)?.value??null}function tq(e,t){let n=eq(e),r=typeof t==`string`?t.trim():null;return r&&!e.promptInjectedEffortLevels.includes(r)&&cYe(e,r)?r:n??void 0}function nq(e,t){return e.contextWindowOptions.some(e=>e.value===t)}function rq(e){return e.contextWindowOptions.find(e=>e.isDefault)?.value??null}function lYe(e,t){let n=rq(e);return t&&nq(e,t)?t:n??void 0}function uYe(e,t){let n=tq(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 dYe(e,t){let n=tq(e,t?.effort),r=e.supportsThinkingToggle?t?.thinking:void 0,i=e.supportsFastMode?t?.fastMode:void 0,a=lYe(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 iq(e){return typeof e==`string`&&/\bultrathink\b/i.test(e)}function aq(e,t=`codex`){if(typeof e!=`string`)return null;let n=e.trim();if(!n)return null;let r=Sne[t],i=Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return typeof i==`string`?i:n}function oq(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=aq(r,e),s=n.find(e=>e.slug===o);return s?s.slug:null}var fYe=[`codex`,`claudeAgent`];function sq(e,t){return fYe.filter(e=>e!==t).some(t=>jte(t,e)!==void 0)}function pYe(e,t){let n=aq(e,t);return!n||sq(n,t)?On[t]:n}function cq(e,t){return pYe(t,e)}function mYe(e){return typeof e==`string`&&e.trim()||null}function hYe(e,t){let n=e.trim();return!n||t!==`ultrathink`||n.startsWith(`Ultrathink:`)?n:`Ultrathink:\n${n}`}function lq(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?uq(e.defaultModelSelection):null,createdAt:e.createdAt,updatedAt:e.updatedAt,scripts:dq(e.scripts)}}function uq(e){return{...e,model:cq(e.provider,e.model)}}function dq(e){return e.map(e=>({...e}))}function gYe(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?uq(t.defaultModelSelection):null},...t.scripts===void 0?{}:{scripts:dq(t.scripts)},updatedAt:t.updatedAt}}function fq(e){let t=oG(e.lastError);return{provider:vYe(e.providerName),status:_Ye(e.status),orchestrationStatus:e.status,activeTurnId:e.activeTurnId??void 0,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{lastError:t}:{}}}function pq(e,t){let n=t.attachments?.map(t=>{let n=qK({environmentId:e,pathname:yYe(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 mq(e){return{id:e.id,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId,createdAt:e.createdAt,updatedAt:e.updatedAt}}function hq(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 _Ye(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 vYe(e){return e===`codex`||e===`claudeAgent`||e===`ollama`||e===`cmmd`||e===`apex`?e:`codex`}function yYe(e){return`/attachments/${encodeURIComponent(e)}`}var bYe=[],xYe=[],SYe=[],CYe=[],wYe={},TYe={},EYe={},DYe={},OYe=[],gq=new WeakMap,_q=new WeakMap;function vq(e,t,n){if(!e||e.length===0||!t)return n;let r=gq.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||gq.set(e,o),a}function kYe(e,t){return vq(e.messageIdsByThreadId[t],e.messageByThreadId[t]??wYe,bYe)}function AYe(e,t){return vq(e.activityIdsByThreadId[t],e.activityByThreadId[t]??TYe,xYe)}function jYe(e,t){return vq(e.proposedPlanIdsByThreadId[t],e.proposedPlanByThreadId[t]??EYe,SYe)}function MYe(e,t){return vq(e.turnDiffIdsByThreadId[t],e.turnDiffSummaryByThreadId[t]??DYe,CYe)}function yq(e,t){let n=e.threadShellById[t];if(!n)return;let r=e.threadSessionById[t]??null,i=e.threadTurnStateById[t],a=e.threadRateLimitStatusById[t]??OYe,o=kYe(e,t),s=AYe(e,t),c=jYe(e,t),l=MYe(e,t),u=_q.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 _q.set(n,{session:r,turnState:i,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l,thread:d}),d}function NYe(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 bq(e){return{settledAt:e.settledAt??null,settledOverride:e.settledOverride??null}}var xq={projectIds:[],projectById:{},threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:{},messageIdsByThreadId:{},messageByThreadId:{},activityIdsByThreadId:{},activityByThreadId:{},proposedPlanIdsByThreadId:{},proposedPlanByThreadId:{},turnDiffIdsByThreadId:{},turnDiffSummaryByThreadId:{},sidebarThreadSummaryById:{},threadSubscriptionErrorById:{},bootstrapComplete:!1},PYe={activeEnvironmentId:null,environmentStateById:{}},Sq=[],Cq=[];function wq(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Tq(e,t){return{id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:uq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,session:e.session?fq(e.session):null,messages:e.messages.map(e=>pq(t,e)),proposedPlans:e.proposedPlans.map(mq),error:oG(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...bq(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan,branch:e.branch,worktreePath:e.worktreePath,turnDiffSummaries:e.checkpoints.map(hq),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 Eq(e,t){let n={id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:uq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:oG(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...bq(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?fq(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,...bq(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 FYe(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 IYe(e){return{latestTurn:e.latestTurn,...e.pendingSourceProposedPlan?{pendingSourceProposedPlan:e.pendingSourceProposedPlan}:{}}}function Dq(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.threadId===t.threadId&&e.planId===t.planId}function Oq(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&&Dq(e.sourceProposedPlan,t.sourceProposedPlan)}function kq(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 Aq(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 jq(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.title===t.title&&Mq(e.titleRegeneration,t.titleRegeneration)&&e.interactionMode===t.interactionMode&&kq(e.session,t.session)&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&Oq(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&&Aq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status}function Mq(e,t){return e===t?!0:e==null||t==null?!1:e.requestId===t.requestId&&e.startedAt===t.startedAt}function Nq(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&&Aq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status&&e.goal===t.goal&&Mq(e.titleRegeneration,t.titleRegeneration)}function Pq(e,t){return e!==void 0&&Oq(e.latestTurn,t.latestTurn)&&Dq(e.pendingSourceProposedPlan,t.pendingSourceProposedPlan)}function LYe(e,t){return e.includes(t)?[...e]:[...e,t]}function Fq(e,t){return e.filter(e=>e!==t)}function RYe(e){return{ids:e.messages.map(e=>e.id),byId:Object.fromEntries(e.messages.map(e=>[e.id,e]))}}function zYe(e){return{ids:e.activities.map(e=>e.id),byId:Object.fromEntries(e.activities.map(e=>[e.id,e]))}}function BYe(e){return{ids:e.proposedPlans.map(e=>e.id),byId:Object.fromEntries(e.proposedPlans.map(e=>[e.id,e]))}}function VYe(e){return{ids:e.turnDiffSummaries.map(e=>e.turnId),byId:Object.fromEntries(e.turnDiffSummaries.map(e=>[e.turnId,e]))}}function HYe(e){return e.projectIds.flatMap(t=>{let n=e.projectById[t];return n?[n]:[]})}function Iq(e){return e.threadIds.flatMap(t=>{let n=yq(e,t);return n?[n]:[]})}function Lq(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]??Sq,i=Fq(n,t);if(i.length===0){let{[r]:t,...n}=e;e=n}else wq(n,i)||(e={...e,[r]:i})}let a=e[n]??Sq,o=LYe(a,t);wq(a,o)||(e={...e,[n]:o}),e!==i.threadIdsByProjectId&&(i={...i,threadIdsByProjectId:e})}return i}function Rq(e,t,n){let r=FYe(t),i=IYe(t),a=e.threadShellById[t.id],o=e.threadTurnStateById[t.id],s=Lq(e,t.id,t.projectId,n?.projectId);Nq(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};jq(c,e)||(s={...s,sidebarThreadSummaryById:{...s.sidebarThreadSummaryById,[t.id]:e}})}if(kq(n?.session??null,t.session)||(s={...s,threadSessionById:{...s.threadSessionById,[t.id]:t.session}}),(n?.rateLimitStatus??Cq)!==(t.rateLimitStatus??Cq)&&(s={...s,threadRateLimitStatusById:{...s.threadRateLimitStatusById,[t.id]:t.rateLimitStatus??Cq}}),Pq(o,i)||(s={...s,threadTurnStateById:{...s.threadTurnStateById,[t.id]:i}}),n?.messages!==t.messages){let e=RYe(t);s={...s,messageIdsByThreadId:{...s.messageIdsByThreadId,[t.id]:e.ids},messageByThreadId:{...s.messageByThreadId,[t.id]:e.byId}}}if(n?.activities!==t.activities){let e=zYe(t);s={...s,activityIdsByThreadId:{...s.activityIdsByThreadId,[t.id]:e.ids},activityByThreadId:{...s.activityByThreadId,[t.id]:e.byId}}}if(n?.proposedPlans!==t.proposedPlans){let e=BYe(t);s={...s,proposedPlanIdsByThreadId:{...s.proposedPlanIdsByThreadId,[t.id]:e.ids},proposedPlanByThreadId:{...s.proposedPlanByThreadId,[t.id]:e.byId}}}if(n?.turnDiffSummaries!==t.turnDiffSummaries){let e=VYe(t);s={...s,turnDiffIdsByThreadId:{...s.turnDiffIdsByThreadId,[t.id]:e.ids},turnDiffSummaryByThreadId:{...s.turnDiffSummaryByThreadId,[t.id]:e.byId}}}return s}function zq(e,t){let n=e.threadShellById[t.shell.id],r=Lq(e,t.shell.id,t.shell.projectId,n?.projectId);return Nq(n,t.shell)||(r={...r,threadShellById:{...r.threadShellById,[t.shell.id]:t.shell}}),kq(e.threadSessionById[t.shell.id]??null,t.session)||(r={...r,threadSessionById:{...r.threadSessionById,[t.shell.id]:t.session}}),Pq(e.threadTurnStateById[t.shell.id],t.turnState)||(r={...r,threadTurnStateById:{...r.threadTurnStateById,[t.shell.id]:t.turnState}}),jq(e.sidebarThreadSummaryById[t.shell.id],t.summary)||(r={...r,sidebarThreadSummaryById:{...r.sidebarThreadSummaryById,[t.shell.id]:t.summary}}),r}function Bq(e,t){return Object.fromEntries(Object.entries(e).flatMap(([e,n])=>t.has(e)?[[e,n]]:[]))}function Vq(e,t){let n=e.threadShellById[t],r=e.sidebarThreadSummaryById[t],i=n?.projectId??r?.projectId;if(!i)return e;let a=Fq(e.threadIds,t),o=Fq(e.threadIdsByProjectId[i]??Sq,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 UYe(e,t){let n=new Set(e.threadIdsByProjectId[t]??Sq);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 Hq(e,t){let n=UYe(e,t);if(!e.projectById[t]&&n.length===0&&!e.projectIds.includes(t))return e;let r=e;for(let e of n)r=Vq(r,e);let{[t]:i,...a}=r.projectById;return{...r,projectById:a,projectIds:Fq(r.projectIds,t)}}function Uq(e){return e===`error`?`error`:e===`missing`?`interrupted`:`completed`}function WYe(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 Wq(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 Gq(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 GYe(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 KYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function qYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function Kq(e,t,n){let r=yq(e,t);if(!r)return e;let i=n(r);return i===r?e:Rq(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 JYe(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]??xq}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 YYe(e,t,n){let r=t.projects.map(e=>lq(e,n)),i=new Set(t.threads.map(e=>e.id)),a={...e,...JYe(r),threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:Bq(e.threadRateLimitStatusById,i),sidebarThreadSummaryById:{},messageIdsByThreadId:Bq(e.messageIdsByThreadId,i),messageByThreadId:Bq(e.messageByThreadId,i),activityIdsByThreadId:Bq(e.activityIdsByThreadId,i),activityByThreadId:Bq(e.activityByThreadId,i),proposedPlanIdsByThreadId:Bq(e.proposedPlanIdsByThreadId,i),proposedPlanByThreadId:Bq(e.proposedPlanByThreadId,i),turnDiffIdsByThreadId:Bq(e.turnDiffIdsByThreadId,i),turnDiffSummaryByThreadId:Bq(e.turnDiffSummaryByThreadId,i),bootstrapComplete:!0};for(let e of t.threads)a=zq(a,Eq(e,n));return a}function XYe(e,t,n){return Yq(e,n,YYe(Jq(e,n),t,n))}function ZYe(e,t,n){let r=Jq(e,n),i=yq(r,t.id);return Yq(e,n,Rq(r,Tq(t,n),i))}function QYe(e,t,n,r){let i=Jq(e,t);return Yq(e,t,{...i,threadSubscriptionErrorById:{...i.threadSubscriptionErrorById,[n]:r}})}function $Ye(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=lq({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=gYe(n,t.payload);return{...e,projectById:{...e.projectById,[t.payload.projectId]:r}}}case`project.deleted`:return Hq(e,t.payload.projectId);case`thread.created`:{let r=yq(e,t.payload.threadId);return Rq(e,Tq({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 Vq(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:uq(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:uq(t.payload.modelSelection)},runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,pendingSourceProposedPlan:t.payload.sourceProposedPlan,latestTurn:Wq({previous:e.latestTurn,turnId:gn.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:Wq({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=pq(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?Gq(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)?Wq({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:fq(t.payload.session),error:oG(t.payload.session.lastError),latestTurn:t.payload.session.status===`running`&&t.payload.session.activeTurnId!==null?Wq({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=mq(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=hq({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?Wq({previous:e.latestTurn,turnId:t.payload.turnId,state:Uq(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=GYe(e.messages,r,t.payload.turnCount).slice(-2e3),a=qYe(e.proposedPlans,r).slice(-200),o=KYe(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:Uq(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(WYe).slice(-500);return{...e,activities:n,updatedAt:t.occurredAt}});case`thread.rate-limit-set`:return Kq(e,t.payload.threadId,e=>({...e,rateLimitStatus:NYe(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=lq(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 Hq(e,t.projectId);case`thread-upserted`:return zq(e,Eq(t.thread,n));case`thread-removed`:return Vq(e,t.threadId)}}function tXe(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):xq}function nXe(e,t){return Iq(Qq(e,t))}function $q(e){return Zq(e).flatMap(([,e])=>HYe(e))}function eJ(e){return Zq(e).flatMap(([,e])=>Iq(e))}function rXe(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 iXe(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]??Sq;return(r.length>0?r:tJ(n)).flatMap(e=>{let r=nJ(t.environmentId,n,e);return!r||r.projectId!==t.projectId?[]:[r]})}function aXe(e,t){return t.length===0?[]:t.length===1?rJ(e,t[0]):t.flatMap(t=>rJ(e,t))}function oXe(e){return e.activeEnvironmentId===null?Object.values(e.environmentStateById).some(e=>e.bootstrapComplete):Qq(e,e.activeEnvironmentId).bootstrapComplete}function sXe(e,t){return t?Qq(e,t.environmentId).projectById[t.projectId]:void 0}function iJ(e,t){return t?yq(Qq(e,t.environmentId),t.threadId):void 0}function cXe(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 lXe(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 uXe(e,t,n){return Yq(e,n,Xq(Jq(e,n),t,n))}function dXe(e,t,n){return Yq(e,n,eXe(Jq(e,n),t,n))}function fXe(e,t){return e.activeEnvironmentId===t?e:{...e,activeEnvironmentId:t}}function pXe(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=Xt(e=>({...PYe,setActiveEnvironmentId:t=>e(e=>fXe(e,t)),syncServerShellSnapshot:(t,n)=>e(e=>XYe(e,t,n)),syncServerThreadDetail:(t,n)=>e(e=>ZYe(e,t,n)),setThreadSubscriptionError:(t,n,r)=>e(e=>QYe(e,t,n,r)),clearThreadSubscriptionError:(t,n)=>e(e=>$Ye(e,t,n)),applyOrchestrationEvent:(t,n)=>e(e=>uXe(e,t,n)),applyOrchestrationEvents:(t,n)=>e(e=>tXe(e,t,n)),applyShellEvent:(t,n)=>e(e=>dXe(e,t,n)),setError:(t,n)=>e(e=>lXe(e,t,n)),setThreadBranch:(t,n,r)=>e(e=>pXe(e,t,n,r))})),sJ=`Thread not found or you no longer have access.`;function mXe(e){if(e==null)return sJ;let t=$K(ote(e)?Ie(e):e,sJ);return/\bnot found\b/i.test(t)?sJ:t}function hXe(e,t,n){oJ.getState().setThreadSubscriptionError(e,t,mXe(n))}function cJ(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var gXe={enabled:!0,leading:!0,trailing:!0,wait:0},_Xe=class{#e;constructor(e,t){this.fn=e,this.store=new Tte(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`}}),bte(`Throttler`,this)},this.#n=()=>!!Yt(this.options.enabled,this),this.#r=()=>Yt(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={...gXe,...t},this.#t(this.options.initialState??{}),this.key&&Cte.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 vXe(e){return!!(e.prompt.trim()||e.images.length||e.terminalContexts.length||e.persistedAttachments.length||e.stagedSubmission)}function yXe(e,t,n){let r=Vo(t),i=Vo(n);if(r===i)return e;let a=e[r];if(!a)return e;let o=e[i];if(o&&vXe(o)&&!bXe(a,o))return null;let s={...e,[i]:{...a,...OXe(a,o)}};return delete s[r],s}function bXe(e,t){let n=e.stagedSubmission;return!n||!xXe(n)||!SXe(e,n)||!CXe(n,t.stagedSubmission)?!1:wXe(e,t)}function xXe(e){return!!e.commandId&&!!e.messageId}function SXe(e,t){return[e.prompt===t.prompt,uJ(e.persistedAttachments,t.attachments),uJ(e.terminalContexts,t.terminalContexts)].every(Boolean)}function CXe(e,t){return!t||TXe(e,t)}function wXe(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),DXe(e.modelSelectionByProvider,t.modelSelectionByProvider),e.activeProvider===t.activeProvider,e.runtimeMode===t.runtimeMode,e.interactionMode===t.interactionMode].every(Boolean)}function TXe(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),EXe(e.executionIntent,t.executionIntent)].every(Boolean)}function lJ(e,t){return e===void 0||t===void 0||JSON.stringify(e)===JSON.stringify(t)}function EXe(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 DXe(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 OXe(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`,kXe=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,AXe=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function gJ(e){return e.replace(/\r\n/g,`
1006
- `).replace(/^\n+|\n+$/g,``)}function _J(e){return gJ(e.text).length>0}function jXe(e){return!_J(e)}function MXe(e){return e.filter(e=>_J(e))}function NXe(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 PXe(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function vJ(e){return`${e.terminalLabel} ${PXe(e)}`}function yJ(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function FXe(e){return gJ(e.text).split(`
1007
- `).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function IXe(e){let t=e.map(e=>NXe(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(...FXe(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
1008
- `)}function LXe(e,t){let n=0,r=``;for(let i of e){if(i!==``){r+=i;continue}let e=t[n]??null;n+=1,e&&(r+=yJ(e))}return r}function RXe(e,t){let n=LXe(e,t).trim(),r=IXe(t);return r.length===0?n:n.length>0?`${n}\n\n${r}`:r}function zXe(e){let t=kXe.exec(e);if(!t)return{promptText:e,contextCount:0,previewTitle:null,contexts:[]};let n=e.slice(0,t.index).replace(/\n+$/,``),r=HXe(t[1]??``);return{promptText:n,contextCount:r.length,previewTitle:r.length>0?r.map(({header:e,body:t})=>t.length>0?`${e}\n${t}`:e).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=JW(e)),e.stackParser===void 0&&(e.stackParser=WW),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=qW),delete e.initialScope,t(e)}var XW=e({BrowserClient:()=>TR,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>gMe,OpenFeatureIntegrationHook:()=>hKe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>vA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>yA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>_A,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>gA,Scope:()=>eA,addBreadcrumb:()=>QN,addEventProcessor:()=>VM,addIntegration:()=>ZM,bindScopeToEmitter:()=>WAe,breadcrumbsIntegration:()=>nB,browserApiErrorsIntegration:()=>rB,browserProfilingIntegration:()=>oKe,browserSessionIntegration:()=>aB,browserTracingIntegration:()=>fW,buildLaunchDarklyFlagUsedHandler:()=>pKe,captureConsoleIntegration:()=>GMe,captureEvent:()=>IM,captureException:()=>PM,captureFeedback:()=>zP,captureMessage:()=>FM,captureSession:()=>GM,chromeStackLineParser:()=>$z,consoleLoggingIntegration:()=>YNe,contextLinesIntegration:()=>XBe,continueTrace:()=>jAe,createConsolaReporter:()=>QNe,createLangChainCallbackHandler:()=>pI,createTransport:()=>yN,createUserFeedbackEnvelope:()=>eBe,dedupeIntegration:()=>vP,defaultRequestInstrumentationOptions:()=>nW,defaultStackParser:()=>WW,elementTimingIntegration:()=>hze,endSession:()=>UM,eventFiltersIntegration:()=>tP,eventFromException:()=>xR,eventFromMessage:()=>SR,eventLoopBlockIntegration:()=>OKe,exceptionFromError:()=>_R,extraErrorDataIntegration:()=>QMe,featureFlagsIntegration:()=>INe,feedbackAsyncIntegration:()=>QLe,feedbackIntegration:()=>gR,feedbackSyncIntegration:()=>gR,fetchStreamPerformanceIntegration:()=>sW,forceLoad:()=>MBe,functionToStringIntegration:()=>eP,getAbsoluteUrl:()=>zze,getActiveSpan:()=>hj,getClient:()=>X,getCurrentScope:()=>dA,getDefaultIntegrations:()=>JW,getFeedback:()=>aLe,getGlobalScope:()=>pA,getIsolationScope:()=>fA,getReplay:()=>KWe,getRootSpan:()=>pj,getSpanDescendants:()=>fj,getSpanStatusFromHttpCode:()=>EA,getTraceData:()=>ZN,globalHandlersIntegration:()=>sB,graphqlClientIntegration:()=>iVe,growthbookIntegration:()=>vKe,httpClientIntegration:()=>RBe,httpContextIntegration:()=>fB,inboundFiltersIntegration:()=>nP,init:()=>YW,instrumentAnthropicAiClient:()=>mFe,instrumentCreateReactAgent:()=>QFe,instrumentGoogleGenAIClient:()=>EFe,instrumentLangChainEmbeddings:()=>VFe,instrumentLangGraph:()=>$Fe,instrumentOpenAiClient:()=>YPe,instrumentOutgoingRequests:()=>rW,instrumentSupabaseClient:()=>AP,isBotUserAgent:()=>dW,isEnabled:()=>BM,isInitialized:()=>Eje,lastEventId:()=>zM,launchDarklyIntegration:()=>fKe,linkedErrorsIntegration:()=>pB,logger:()=>xIe,makeRendererTransport:()=>qW,metrics:()=>OIe,moduleMetadataIntegration:()=>HMe,normalizeStringifyValue:()=>mB,onLoad:()=>NBe,openFeatureIntegration:()=>mKe,parameterize:()=>XN,registerSpanErrorInstrumentation:()=>vj,registerWebWorker:()=>CKe,replayCanvasIntegration:()=>dGe,replayIntegration:()=>EU,reportPageLoaded:()=>NGe,reportingObserverIntegration:()=>IBe,rewriteFramesIntegration:()=>oNe,scopeToMainIntegration:()=>KW,sendFeedback:()=>qI,setActiveSpanInBrowser:()=>PGe,setAttribute:()=>wje,setAttributes:()=>Cje,setContext:()=>LM,setConversationId:()=>Tje,setCurrentClient:()=>RN,setExtra:()=>bje,setExtras:()=>yje,setHttpStatus:()=>DA,setMeasurement:()=>Bj,setTag:()=>Sje,setTags:()=>xje,setUser:()=>RM,showReportDialog:()=>gB,spanStreamingIntegration:()=>FGe,spanToBaggageHeader:()=>pAe,spanToJSON:()=>$A,spanToTraceHeader:()=>JA,spotlightBrowserIntegration:()=>dKe,startBrowserTracingNavigationSpan:()=>mW,startBrowserTracingPageLoadSpan:()=>pW,startInactiveSpan:()=>Qj,startNewTrace:()=>tM,startSession:()=>HM,startSpan:()=>Xj,startSpanManual:()=>Zj,statsigIntegration:()=>yKe,supabaseIntegration:()=>bNe,suppressTracing:()=>MAe,thirdPartyErrorFilterIntegration:()=>kNe,uiProfiler:()=>Wze,unleashIntegration:()=>gKe,updateSpanName:()=>cAe,viewHierarchyIntegration:()=>aVe,webVitalsIntegration:()=>cW,webWorkerIntegration:()=>xKe,withActiveSpan:()=>$j,withIsolationScope:()=>jke,withScope:()=>mA,withStreamedSpan:()=>mAe,zodErrorsIntegration:()=>ONe}),AKe=100,jKe=5,MKe=[`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 ZW(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function NKe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),ZW(e.extra),ZW(e.tags)}function PKe(e){let t=$W(e.version)??`0.0.0`,n=$W(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function QW(e,t){for(let n of t){let t=$W(e[n]);if(t)return t}}function FKe(e){return eG(e.enabled)??e.defaultEnabled??!1}function IKe(e){let t=$W(e.dsn);return!t||FKe(e)===!1?null:{dsn:t,environment:$W(e.environment)??$W(e.defaultEnvironment)??`production`,release:$W(e.release)??$W(e.defaultRelease)??void 0,debug:eG(e.debug)??e.defaultDebug??!1,tracesSampleRate:nG(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:tG(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:tG(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:tG(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:AKe,normalizeDepth:jKe,tags:LKe(e)}}function LKe(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=$W(r);e&&(t[n]=e)}return t}function $W(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function eG(e){if(typeof e==`boolean`)return e;let t=$W(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function tG(e,t){if(t!==void 0||e!==void 0)return nG(e,t??0)}function nG(e,t){let n=RKe(e);return n===null||n<0||n>1?t:n}function RKe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=$W(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}function zKe(e){let t=(0,cl.c)(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=Zt(hl,`bg-background text-foreground`),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=Zt(pl,`pl-1 md:pl-2.5`),t[1]=r):r=t[1];let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Nr.jsx)(_l,{}),t[2]=i):i=t[2];let a;t[3]===e.onGoToNewChat?a=t[4]:(a=(0,Nr.jsx)(`div`,{className:r,children:(0,Nr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:e.onGoToNewChat,className:`${ml} 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,Nr.jsx)(`div`,{}),t[5]=o):o=t[5];let s;t[6]===a?s=t[7]:(s=(0,Nr.jsxs)(`header`,{className:fl,children:[a,o]}),t[6]=a,t[7]=s);let c;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Nr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Nr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Nr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Nr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Nr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:BKe,type:`button`,children:`Reload app`})]})}),t[8]=c):c=t[8];let l;return t[9]===s?l=t[10]:(l=(0,Nr.jsxs)(`div`,{className:n,children:[s,c]}),t[9]=s,t[10]=l),l}function BKe(){return window.location.reload()}var VKe=[/\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],HKe=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function rG(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 UKe(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 WKe(e){if(!e)return null;let t=e.toLowerCase(),n=UKe(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.`:rG(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 GKe(e){return e?VKe.some(t=>t.test(e)):!1}function iG(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:GKe(n)?WKe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var KKe=[/\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 aG(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&KKe.some(e=>e.test(t))}function oG(e){return aG(e)?null:iG(e,{fallback:HKe})}var sG=`forge-web`,cG=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],lG=[`VITE_SENTRY_RELEASE`],qKe=[`VITE_SENTRY_DSN`],JKe=[`VITE_SENTRY_DEBUG`],YKe=[`VITE_SENTRY_ENABLED`],XKe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],ZKe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],QKe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],$Ke=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],eqe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],uG=!1,dG={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 tqe(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 nqe(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 rqe(e){return tqe(e).some(aG)||nqe(e)}function iqe(){let e=new URL(window.location.href);Pr?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function aqe(){let e=Pr?`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:`490879f4e6247cf933d524a1e84b36966d2d3111`,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+490879f4e6247cf933d524a1e84b36966d2d3111`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=QW(t,[...lG])??PKe({appName:sG,version:`0.13.4`,commitHash:QW(t,[...eqe])});return IKe({appName:sG,runtime:e,defaultEnvironment:QW(t,[...cG])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:QW(t,[...YKe]),dsn:QW(t,[...qKe]),environment:QW(t,[...cG]),release:QW(t,[...lG]),debug:QW(t,[...JKe]),tracesSampleRate:QW(t,[...XKe]),profilesSampleRate:QW(t,[...ZKe]),replaysSessionSampleRate:QW(t,[...QKe]),replaysOnErrorSampleRate:QW(t,[...$Ke]),tags:{platform:Pr?`desktop`:`web`}})}function fG(e){return NKe(e),rqe(e)?null:e}function oqe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function pG(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...MKe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...oqe(e)}}function sqe(e){let t=[];e.tracesSampleRate>0&&t.push(fW()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(EU());let n=gR(dG);t.push(n);try{YW({...pG(e),beforeSend:e=>fG(e),integrations:t})}catch{return null}return uG=!0,XW}function cqe(e){let t=[];e.tracesSampleRate>0&&t.push(pE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(DT());let n=ub(dG);t.push(n);try{qE({...pG(e),beforeSend:e=>fG(e),integrations:t})}catch{return null}return uG=!0,xO}function mG(){if(uG)return Pr?XW:xO;let e=aqe();return e?Pr?sqe(e):cqe(e):null}function hG(e){if(mG()){if(Pr){RM(e);return}Em(e)}}function gG(e,t,n){if(!mG())return;let r=lqe(e);if(Pr){mA(e=>{t&&e.setTags(t);let i=PM(r);n?.showReportDialog&&gB({eventId:i})});return}Ud(e=>{t&&e.setTags(t);let i=Sm(r);n?.showReportDialog&&gS({eventId:i})})}function lqe(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 uqe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){gG(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Nr.jsx)(zKe,{onGoToNewChat:iqe}):this.props.children}},_G=!1,vG=!1,yG=null,bG=null,xG=null,SG=!1,CG=new Set;function dqe(e){if(_G||vG)return;if(!e.publicKey||!e.host){vG=!0;return}if(yG)return;if(typeof window>`u`||typeof location>`u`){vG=!0;return}let t=e.publicKey,n=e.host;yG=N(async()=>{let{default:e}=await import(`./module-CPO4cjSm.js`);return{default:e}},[]).then(({default:e})=>{bG=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{_G=!0,xG&&wG(xG),TG(),CG.forEach(e=>e())}})}).catch(()=>{vG=!0,bG=null})}function wG(e){if(xG=e,!_G||!bG)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),bG.identify(e.cmmdUserId,t)}function fqe(e){return!_G||!bG?!1:bG.isFeatureEnabled(e)===!0}function TG(){!bG||SG||(SG=!0,bG.onFeatureFlags(()=>{CG.forEach(e=>e())}))}function pqe(e){return CG.add(e),_G&&bG&&(TG(),e()),()=>{CG.delete(e)}}var EG=`/api/cmmd/auth-runtime`;function mqe(e){return P({method:`POST`,path:EG},e)}function hqe(e){return P({method:`GET`,path:EG},e)}function gqe(e){return P({method:`DELETE`,path:EG},e)}function _qe(e){return P({method:`POST`,path:`${EG}/connect`},e)}function vqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing`,...t?.organizationId===void 0?{}:{query:{orgId:t.organizationId}}},e)}function yqe(e,t){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:t.timeZone}},e)}var DG=`/api/cmmd/providers/codex/credential`,OG=`/api/cmmd/providers/claude/credential`;function bqe(e){return P({method:`GET`,path:DG},e)}function xqe(e){return P({method:`DELETE`,path:DG},e)}function Sqe(e){return P({method:`GET`,path:OG},e)}function Cqe(e){return P({method:`DELETE`,path:OG},e)}function wqe(e,t){return P({method:`DELETE`,path:`/api/cmmd/providers/accounts/${encodeURIComponent(String(t))}`},e)}function Tqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/disposition`}function Eqe(e,t,n,r,i){return P({method:`PUT`,path:Tqe(t,n,r),body:i},e)}function Dqe(e){return(t,n,r,i)=>Eqe(e,t,n,r,i)}function Oqe(e,t,n){return`/api/cmmd/threads/${encodeURIComponent(e)}/${encodeURIComponent(t)}/${encodeURIComponent(n)}/archive`}function kqe(e,t,n,r,i){return P({method:`POST`,path:Oqe(t,n,r),body:i},e)}function Aqe(e){return(t,n,r,i)=>kqe(e,t,n,r,i)}function jqe(e){return typeof e==`object`&&!!e&&`status`in e&&e.status===409}async function Mqe(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(!jqe(n))throw n;let r=await e.refresh();return e.submit({...t,expectedRevision:r.revision})}}function Nqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/forge-runtimes/${encodeURIComponent(t)}/rename`,body:{displayName:n}},e)}function Pqe(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/rename`,body:{displayName:n}},e)}function Fqe(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/revoke`},e)}function kG(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var Iqe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},Lqe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},AG=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function jG(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 MG(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 NG(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 PG(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 Rqe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function FG(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 IG(e){let t=`${PG(e,`firstName`)??``} ${PG(e,`lastName`)??``}`.trim()||PG(e,`username`)||PG(e,`email`)||`Unknown`;return{id:FG(e,`userId`)??FG(e,`id`)??t,name:t,email:PG(e,`email`),role:PG(e,`role`),avatarUrl:PG(e,`profileImage`)??PG(e,`avatar`)}}function zqe(e){let t=RG(e,`user`)??e;return IG({...typeof t==`object`&&t?t:{},userId:FG(e,`userId`)??FG(t,`id`),role:PG(e,`role`)})}function LG(e){let t=PG(e,`authorFirstName`)??``,n=PG(e,`authorLastName`)??``,r=PG(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:FG(e,`id`)??``,status:i,body:PG(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:PG(e,`authorProfileImage`)??null,createdAt:PG(e,`createdAt`)??``,updatedAt:PG(e,`updatedAt`)??PG(e,`createdAt`)??``,canEdit:Rqe(e,`canEdit`)??!1}}function Bqe(e,t,n){let r=Array.isArray(e.data)?e.data.map(LG):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function RG(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var Vqe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function zG(e,t){let n=RG(e,t);if(!n)return null;for(let e of Vqe){let t=PG(n,e);if(t)return t}return null}function BG(e,t){let n=RG(e,t);return n?FG(n,`id`):null}function VG(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function Hqe(e){let t={...e,id:FG(e,`id`)??e.id,title:e.title??PG(e,`name`)??``},n=FG(e,`workspaceId`)??FG(e,`workspace_id`)??BG(e,`workspace`)??e.workspaceId??null;return n!==null||VG(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??PG(e,`start_date`)??null,endDate:e.endDate??PG(e,`end_date`)??null}:t}function HG(e){let t=e.ownerAvatarUrl??PG(e,`owner_avatar_url`)??PG(e,`ownerProfileImage`)??PG(e,`owner_profile_image`)??PG(e,`ownerImage`)??PG(e,`owner_image`)??PG(e,`ownerImageUrl`)??PG(e,`owner_image_url`)??PG(e,`createdByAvatarUrl`)??PG(e,`created_by_avatar_url`)??PG(e,`createdByProfileImage`)??PG(e,`created_by_profile_image`)??zG(e,`owner`)??zG(e,`createdBy`)??zG(e,`created_by`)??null,n={...e,id:FG(e,`id`)??e.id},r=FG(e,`campaignId`)??FG(e,`campaign_id`)??BG(e,`campaign`)??e.campaignId??null;(r!==null||VG(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??PG(e,`campaignTitle`)??PG(e,`campaign_title`)??PG(RG(e,`campaign`),`title`)??PG(RG(e,`campaign`),`name`)??null;(i!==null||VG(e,`campaignTitle`))&&(n.campaignTitle=i);let a=FG(e,`workspaceId`)??FG(e,`workspace_id`)??BG(e,`workspace`)??e.workspaceId??null;(a!==null||VG(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??PG(e,`workspace_name`)??PG(RG(e,`workspace`),`name`)??null;(o!==null||VG(e,`workspaceName`))&&(n.workspaceName=o);let s=PG(e,`workspaceIconUrl`)??PG(e,`workspace_icon_url`)??PG(RG(e,`workspace`),`iconUrl`)??null;(s!==null||VG(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=FG(e,`ownerId`)??FG(e,`owner_id`)??BG(e,`owner`)??e.ownerId??null;(c!==null||VG(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??PG(e,`owner_name`)??PG(RG(e,`owner`),`name`)??null;(l!==null||VG(e,`ownerName`))&&(n.ownerName=l),(t!==null||VG(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=FG(e,`teamId`)??FG(e,`team_id`)??BG(e,`team`)??e.teamId??null;(u!==null||VG(e,`teamId`))&&(n.teamId=u);let d=e.teamName??PG(e,`team_name`)??PG(RG(e,`team`),`name`)??null;(d!==null||VG(e,`teamName`))&&(n.teamName=d);let f=e.startDate??PG(e,`start_date`)??null;(f!==null||VG(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??PG(e,`target_end_date`)??null;return(p!==null||VG(e,`targetEndDate`))&&(n.targetEndDate=p),n}function UG(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 Uqe(e){return UG(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 Wqe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function WG(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function GG(e){try{return await e}catch(e){throw e instanceof gr?e.kind===`auth`?new Iqe(e.message):new Lqe(e.message,e.status??502):e}}var KG=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?or:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??hr,...t?{resolveBearerToken:()=>mr()?.bearerToken??null}:{}},this.putThreadDisposition=Dqe(this.cfg),this.postThreadArchive=Aqe(this.cfg)}async getTask(e){return GG(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 GG(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await GG(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await GG(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return GG(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return GG(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return GG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await GG(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return GG(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=rn(_ne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return UG(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return Uqe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return UG(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),GG(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return GG(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 GG(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 GG(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 gr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of ene){let r=t[e];r!==void 0&&(n[e]=sne[e]===`nullableId`?WG(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),GG(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 vqe(this.cfg,e)}getBillingSeries(e){return yqe(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 mqe(this.cfg)}getAuthRuntimeState(){return hqe(this.cfg)}destroyAuthRuntime(){return gqe(this.cfg)}connectAuthRuntime(){return _qe(this.cfg)}getUserCodexCredential(){return bqe(this.cfg)}disconnectUserCodexCredential(){return xqe(this.cfg)}getUserClaudeCredential(){return Sqe(this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(e){return wqe(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 Cqe(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 Nqe(this.cfg,e,t)}renameDevice(e,t){return Pqe(this.cfg,e,t)}revokeDevice(e){return Fqe(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`),jG(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map(Hqe)}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`),jG(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(HG)}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 HG(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(IG):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map(zqe):[]}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 Bqe(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 LG(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return LG(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 MG(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return MG(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 MG(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=NG(t);return MG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=NG(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=NG(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=NG(t,t?.taskId);return MG(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=NG(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=NG(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=NG(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=NG(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=NG(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=NG(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 spawnForgeThreadFromBoardTask(e,t){return P({method:`POST`,path:`/api/cmmd/projects/${e}/board/${t}/spawn-forge-thread`,body:{}},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:kG(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:kG(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new AG(`createSubtask`)}async createBoardTask(e){throw new AG(`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=WG(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=WG(e.organizationId)),Wqe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:WG(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=WG(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 AG(`uploadBrainDoc`)}};function qG(e){return new KG(e)}var JG=new KG({onAuthExpired:hr}),YG=class extends $t(`BootstrapHttpError`){},XG=e=>nee(e,`BootstrapHttpError`);function ZG(e){return typeof e!=`object`||!e?!1:!!(XG(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof gr&&e.kind===`auth`)}function Gqe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function QG(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new YG({message:`${t} returned a non-JSON response (${Gqe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function $G(e={resolveUrl:or}){let t=mr()?.bearerToken;return t?{...e,bearerToken:t}:e}var eK=null,tK=null,nK=null,rK=new Set,iK=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function Kqe(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();hG({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),wG({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function aK(){if(typeof window>`u`||nK)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(nK=e(e=>{eK=null,tK=null,e.sessionLifecycle.status!==`ready`&&hG(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&Ane().catch(e=>{gG(e,{route:`desktop-auth-session-expired`})})}))}function qqe(){return Gl(new URL(window.location.href))}function oK(){let e=new URL(window.location.href),t=ple(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function Jqe(){return hK(async()=>{let e=or(`/api/auth/session`),t=async()=>{let t=await fetch(e,ur({credentials:`include`}));if(!t.ok)throw new YG({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return QG(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 Mne()?t():n})}async function Yqe(e,t){return await e.text()||t}var sK=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function Xqe(e){return hK(async()=>{let t={credential:e},n=or(`/api/auth/bootstrap`),r=await fetch(n,ur({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new YG({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return QG(r,n)})}function cK(e){return new URL(e,window.location.origin).toString()}function lK(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function uK(){return typeof window>`u`?null:lK(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function Zqe(){return typeof window>`u`?!1:Nne()===`session-expired`}function dK(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(iK),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function fK(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(iK);return}window.sessionStorage.setItem(iK,JSON.stringify([...e]))}catch{}}function Qqe(){let e=uK();if(!e)return;let t=new Set(dK());t.add(e),fK(t)}function $qe(e){return dK().has(e)}function pK(){let e=uK();if(!e){fK(new Set);return}let t=new Set(dK());t.delete(e),fK(t)}async function mK(){let e=cK(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?QG(t,e):null}async function eJe(e){if(typeof window>`u`)return;let t=lK(e);if(!t||Zqe()||rK.has(t)||$qe(t))return;if((await mK().catch(()=>null))?.authenticated){rK.add(t);return}let n=cK(`/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 YG({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await QG(r,n),rK.add(t)}async function tJe(){let e=await Jqe();if(e.authenticated)return e;let t=mr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await mK().catch(()=>null);return n?.authenticated?n:e}var nJe=new Set([404,502,503,504]),rJe=15e3,iJe=500;function aJe(e){mr()?.source===`paired-bearer`&&ZG(e)&&dr(`http`)}async function hK(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(aJe(e),!sJe(e))throw e;if(Date.now()-t>=rJe)throw gG(e,{route:`bootstrap-retry-exhausted`}),e;await oJe(iJe)}}function oJe(e){return new Promise(t=>{setTimeout(t,e)})}function sJe(e){return XG(e)?nJe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function cJe(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 lJe(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return cJe(await t(),e)}catch(e){return gG(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function uJe(e,t){return hG(null),jne(t),await sr().catch(e=>{gG(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Pne(t)??`Forge Desktop requires CMMD authentication.`}}async function dJe(){let e=await tJe();if(e.authenticated){if(e.cmmdIdentity){let t=await lJe(e.cmmdIdentity);return t?(fr(),uJe(e,t)):(fr(),Kqe(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function fJe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);tK=null,pK(),await Xqe(t),eK=null,oK()}function gK(){pK(),tK=null,eK=null}async function _K(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=or(`/api/auth/bootstrap/command`),s=await fetch(o,ur({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 YG({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await QG(s,o),gK()}async function pJe(){let e=or(`/api/auth/ws-token`),t=await fetch(e,ur({credentials:`include`,method:`POST`}));if(!t.ok)throw new YG({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return QG(t,e)}async function mJe(e){let t=await pJe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function hJe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=or(`/api/auth/pairing-token`),a=await fetch(i,ur({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await Yqe(a,`Failed to create pairing credential (${a.status}).`));return QG(a,i)}async function gJe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new YG({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return _Je(await QG(t,e))}function _Je(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=vJe(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 vJe(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 yJe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},$G())}catch(e){throw e instanceof gr&&e.kind!==`auth`&&e.code!==null&&sK.has(e.code)?new gr({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 bJe(e={}){return yJe(e.forceFresh===!0)}async function vK(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},$G())}catch(e){throw e instanceof gr&&e.kind!==`auth`&&e.code!==null&&sK.has(e.code)?new gr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function xJe(e){try{return await vK(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof gr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof gr||t instanceof Error)return vK(`/api/command/tasks/update`,e);throw t}}async function SJe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function CJe(){let e=await Promise.allSettled([sr(),SJe()]);hG(null),Qqe(),eK=null,tK=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function wJe(){if(aK(),tK?.status===`authenticated`)return fr(),tK;if(eK)return eK;let e=yK();return eK=e,e.then(e=>(e.status===`authenticated`&&(tK=e),e)).finally(()=>{eK===e&&(eK=null)})}async function yK(){return lr().then(e=>eJe(e)).then(()=>dJe())}async function TJe(){aK(),eK=null,tK=null;let e=await yK();return e.status===`authenticated`&&(tK=e,fr()),e}async function EJe(e){let t=e.email.trim();if(!t||!e.password)throw Error(`Enter your CMMD email and password.`);let n=or(`/api/auth/cmmd-password/token`),r=await fetch(n,ur({body:JSON.stringify({email:t,password:e.password}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new YG({message:await r.text()||`CMMD login failed (${r.status}).`,status:r.status});let i=await QG(r,n);if(i.authenticated===!0)return gK(),{serverEstablishedSession:!0};if(typeof i.access_token!=`string`||i.access_token.trim().length===0)throw Error(`CMMD login did not return an access token.`);return await _K(i.access_token,i.user,{refreshToken:typeof i.refresh_token==`string`?i.refresh_token:void 0,mcpToken:typeof i.mcp_token==`string`?i.mcp_token:void 0}),{serverEstablishedSession:!1}}var DJe=`/.well-known/forge/environment`,bK=Xt()(e=>({descriptor:null,setDescriptor:t=>e({descriptor:t}),reset:()=>e({descriptor:null})})),xK=null;function OJe(e){let t=SK();return t?Qie(Po({id:t.environmentId,label:t.label,source:e.source,target:e.target}),t):null}async function kJe(){return hK(async()=>{await lr();let e=mr()?.bearerToken,t=or(DJe),n=e?await fetch(t,{headers:{Authorization:`Bearer ${e}`}}):await fetch(t);if(!n.ok)throw new YG({message:`Failed to load server environment descriptor (${n.status}).`,status:n.status});let r=await QG(n,t);return CK(r),r})}function SK(){return bK.getState().descriptor}function AJe(){return bK(jJe)}function jJe(e){return e.descriptor?.environmentId??null}function MJe(){return bK(NJe)}function NJe(e){return e.descriptor}function PJe(){return bK(FJe)}function FJe(e){return e.descriptor?.deviceRuntimeId??null}function IJe(){return SK()?.deviceRuntimeId??null}function LJe(){return bK(RJe)}function RJe(e){return iae(e.descriptor)}function zJe(){return bK(BJe)}function BJe(e){return aae(e.descriptor)}function CK(e){bK.getState().setDescriptor(e)}function VJe(e,t){return t?.primaryMode!==`cloud`||e.environmentId===t.environmentId}function wK(){let e=mr();return e?OJe({source:e.source,target:e.target}):null}function HJe(){return UJe()}async function UJe(){let e=await lr(),t=SK();if(t&&VJe(t,e))return Promise.resolve(t);if(t&&CK(null),xK)return xK;let n=kJe();return xK=n,n.finally(()=>{xK===n&&(xK=null)})}var TK=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 EK(e){return{match:t=>t.present({target:e})}}function DK(){return{match:e=>e.provablyAbsent()}}function WJe(e){return{match:t=>t.unprovable(e)}}var GJe=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?DK():EK(TK.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 EK(TK.namedByCatalog(t))}if(this.#e.length===0)return DK();let t=e.runtimeId??e.cmmdEnvironmentId;return WJe(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 OK(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(KJe))throw Error(`Forge Cloud returned a project catalog this version cannot read (invalid project entry).`);if(!i.every(qJe))throw Error(`Forge Cloud returned an Environment catalog this version cannot read (invalid Environment entry).`);return GJe.fromValidatedBody(r,i,n?.capacity??null)}function KJe(e){return!AK(e)||typeof e.organizationId!=`number`||typeof e.projectId!=`number`?!1:e.runtime===void 0||e.runtime===null||kK(e.runtime)}function qJe(e){return AK(e)&&typeof e.organizationId==`number`&&typeof e.userId==`number`&&kK(e.runtime)}function kK(e){return AK(e)&&typeof e.runtimeId==`string`&&typeof e.status==`string`}function AK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JJe(e,t){let n=new URL(e);return n.pathname=t,n.search=``,n.hash=``,n.toString()}function jK(e){return e.accessToken??e.resolveAccessToken?.()}function MK(e,t,n=t=>JJe(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:()=>jK(e)})}function YJe(e,t){return MK(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 XJe(e,t){return MK(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 NK(e,t=``){return`/api/forge/context/runtimes/${encodeURIComponent(e)}${t}`}async function ZJe(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 PK=class{config;constructor(e){this.config=e}async ensureRuntime(e){return(await MK(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 MK(this.config,{method:`POST`,path:NK(e.runtimeId,`/connect`),...e.organizationId===void 0?{}:{body:{organizationId:e.organizationId}},...e.signal===void 0?{}:{signal:e.signal}})}async getRuntime(e){return(await MK(this.config,{method:`GET`,path:NK(e.runtimeId),...e.signal===void 0?{}:{signal:e.signal}})).runtime}async destroyRuntime(e){return(await MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`POST`,path:NK(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 MK(this.config,{method:`GET`,path:NK(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=jK(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 ZJe(n),OK(await n.json())}return OK(await MK(this.config,{method:`GET`,path:`/api/forge/context/cloud-projects`,...e?.signal===void 0?{}:{signal:e.signal}}))}async previewCloudProjectRemoval(e){return YJe(this.config,e)}async requestCloudProjectRemoval(e){return XJe(this.config,e)}async getCloudProjectRemoval(e){return(await MK(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}},FK=`/api/attachments/upload/`;function QJe(e){if(!e.relativeUrl.startsWith(FK))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}${FK}`,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 IK=!1,LK=null;function RK(e){return Object.values(e)}function zK(e){return e.map(e=>wn(e))}function BK(e){try{zl(zK(RK(e))).catch(e=>{console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)})}catch(e){console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)}}function $Je(e){let t=VK.getState().byId,n=Object.fromEntries(e.map(e=>[e.environmentId,e]));VK.setState({byId:{...n,...t}})}async function eYe(){if(IK)return;if(LK)return LK;let e=(async()=>{try{$Je(await Rl())}catch(e){console.error(`[SAVED_ENVIRONMENTS] hydrate failed`,e)}finally{IK=!0,VK.setState({hydrated:!0})}})().finally(()=>{LK===e&&(LK=null)});return LK=e,LK}var VK=Xt()(e=>({byId:{},hydrated:IK,upsert:t=>e(e=>{let n={...e.byId,[t.environmentId]:t};return BK(n),{byId:n}}),remove:t=>e(e=>{let{[t]:n,...r}=e.byId;return BK(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 BK(i),{byId:i}}),reset:()=>{BK({}),e({byId:{}})}}));function HK(){return IK}function UK(){return HK()?Promise.resolve():eYe()}function WK(){return Object.values(VK.getState().byId).toSorted((e,t)=>e.label.localeCompare(t.label))}function tYe(){return WK().filter(e=>e.lastAuthenticatedPullRequestCapability===!0)}function GK(e){return VK.getState().byId[e]??null}function KK(e){let t=wK();return t?.environmentId===e?Zie(t):GK(e)?.httpBaseUrl??null}function qK(e){let t=KK(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 JK(e){if(!KK(e))throw Error(`Unable to resolve HTTP base URL for environment ${e}.`)}function nYe(e){return JK(e.environmentId),QJe({httpBaseUrl:KK(e.environmentId),relativeUrl:e.relativeUrl})}async function YK(e){await zl(zK(RK({...VK.getState().byId,[e.environmentId]:e})))}async function rYe(e,t){let{[e]:n,...r}=VK.getState().byId,i={...r,[t.environmentId]:t};await zl(zK(RK(i))),VK.setState({byId:i})}async function XK(e){return Bl(e)}async function iYe(e,t){return Vl(e,t)}async function ZK(e){await Hl(e)}var aYe=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function QK(e){let t=e?.trim();return t&&t.length>0?t:null}function oYe(e){return QK(e)??`Project`}function sYe(e,t=`safe`){let n=QK(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function $K(e,t=`Something went wrong. Try again.`){let n=iG(e instanceof Error?e.message:typeof e==`string`?e:String(e),{fallback:t});return!n||aYe.some(e=>e.test(n))?t:n}function cYe(e,t){return e.reasoningEffortLevels.some(e=>e.value===t)}function eq(e){return e.reasoningEffortLevels.find(e=>e.isDefault)?.value??null}function tq(e,t){let n=eq(e),r=typeof t==`string`?t.trim():null;return r&&!e.promptInjectedEffortLevels.includes(r)&&cYe(e,r)?r:n??void 0}function nq(e,t){return e.contextWindowOptions.some(e=>e.value===t)}function rq(e){return e.contextWindowOptions.find(e=>e.isDefault)?.value??null}function lYe(e,t){let n=rq(e);return t&&nq(e,t)?t:n??void 0}function uYe(e,t){let n=tq(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 dYe(e,t){let n=tq(e,t?.effort),r=e.supportsThinkingToggle?t?.thinking:void 0,i=e.supportsFastMode?t?.fastMode:void 0,a=lYe(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 iq(e){return typeof e==`string`&&/\bultrathink\b/i.test(e)}function aq(e,t=`codex`){if(typeof e!=`string`)return null;let n=e.trim();if(!n)return null;let r=Sne[t],i=Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return typeof i==`string`?i:n}function oq(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=aq(r,e),s=n.find(e=>e.slug===o);return s?s.slug:null}var fYe=[`codex`,`claudeAgent`];function sq(e,t){return fYe.filter(e=>e!==t).some(t=>jte(t,e)!==void 0)}function pYe(e,t){let n=aq(e,t);return!n||sq(n,t)?On[t]:n}function cq(e,t){return pYe(t,e)}function mYe(e){return typeof e==`string`&&e.trim()||null}function hYe(e,t){let n=e.trim();return!n||t!==`ultrathink`||n.startsWith(`Ultrathink:`)?n:`Ultrathink:\n${n}`}function lq(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?uq(e.defaultModelSelection):null,createdAt:e.createdAt,updatedAt:e.updatedAt,scripts:dq(e.scripts)}}function uq(e){return{...e,model:cq(e.provider,e.model)}}function dq(e){return e.map(e=>({...e}))}function gYe(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?uq(t.defaultModelSelection):null},...t.scripts===void 0?{}:{scripts:dq(t.scripts)},updatedAt:t.updatedAt}}function fq(e){let t=oG(e.lastError);return{provider:vYe(e.providerName),status:_Ye(e.status),orchestrationStatus:e.status,activeTurnId:e.activeTurnId??void 0,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{lastError:t}:{}}}function pq(e,t){let n=t.attachments?.map(t=>{let n=qK({environmentId:e,pathname:yYe(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 mq(e){return{id:e.id,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId,createdAt:e.createdAt,updatedAt:e.updatedAt}}function hq(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 _Ye(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 vYe(e){return e===`codex`||e===`claudeAgent`||e===`ollama`||e===`cmmd`||e===`apex`?e:`codex`}function yYe(e){return`/attachments/${encodeURIComponent(e)}`}var bYe=[],xYe=[],SYe=[],CYe=[],wYe={},TYe={},EYe={},DYe={},OYe=[],gq=new WeakMap,_q=new WeakMap;function vq(e,t,n){if(!e||e.length===0||!t)return n;let r=gq.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||gq.set(e,o),a}function kYe(e,t){return vq(e.messageIdsByThreadId[t],e.messageByThreadId[t]??wYe,bYe)}function AYe(e,t){return vq(e.activityIdsByThreadId[t],e.activityByThreadId[t]??TYe,xYe)}function jYe(e,t){return vq(e.proposedPlanIdsByThreadId[t],e.proposedPlanByThreadId[t]??EYe,SYe)}function MYe(e,t){return vq(e.turnDiffIdsByThreadId[t],e.turnDiffSummaryByThreadId[t]??DYe,CYe)}function yq(e,t){let n=e.threadShellById[t];if(!n)return;let r=e.threadSessionById[t]??null,i=e.threadTurnStateById[t],a=e.threadRateLimitStatusById[t]??OYe,o=kYe(e,t),s=AYe(e,t),c=jYe(e,t),l=MYe(e,t),u=_q.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 _q.set(n,{session:r,turnState:i,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l,thread:d}),d}function NYe(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 bq(e){return{settledAt:e.settledAt??null,settledOverride:e.settledOverride??null}}var xq={projectIds:[],projectById:{},threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:{},messageIdsByThreadId:{},messageByThreadId:{},activityIdsByThreadId:{},activityByThreadId:{},proposedPlanIdsByThreadId:{},proposedPlanByThreadId:{},turnDiffIdsByThreadId:{},turnDiffSummaryByThreadId:{},sidebarThreadSummaryById:{},threadSubscriptionErrorById:{},bootstrapComplete:!1},PYe={activeEnvironmentId:null,environmentStateById:{}},Sq=[],Cq=[];function wq(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Tq(e,t){return{id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:uq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,session:e.session?fq(e.session):null,messages:e.messages.map(e=>pq(t,e)),proposedPlans:e.proposedPlans.map(mq),error:oG(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...bq(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan,branch:e.branch,worktreePath:e.worktreePath,turnDiffSummaries:e.checkpoints.map(hq),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 Eq(e,t){let n={id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:uq(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:oG(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...bq(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?fq(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,...bq(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 FYe(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 IYe(e){return{latestTurn:e.latestTurn,...e.pendingSourceProposedPlan?{pendingSourceProposedPlan:e.pendingSourceProposedPlan}:{}}}function Dq(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.threadId===t.threadId&&e.planId===t.planId}function Oq(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&&Dq(e.sourceProposedPlan,t.sourceProposedPlan)}function kq(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 Aq(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 jq(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.title===t.title&&Mq(e.titleRegeneration,t.titleRegeneration)&&e.interactionMode===t.interactionMode&&kq(e.session,t.session)&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&Oq(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&&Aq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status}function Mq(e,t){return e===t?!0:e==null||t==null?!1:e.requestId===t.requestId&&e.startedAt===t.startedAt}function Nq(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&&Aq(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status&&e.goal===t.goal&&Mq(e.titleRegeneration,t.titleRegeneration)}function Pq(e,t){return e!==void 0&&Oq(e.latestTurn,t.latestTurn)&&Dq(e.pendingSourceProposedPlan,t.pendingSourceProposedPlan)}function LYe(e,t){return e.includes(t)?[...e]:[...e,t]}function Fq(e,t){return e.filter(e=>e!==t)}function RYe(e){return{ids:e.messages.map(e=>e.id),byId:Object.fromEntries(e.messages.map(e=>[e.id,e]))}}function zYe(e){return{ids:e.activities.map(e=>e.id),byId:Object.fromEntries(e.activities.map(e=>[e.id,e]))}}function BYe(e){return{ids:e.proposedPlans.map(e=>e.id),byId:Object.fromEntries(e.proposedPlans.map(e=>[e.id,e]))}}function VYe(e){return{ids:e.turnDiffSummaries.map(e=>e.turnId),byId:Object.fromEntries(e.turnDiffSummaries.map(e=>[e.turnId,e]))}}function HYe(e){return e.projectIds.flatMap(t=>{let n=e.projectById[t];return n?[n]:[]})}function Iq(e){return e.threadIds.flatMap(t=>{let n=yq(e,t);return n?[n]:[]})}function Lq(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]??Sq,i=Fq(n,t);if(i.length===0){let{[r]:t,...n}=e;e=n}else wq(n,i)||(e={...e,[r]:i})}let a=e[n]??Sq,o=LYe(a,t);wq(a,o)||(e={...e,[n]:o}),e!==i.threadIdsByProjectId&&(i={...i,threadIdsByProjectId:e})}return i}function Rq(e,t,n){let r=FYe(t),i=IYe(t),a=e.threadShellById[t.id],o=e.threadTurnStateById[t.id],s=Lq(e,t.id,t.projectId,n?.projectId);Nq(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};jq(c,e)||(s={...s,sidebarThreadSummaryById:{...s.sidebarThreadSummaryById,[t.id]:e}})}if(kq(n?.session??null,t.session)||(s={...s,threadSessionById:{...s.threadSessionById,[t.id]:t.session}}),(n?.rateLimitStatus??Cq)!==(t.rateLimitStatus??Cq)&&(s={...s,threadRateLimitStatusById:{...s.threadRateLimitStatusById,[t.id]:t.rateLimitStatus??Cq}}),Pq(o,i)||(s={...s,threadTurnStateById:{...s.threadTurnStateById,[t.id]:i}}),n?.messages!==t.messages){let e=RYe(t);s={...s,messageIdsByThreadId:{...s.messageIdsByThreadId,[t.id]:e.ids},messageByThreadId:{...s.messageByThreadId,[t.id]:e.byId}}}if(n?.activities!==t.activities){let e=zYe(t);s={...s,activityIdsByThreadId:{...s.activityIdsByThreadId,[t.id]:e.ids},activityByThreadId:{...s.activityByThreadId,[t.id]:e.byId}}}if(n?.proposedPlans!==t.proposedPlans){let e=BYe(t);s={...s,proposedPlanIdsByThreadId:{...s.proposedPlanIdsByThreadId,[t.id]:e.ids},proposedPlanByThreadId:{...s.proposedPlanByThreadId,[t.id]:e.byId}}}if(n?.turnDiffSummaries!==t.turnDiffSummaries){let e=VYe(t);s={...s,turnDiffIdsByThreadId:{...s.turnDiffIdsByThreadId,[t.id]:e.ids},turnDiffSummaryByThreadId:{...s.turnDiffSummaryByThreadId,[t.id]:e.byId}}}return s}function zq(e,t){let n=e.threadShellById[t.shell.id],r=Lq(e,t.shell.id,t.shell.projectId,n?.projectId);return Nq(n,t.shell)||(r={...r,threadShellById:{...r.threadShellById,[t.shell.id]:t.shell}}),kq(e.threadSessionById[t.shell.id]??null,t.session)||(r={...r,threadSessionById:{...r.threadSessionById,[t.shell.id]:t.session}}),Pq(e.threadTurnStateById[t.shell.id],t.turnState)||(r={...r,threadTurnStateById:{...r.threadTurnStateById,[t.shell.id]:t.turnState}}),jq(e.sidebarThreadSummaryById[t.shell.id],t.summary)||(r={...r,sidebarThreadSummaryById:{...r.sidebarThreadSummaryById,[t.shell.id]:t.summary}}),r}function Bq(e,t){return Object.fromEntries(Object.entries(e).flatMap(([e,n])=>t.has(e)?[[e,n]]:[]))}function Vq(e,t){let n=e.threadShellById[t],r=e.sidebarThreadSummaryById[t],i=n?.projectId??r?.projectId;if(!i)return e;let a=Fq(e.threadIds,t),o=Fq(e.threadIdsByProjectId[i]??Sq,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 UYe(e,t){let n=new Set(e.threadIdsByProjectId[t]??Sq);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 Hq(e,t){let n=UYe(e,t);if(!e.projectById[t]&&n.length===0&&!e.projectIds.includes(t))return e;let r=e;for(let e of n)r=Vq(r,e);let{[t]:i,...a}=r.projectById;return{...r,projectById:a,projectIds:Fq(r.projectIds,t)}}function Uq(e){return e===`error`?`error`:e===`missing`?`interrupted`:`completed`}function WYe(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 Wq(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 GYe(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 KYe(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 qYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function JYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function Gq(e,t,n){let r=yq(e,t);if(!r)return e;let i=n(r);return i===r?e:Rq(e,i,r)}function Kq(e,t,n,r){let i=Gq(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 YYe(e){return{projectIds:e.map(e=>e.id),projectById:Object.fromEntries(e.map(e=>[e.id,e]))}}function qq(e,t){return e.environmentStateById[t]??xq}function Jq(e,t,n){let r=e.environmentStateById[t]===n?e.environmentStateById:{...e.environmentStateById,[t]:n};return r===e.environmentStateById?e:{...e,environmentStateById:r}}function XYe(e,t,n){let r=t.projects.map(e=>lq(e,n)),i=new Set(t.threads.map(e=>e.id)),a={...e,...YYe(r),threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:Bq(e.threadRateLimitStatusById,i),sidebarThreadSummaryById:{},messageIdsByThreadId:Bq(e.messageIdsByThreadId,i),messageByThreadId:Bq(e.messageByThreadId,i),activityIdsByThreadId:Bq(e.activityIdsByThreadId,i),activityByThreadId:Bq(e.activityByThreadId,i),proposedPlanIdsByThreadId:Bq(e.proposedPlanIdsByThreadId,i),proposedPlanByThreadId:Bq(e.proposedPlanByThreadId,i),turnDiffIdsByThreadId:Bq(e.turnDiffIdsByThreadId,i),turnDiffSummaryByThreadId:Bq(e.turnDiffSummaryByThreadId,i),bootstrapComplete:!0};for(let e of t.threads)a=zq(a,Eq(e,n));return a}function ZYe(e,t,n){return Jq(e,n,XYe(qq(e,n),t,n))}function QYe(e,t,n){let r=qq(e,n),i=yq(r,t.id);return Jq(e,n,Rq(r,Tq(t,n),i))}function $Ye(e,t,n,r){let i=qq(e,t);return Jq(e,t,{...i,threadSubscriptionErrorById:{...i.threadSubscriptionErrorById,[n]:r}})}function eXe(e,t,n){let r=qq(e,t);if(!(n in r.threadSubscriptionErrorById))return e;let{[n]:i,...a}=r.threadSubscriptionErrorById;return Jq(e,t,{...r,threadSubscriptionErrorById:a})}function Yq(e,t,n){switch(t.type){case`project.created`:{let r=lq({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=gYe(n,t.payload);return{...e,projectById:{...e.projectById,[t.payload.projectId]:r}}}case`project.deleted`:return Hq(e,t.payload.projectId);case`thread.created`:{let r=yq(e,t.payload.threadId);return Rq(e,Tq({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 Vq(e,t.payload.threadId);case`thread.archived`:return Kq(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:t.payload.archivedAt});case`thread.unarchived`:return Kq(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:null});case`thread.settled`:return Kq(e,t.payload.threadId,t.payload.updatedAt,{settledAt:t.payload.settledAt,settledOverride:t.payload.settledOverride});case`thread.unsettled`:return Kq(e,t.payload.threadId,t.payload.updatedAt,{settledAt:null,settledOverride:`active`});case`thread.meta-updated`:return Gq(e,t.payload.threadId,e=>({...e,...t.payload.title===void 0?{}:{title:t.payload.title},...t.payload.modelSelection===void 0?{}:{modelSelection:uq(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 Gq(e,t.payload.threadId,e=>({...e,runtimeMode:t.payload.runtimeMode,updatedAt:t.payload.updatedAt}));case`thread.interaction-mode-set`:return Gq(e,t.payload.threadId,e=>({...e,interactionMode:t.payload.interactionMode,updatedAt:t.payload.updatedAt}));case`thread.turn-start-requested`:return Gq(e,t.payload.threadId,e=>({...e,...t.payload.modelSelection===void 0?{}:{modelSelection:uq(t.payload.modelSelection)},runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,pendingSourceProposedPlan:t.payload.sourceProposedPlan,latestTurn:Wq({previous:e.latestTurn,turnId:gn.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:Gq(e,t.payload.threadId,e=>{let n=e.latestTurn;return n===null||n.turnId!==t.payload.turnId?e:{...e,latestTurn:Wq({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 Gq(e,t.payload.threadId,e=>{let n=pq(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?GYe(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)?Wq({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 Gq(e,t.payload.threadId,e=>({...e,session:fq(t.payload.session),error:oG(t.payload.session.lastError),latestTurn:t.payload.session.status===`running`&&t.payload.session.activeTurnId!==null?Wq({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 Gq(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 Gq(e,t.payload.threadId,e=>{let n=mq(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 Gq(e,t.payload.threadId,e=>{let n=hq({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?Wq({previous:e.latestTurn,turnId:t.payload.turnId,state:Uq(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 Gq(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=KYe(e.messages,r,t.payload.turnCount).slice(-2e3),a=JYe(e.proposedPlans,r).slice(-200),o=qYe(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:Uq(s.status??`ready`),requestedAt:s.completedAt,startedAt:s.completedAt,completedAt:s.completedAt,assistantMessageId:s.assistantMessageId??null},updatedAt:t.occurredAt}});case`thread.activity-appended`:return Gq(e,t.payload.threadId,e=>{let n=[...e.activities.filter(e=>e.id!==t.payload.activity.id),{...t.payload.activity}].toSorted(WYe).slice(-500);return{...e,activities:n,updatedAt:t.occurredAt}});case`thread.rate-limit-set`:return Gq(e,t.payload.threadId,e=>({...e,rateLimitStatus:NYe(e.rateLimitStatus??[],t.payload),updatedAt:t.occurredAt}));case`thread.worker-spawned`:return Gq(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 tXe(e,t,n){switch(t.kind){case`project-upserted`:{let r=lq(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 Hq(e,t.projectId);case`thread-upserted`:return zq(e,Eq(t.thread,n));case`thread-removed`:return Vq(e,t.threadId)}}function nXe(e,t,n){if(t.length===0)return e;let r=qq(e,n);return Jq(e,n,t.reduce((e,t)=>Yq(e,t,n),r))}function Xq(e){return Object.entries(e.environmentStateById)}function Zq(e,t){return t?qq(e,t):xq}function rXe(e,t){return Iq(Zq(e,t))}function Qq(e){return Xq(e).flatMap(([,e])=>HYe(e))}function $q(e){return Xq(e).flatMap(([,e])=>Iq(e))}function iXe(e){return Xq(e).flatMap(([,e])=>eJ(e).flatMap(t=>{let n=e.threadShellById[t];return n?[n]:[]}))}function eJ(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 tJ(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 Xq(e).flatMap(([e,t])=>eJ(t).flatMap(n=>{let r=tJ(e,t,n);return r?[r]:[]}))}function nJ(e,t){if(!t)return[];let n=Zq(e,t.environmentId),r=n.threadIdsByProjectId[t.projectId]??Sq;return(r.length>0?r:eJ(n)).flatMap(e=>{let r=tJ(t.environmentId,n,e);return!r||r.projectId!==t.projectId?[]:[r]})}function oXe(e,t){return t.length===0?[]:t.length===1?nJ(e,t[0]):t.flatMap(t=>nJ(e,t))}function sXe(e){return e.activeEnvironmentId===null?Object.values(e.environmentStateById).some(e=>e.bootstrapComplete):Zq(e,e.activeEnvironmentId).bootstrapComplete}function cXe(e,t){return t?Zq(e,t.environmentId).projectById[t.projectId]:void 0}function rJ(e,t){return t?yq(Zq(e,t.environmentId),t.threadId):void 0}function lXe(e,t){return t?Zq(e,t.environmentId).threadShellById[t.threadId]!==void 0:!1}function iJ(e,t){return t?tJ(t.environmentId,Zq(e,t.environmentId),t.threadId)??void 0:void 0}function uXe(e,t,n){if(e.activeEnvironmentId===null)return e;let r=Gq(qq(e,e.activeEnvironmentId),t,e=>e.error===n?e:{...e,error:n});return Jq(e,e.activeEnvironmentId,r)}function dXe(e,t,n){return Jq(e,n,Yq(qq(e,n),t,n))}function fXe(e,t,n){return Jq(e,n,tXe(qq(e,n),t,n))}function pXe(e,t){return e.activeEnvironmentId===t?e:{...e,activeEnvironmentId:t}}function mXe(e,t,n,r){let i=Gq(qq(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 Jq(e,t.environmentId,i)}var aJ=Xt(e=>({...PYe,setActiveEnvironmentId:t=>e(e=>pXe(e,t)),syncServerShellSnapshot:(t,n)=>e(e=>ZYe(e,t,n)),syncServerThreadDetail:(t,n)=>e(e=>QYe(e,t,n)),setThreadSubscriptionError:(t,n,r)=>e(e=>$Ye(e,t,n,r)),clearThreadSubscriptionError:(t,n)=>e(e=>eXe(e,t,n)),applyOrchestrationEvent:(t,n)=>e(e=>dXe(e,t,n)),applyOrchestrationEvents:(t,n)=>e(e=>nXe(e,t,n)),applyShellEvent:(t,n)=>e(e=>fXe(e,t,n)),setError:(t,n)=>e(e=>uXe(e,t,n)),setThreadBranch:(t,n,r)=>e(e=>mXe(e,t,n,r))})),oJ=`Thread not found or you no longer have access.`;function hXe(e){if(e==null)return oJ;let t=$K(ote(e)?Ie(e):e,oJ);return/\bnot found\b/i.test(t)?oJ:t}function gXe(e,t,n){aJ.getState().setThreadSubscriptionError(e,t,hXe(n))}function sJ(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var _Xe={enabled:!0,leading:!0,trailing:!0,wait:0},vXe=class{#e;constructor(e,t){this.fn=e,this.store=new Tte(sJ()),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`}}),bte(`Throttler`,this)},this.#n=()=>!!Yt(this.options.enabled,this),this.#r=()=>Yt(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(sJ())},this.key=t.key,this.options={..._Xe,...t},this.#t(this.options.initialState??{}),this.key&&Cte.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 yXe(e){return!!(e.prompt.trim()||e.images.length||e.terminalContexts.length||e.persistedAttachments.length||e.stagedSubmission)}function bXe(e,t,n){let r=Vo(t),i=Vo(n);if(r===i)return e;let a=e[r];if(!a)return e;let o=e[i];if(o&&yXe(o)&&!xXe(a,o))return null;let s={...e,[i]:{...a,...kXe(a,o)}};return delete s[r],s}function xXe(e,t){let n=e.stagedSubmission;return!n||!SXe(n)||!CXe(e,n)||!wXe(n,t.stagedSubmission)?!1:TXe(e,t)}function SXe(e){return!!e.commandId&&!!e.messageId}function CXe(e,t){return[e.prompt===t.prompt,lJ(e.persistedAttachments,t.attachments),lJ(e.terminalContexts,t.terminalContexts)].every(Boolean)}function wXe(e,t){return!t||EXe(e,t)}function TXe(e,t){return[e.prompt===t.prompt,e.lastGeneratedPullRequestPrompt===t.lastGeneratedPullRequestPrompt,dJ(e.images,t.images),uJ(e.nonPersistedImageIds,t.nonPersistedImageIds),e.nonPersistedImageIds.length===0,dJ(e.persistedAttachments,t.persistedAttachments),dJ(e.terminalContexts,t.terminalContexts),OXe(e.modelSelectionByProvider,t.modelSelectionByProvider),e.activeProvider===t.activeProvider,e.runtimeMode===t.runtimeMode,e.interactionMode===t.interactionMode].every(Boolean)}function EXe(e,t){return[e.commandId===t.commandId&&e.messageId===t.messageId,e.prompt===t.prompt,lJ(e.attachments,t.attachments),lJ(e.terminalContexts,t.terminalContexts),cJ(e.modelSelection,t.modelSelection),cJ(e.runtimeMode,t.runtimeMode),cJ(e.interactionMode,t.interactionMode),DXe(e.executionIntent,t.executionIntent)].every(Boolean)}function cJ(e,t){return e===void 0||t===void 0||JSON.stringify(e)===JSON.stringify(t)}function DXe(e,t){return!e||!t||e.runtimeId===t.runtimeId}function lJ(e,t){return e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id)}function uJ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function dJ(e,t){return e.length===t.length&&e.every((e,n)=>JSON.stringify(e)===JSON.stringify(t[n]))}function OXe(e,t){let n=Object.keys(e).toSorted();return uJ(n,Object.keys(t).toSorted())?n.every(n=>JSON.stringify(e[n])===JSON.stringify(t[n])):!1}function kXe(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 fJ=`full-access`,pJ=`default`,mJ=`default`,AXe=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,jXe=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function hJ(e){return e.replace(/\r\n/g,`
1006
+ `).replace(/^\n+|\n+$/g,``)}function gJ(e){return hJ(e.text).length>0}function MXe(e){return!gJ(e)}function NXe(e){return e.filter(e=>gJ(e))}function PXe(e){let t=hJ(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 FXe(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function _J(e){return`${e.terminalLabel} ${FXe(e)}`}function vJ(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function IXe(e){return hJ(e.text).split(`
1007
+ `).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function LXe(e){let t=e.map(e=>PXe(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(`- ${_J(r)}:`),n.push(...IXe(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
1008
+ `)}function RXe(e,t){let n=0,r=``;for(let i of e){if(i!==``){r+=i;continue}let e=t[n]??null;n+=1,e&&(r+=vJ(e))}return r}function zXe(e,t){let n=RXe(e,t).trim(),r=LXe(t);return r.length===0?n:n.length>0?`${n}\n\n${r}`:r}function BXe(e){let t=AXe.exec(e);if(!t)return{promptText:e,contextCount:0,previewTitle:null,contexts:[]};let n=e.slice(0,t.index).replace(/\n+$/,``),r=UXe(t[1]??``);return{promptText:n,contextCount:r.length,previewTitle:r.length>0?r.map(({header:e,body:t})=>t.length>0?`${e}\n${t}`:e).join(`
1009
1009
 
1010
- `):null,contexts:r}}function BXe(e){let t=AXe.exec(e);if(!t)return{promptText:e,cmmdContext:null};let n=(t[1]??``).trim();return{promptText:e.slice(t[0].length).replace(/^\n+/,``),cmmdContext:n.length>0?{body:n}:null}}function VXe(e){let t=BXe(e),n=zXe(t.promptText);return{visibleText:n.promptText,copyText:e,contextCount:n.contextCount,previewTitle:n.previewTitle,contexts:n.contexts,cmmdContext:t.cmmdContext}}function HXe(e){let t=[],n=null,r=()=>{n&&=(t.push({header:n.header,body:n.bodyLines.join(`
1010
+ `):null,contexts:r}}function VXe(e){let t=jXe.exec(e);if(!t)return{promptText:e,cmmdContext:null};let n=(t[1]??``).trim();return{promptText:e.slice(t[0].length).replace(/^\n+/,``),cmmdContext:n.length>0?{body:n}:null}}function HXe(e){let t=VXe(e),n=BXe(t.promptText);return{visibleText:n.promptText,copyText:e,contextCount:n.contextCount,previewTitle:n.previewTitle,contexts:n.contexts,cmmdContext:t.cmmdContext}}function UXe(e){let t=[],n=null,r=()=>{n&&=(t.push({header:n.header,body:n.bodyLines.join(`
1011
1011
  `).trimEnd()}),null)};for(let t of e.split(`
1012
- `)){let e=/^- (.+):$/.exec(t);if(e){r(),n={header:e[1],bodyLines:[]};continue}if(n){if(t.startsWith(` `)){n.bodyLines.push(t.slice(2));continue}t.length===0&&n.bodyLines.push(``)}}return r(),t}function bJ(e){let t=0;for(let n of e)n===``&&(t+=1);return t}function xJ(e,t){let n=t-bJ(e);return n<=0?e:`${``.repeat(n)}${e}`}function UXe(e){return e===void 0||e===` `||e===`
1013
- `||e===` `||e===`\r`}function WXe(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${UXe(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:bJ(e.slice(0,n))}}function GXe(e){return e.replaceAll(``,``)}function KXe(e,t){if(t<0)return{prompt:e,cursor:e.length};let n=0;for(let r=0;r<e.length;r+=1)if(e[r]===``){if(n===t)return{prompt:e.slice(0,r)+e.slice(r+1),cursor:r};n+=1}return{prompt:e,cursor:e.length}}function SJ(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var CJ=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return CJ(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return CJ(t)(e)}}}},wJ=(e,t)=>(n,r,i)=>{let a={storage:SJ(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return CJ(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p},TJ=e=>Symbol.iterator in e,EJ=e=>`entries`in e,DJ=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},qXe=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function JXe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:TJ(e)&&TJ(t)?EJ(e)&&EJ(t)?DJ(e,t):qXe(e,t):DJ({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function OJ(e){let t=F.useRef(void 0);return n=>{let r=e(n);return JXe(t.current,r)?t.current:t.current=r}}function kJ(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function YXe(e){return e!=null&&typeof e.getItem==`function`&&typeof e.setItem==`function`&&typeof e.removeItem==`function`}function AJ(e){return YXe(e)?e:kJ()}var jJ=kJ();function MJ(){return globalThis.localStorage||globalThis.window?.localStorage}var NJ={getItem:e=>{try{let t=MJ()?.getItem(e);if(t!==void 0)return t}catch{}return jJ.getItem(e)},setItem:(e,t)=>{try{let n=MJ();if(n){n.setItem(e,t);return}}catch{}jJ.setItem(e,t)},removeItem:e=>{try{let t=MJ();if(t){t.removeItem(e);return}}catch{}jJ.removeItem(e)}};function PJ(e){let t=NJ.getItem(e);return typeof t==`string`?t:null}function FJ(e,t){NJ.setItem(e,t)}function XXe(e){NJ.removeItem(e)}function ZXe(e,t=300){let n=AJ(e),r=new Qt((e,t)=>{n.setItem(e,t)},{wait:t});return{getItem:e=>n.getItem(e),setItem:(e,t)=>{r.maybeExecute(e,t)},removeItem:e=>{r.cancel(),n.removeItem(e)},flush:()=>{r.flush()}}}var IJ=[`draftsByThreadKey`,`draftThreadsByThreadKey`,`logicalProjectDraftThreadKeyByLogicalProjectKey`],QXe=[`stickyModelSelectionByProvider`,`stickyActiveProvider`];function $Xe(e){let t=LJ(e.nextLocal,e.version,!1);if(!t)return e.currentStored??e.nextLocal;if(e.currentStored!==null&&e.canMigrate!==void 0&&!e.canMigrate(e.currentStored,e.version))return e.currentStored;if(e.previousLocal===e.currentStored&&(e.canMigrate??eZe)(e.currentStored,e.version))return e.nextLocal;let n=LJ(e.previousLocal,e.version,!0),r=LJ(e.currentStored,e.version,!0);if(!r||!n)return e.currentStored??e.nextLocal;let i={...r.state};for(let e of IJ)i[e]=iZe(n.state[e],r.state[e],t.state[e]);for(let e of QXe)RJ(n.state[e],t.state[e])||(i[e]=t.state[e]);return JSON.stringify({...r,version:e.version,state:i})}function eZe(e,t){if(e===null)return!0;try{let n=JSON.parse(e);return!zJ(n)||!zJ(n.state)||typeof n.version!=`number`||!Number.isInteger(n.version)?!1:n.version>=1&&n.version<t}catch{return!1}}function LJ(e,t,n){if(e===null)return n?{version:t,state:rZe()}:null;let r=tZe(e);return r&&nZe(r,t)?{version:t,state:r.state}:null}function tZe(e){try{let t=JSON.parse(e);return zJ(t)?t:null}catch{return null}}function nZe(e,t){let n=e.state;return e.version!==t||!zJ(n)?!1:IJ.every(e=>zJ(n[e]))}function rZe(){return Object.fromEntries(IJ.map(e=>[e,{}]))}function iZe(e,t,n){let r={...t};for(let t of new Set([...Object.keys(e),...Object.keys(n)]))RJ(e[t],n[t])||(t in n?r[t]=n[t]:delete r[t]);return r}function RJ(e,t){return JSON.stringify(e)===JSON.stringify(t)}function zJ(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function aZe(e){let t;return{getItem:n=>{let r=e.storage.getItem(n);return t===void 0&&(t=r),r},setItem:(n,r)=>{let i=e.storage.getItem(n),a=$Xe({previousLocal:t??null,currentStored:i,nextLocal:r,version:e.version,...e.canMigrate===void 0?{}:{canMigrate:e.canMigrate}});(a!==i||i===r)&&(e.storage.setItem(n,a),t=r)},removeItem:n=>{e.storage.removeItem(n),t=null}}}function BJ(e){let t=e.auth.status!==`unauthenticated`||e.auth.provenance?.credentialScope===`proxied`;return e.enabled&&e.installed&&e.status===`ready`&&t&&e.models.length>0}function oZe(e){if(!UJ(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(sZe)}}function sZe(e){return UJ(e)?lZe(e.provider)&&VJ(e.providerAccountId)&&cZe(e)&&HJ(e.accountEmail)&&HJ(e.accountDisplayName)&&HJ(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function cZe(e){return(e.credentialTarget===`primary`||e.credentialTarget===`linked`)&&Array.isArray(e.legacyProviderAccountIds)&&e.legacyProviderAccountIds.every(VJ)}function lZe(e){return e===`codex`||e===`claudeAgent`}function VJ(e){return typeof e==`string`&&e.trim().length>0}function HJ(e){return typeof e==`string`||e===null}function UJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uZe(e){let t=Dl(e);return t.legacyRuntimeId===null?t.shape===`durable-environment`&&typeof e==`string`?e:null:t.legacyRuntimeId}var WJ=class extends Error{constructor(e){super(e===`auth`?`Your CMMD session expired. Sign in again to verify Claude runtime readiness.`:`CMMD denied access to verify Claude runtime readiness. Check your organization permissions.`),this.name=`ForgeProviderAccessAuthorityError`}};async function dZe(e){if(!e.enabled||e.readinessTargetId===null)return null;try{return mZe(await e.load(e.readinessTargetId),e.readinessTargetId)}catch(e){if(e instanceof gr&&(e.kind===`auth`||e.kind===`permission`))throw new WJ(e.kind);return null}}var fZe=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),pZe=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`];function mZe(e,t){if(!GJ(e)||!bZe(e)||!hZe(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function hZe(e,t){if(e.deliveryReceipt===null)return e.nativeExecutable!==!0;if(!GJ(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=GJ(n.identity)?n.identity:null;return r!==null&&gZe(n,t)&&yZe(r,e.generationId)}function gZe(e,t){return _Ze(e,t)&&vZe(e)}function _Ze(e,t){return typeof e.receiptId==`string`&&e.receiptId.trim().length>0&&e.runtimeId===t&&typeof e.machineId==`string`&&e.machineId.trim().length>0&&typeof e.credentialEpoch==`number`&&Number.isSafeInteger(e.credentialEpoch)&&e.credentialEpoch>=0}function vZe(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function yZe(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function bZe(e){return typeof e.connected==`boolean`&&fZe.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&pZe.every(t=>xZe(e[t]))}function xZe(e){return e===null||typeof e==`string`}function GJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var KJ={providers:{codex:!0,claude:!1,cmmd:!0},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function qJ(e){if(e==null)return KJ;let t=e.providers,n=e.allowedWallets;return{providers:{...KJ.providers,...t},allowedWallets:Array.isArray(n)&&n.length>0?n:KJ.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:KJ.updatedAt}}function SZe(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var CZe=[`codex`,`claudeAgent`,`cmmd`];function wZe(e,t){if(t==null)return null;let n=t.providers;if(typeof n!=`object`||!n)return null;let r=n[e];return typeof r==`boolean`?r:null}function JJ(e,t){let n=SZe(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=wZe(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:qJ(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function YJ(e,t){return JJ(e,t).offered}function TZe(e,t){return XJ(e,t).offered}function XJ(e,t){return t===null?{offered:!0}:JJ(e,t)}function ZJ(e,t){return qJ(t).allowedWallets.includes(e)}function QJ(e){return ZJ(`personal`,e)}function EZe(e){return e===`claudeAgent`||e===`codex`}function DZe(e,t){return e!==`claudeAgent`||QJ(t)||YJ(`claudeAgent`,t)}function OZe(e){return e.isDebugDisclosureEnabled||EZe(e.provider)&&QJ(e.policy)?!1:!YJ(e.provider===`apex`?`apex`:e.provider,e.policy)}var $J={credential_expired_refreshing:`CREDENTIAL_EXPIRED_REFRESHING`,credential_reconnect_required:`CREDENTIAL_RECONNECT_REQUIRED`,credential_not_connected:`CREDENTIAL_RECONNECT_REQUIRED`,credential_generation_not_applied:`CREDENTIAL_GENERATION_NOT_APPLIED`,runtime_unavailable:`RUNTIME_UNAVAILABLE`};function kZe(e){return typeof e!=`string`||!Object.hasOwn($J,e)?null:$J[e]??null}var AZe=new Set([`pending`,`claimed`,`activating`]),jZe=2e3;function eY(e){return{readinessTargetId:e,dataUpdatedAt:0,consecutiveUnavailableResponses:0,consecutiveFailedResponses:0}}function MZe(e){let t=e.current.readinessTargetId===e.readinessTargetId?e.current:eY(e.readinessTargetId);return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{readinessTargetId:e.readinessTargetId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0,consecutiveFailedResponses:e.deliveryStatus===`failed`?t.consecutiveFailedResponses+1:0}}function NZe(e,t){if(!e.claudeOffered||!e.claudeConnected)return!1;let n=kZe(e.reason);return n===`CREDENTIAL_EXPIRED_REFRESHING`?!0:e.deliveryStatus===`failed`?n!==`CREDENTIAL_RECONNECT_REQUIRED`&&t.consecutiveFailedResponses<16:e.deliveryStatus===null?t.consecutiveUnavailableResponses>0&&t.consecutiveUnavailableResponses<3:AZe.has(e.deliveryStatus)}function tY(e){return e.credentialMode===`runtime`?e.provider&&BJ(e.provider)?{eligible:!0}:{eligible:!1,reason:`runtime-unavailable`}:e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`?{eligible:!1,reason:`access-error`}:PZe({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function PZe(e){return!e.provider||!BJ(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:YJ(e.providerKind,e.policy)?rY({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function nY(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:YJ(e.providerKind,e.access.policy)?rY({providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness,stage:`provisioning`}):{eligible:!1,reason:`not-offered`}}function rY(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:FZe({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:ZJ(`workspace`,e.policy),stage:e.stage})}function FZe(e){return IZe(e.workspaceWalletAllowed)?{eligible:!0}:LZe(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:RZe(e.providerKind,e.personalConnections)?VZe(e)?{eligible:!1,reason:`environment-not-running`}:zZe(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function IZe(e){return e&&!1}function LZe(e,t){return e===`codex`&&t?.codex===!0}function RZe(e,t){return t?.[e]===!0}function zZe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||HZe(e.claudeRuntimeReadiness)}var BZe=`runtime_unavailable`;function VZe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`?!1:e.claudeRuntimeReadiness?.reason===BZe}function HZe(e){if(!UZe(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function UZe(e){return e?.connected===!0&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function iY(e){return e.providers.filter(t=>tY({provider:t,providerKind:t.provider,access:e.access,credentialMode:e.credentialMode}).eligible)}function WZe(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=ZJ(`workspace`,e.policy);return t.cmmd?!0:ZJ(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var GZe={providers:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},aY=[`cmmd`,`forge-provider-access`],KZe=jZe;function qZe(e,t){return!(t instanceof WJ)&&e<3}function JZe(e,t=null){return[...aY,e,t]}async function YZe(e){e.queryClient.setQueriesData({queryKey:aY},t=>XZe(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:aY,refetchType:`all`})}function XZe(e,t,n){return e?.status!==`ready`||e.personalConnections===null?e:{...e,personalConnections:{...e.personalConnections,[t]:n},...t===`codex`?{personalReconnectRequired:{codex:!1}}:{},...t===`claudeAgent`?{claudeRuntimeReadiness:null}:{}}}async function oY(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=qG(),r=nQe(await n.getOrgProviderPolicy());ZJ(`workspace`,r);let[i,a,o,s]=await Promise.all([$Ze(()=>n.getProviderAccounts()),sY({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),sY({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),dZe({enabled:r.providers.claude,readinessTargetId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=ZZe(c),u=l.codex||a.connected,d=l.claudeAgent||o.connected,f=c.some(e=>e.provider===`codex`&&e.needsReconnect)||a.reconnectRequired;return{status:`ready`,policy:r,personalConnections:{codex:u,claudeAgent:d},providerAccounts:c,...f?{personalReconnectRequired:{codex:!0}}:{},claudeRuntimeReadiness:s}}function ZZe(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function QZe(e,t){if(e.status!==`ready`)return;let n=e.providerAccounts??[];return(n.find(e=>e.provider===t&&e.isDefault&&!e.needsReconnect)??n.find(e=>e.provider===t&&!e.needsReconnect))?.providerAccountId}async function $Ze(e){try{return oZe(await e())}catch{return{accounts:[]}}}async function sY(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return aQe(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function eQe(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,reason:e?.claudeRuntimeReadiness?.reason??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function tQe(e){let t=(0,cl.c)(21),n;t[0]!==e.environmentId||t[1]!==e.runtimeId?(n=e.environmentId==null?e.runtimeId??null:uZe(e.environmentId),t[0]=e.environmentId,t[1]=e.runtimeId,t[2]=n):n=t[2];let r=n,i;t[3]===r?i=t[4]:(i=eY(r),t[3]=r,t[4]=i);let a=(0,F.useRef)(i),o;t[5]!==e.credentialMode||t[6]!==r?(o=JZe(e.credentialMode,r),t[5]=e.credentialMode,t[6]=r,t[7]=o):o=t[7];let s;t[8]===r?s=t[9]:(s=()=>oY(`cmmd-cloud`,r),t[8]=r,t[9]=s);let c=e.enabled&&e.credentialMode===`cmmd-cloud`,l;t[10]===r?l=t[11]:(l=e=>{if(e.state.error instanceof WJ)return!1;let t=eQe(e.state.data);return a.current=MZe({current:a.current,readinessTargetId:r,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:r!==null&&t.readinessUnavailable,deliveryStatus:t.deliveryStatus}),r!==null&&NZe(t,a.current)?KZe:!1},t[10]=r,t[11]=l);let u;t[12]!==o||t[13]!==s||t[14]!==c||t[15]!==l?(u={queryKey:o,queryFn:s,enabled:c,retry:qZe,staleTime:3e4,refetchInterval:l},t[12]=o,t[13]=s,t[14]=c,t[15]=l,t[16]=u):u=t[16];let d=ji(u);if(!e.enabled){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[17]=e):e=t[17],e}if(e.credentialMode===`runtime`){let e;return t[18]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[18]=e):e=t[18],e}if(d.isPending){let e;return t[19]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[19]=e):e=t[19],e}if(d.isError||!d.data){let e;return t[20]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[20]=e):e=t[20],e}return d.data}function nQe(e){if(!cY(e)||!cY(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,allowedWallets:n,updatedAt:r}=e,i=iQe(n,r);if(!rQe(t)||i===null)throw Error(`CMMD returned an invalid organization provider policy.`);return{providers:{codex:t.codex,claude:t.claude,cmmd:t.cmmd},allowedWallets:[...new Set(i.allowedWallets)],updatedAt:i.updatedAt}}function rQe(e){return typeof e.codex==`boolean`&&typeof e.claude==`boolean`&&typeof e.cmmd==`boolean`}function iQe(e,t){return Array.isArray(e)&&e.length>0&&e.every(oQe)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function aQe(e,t){if(!cY(e)||typeof e.connected!=`boolean`)throw Error(`CMMD returned an invalid ${t} connection state.`);if(!e.connected)return{connected:!1,reconnectRequired:!1};if(t===`codex`){if(typeof e.needsReconnect!=`boolean`)throw Error(`CMMD returned an invalid Codex connection state.`);return{connected:!e.needsReconnect,reconnectRequired:e.needsReconnect}}if(typeof e.generationId!=`string`||e.generationId.trim().length===0)throw Error(`CMMD returned an invalid Claude connection state.`);return{connected:!0,reconnectRequired:!1}}function oQe(e){return e===`personal`||e===`workspace`}function cY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sQe(e){return e.status===`ready`?e.policy:GZe}var lY=[`cursor`,`opencode`,`gemini`],uY={state:`usable`},dY={state:`withheld`,reason:`unbuilt`},fY={state:`withheld`,reason:`not-on-this-environment`};function pY(e){return lY.includes(e)}function mY(e){return e===`gemini`?null:e}function hY(e,t){if(e===void 0)return t?fY:uY;if(e.availability===`unavailable`){let t=e.unavailableReason??`not-on-this-environment`;return e.unavailableDetail===void 0?{state:`withheld`,reason:t}:{state:`withheld`,reason:t,detail:e.unavailableDetail}}return e.availability===`available`||BJ(e)||cQe(e)?uY:fY}function cQe(e){return e.installed&&e.auth.status===`unauthenticated`&&e.auth.provenance?.credentialScope!==`proxied`}function lQe(e,t){let n=nY({providerKind:e,access:t});return n.eligible?null:uQe(n.reason)}function uQe(e){switch(e){case`access-loading`:return{state:`unresolved`,cause:`loading`};case`access-error`:return{state:`unresolved`,cause:`error`};case`not-offered`:return{state:`withheld`,reason:`not-offered`};case`personal-credential-required`:return{state:`withheld`,reason:`not-usable`,detail:`no-connection`};case`personal-credential-reconnect-required`:return{state:`withheld`,reason:`not-usable`,detail:`reconnect-required`};case`native-runtime-not-ready`:return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};case`environment-not-running`:return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};case`runtime-unavailable`:return null}}function dQe(e){if(pY(e.provider))return{pick:dY,run:dY};let t=mY(e.provider);return t===null?{pick:dY,run:dY}:gY({...e,providerKind:t})}function gY(e){return{pick:_Y(e,`pick`),run:_Y(e,`run`)}}function fQe(e){return dQe(e).pick}function pQe(e){return _Y(e,`pick`)}function mQe(e){return e.providers.filter(t=>_Y({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0},`run`).state===`usable`)}function _Y(e,t){let{providerKind:n}=e;if(e.snapshot?.unavailableReason===`unbuilt`)return dY;if(e.credentialMode===`runtime`)return vY({...e,providerKind:n},t);if(e.access.status!==`ready`)return{state:`unresolved`,cause:e.access.status};if(!XJ(n,e.access.policy).offered)return{state:`withheld`,reason:`not-offered`};let r=lQe(n,e.access);return r===null?vY({...e,providerKind:n},t):r}function vY(e,t){let n=tY({provider:e.snapshot,providerKind:e.providerKind,access:e.access,credentialMode:e.credentialMode});return!n.eligible&&n.reason===`environment-not-running`?{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`}:!n.eligible&&n.reason===`native-runtime-not-ready`?{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`}:!n.eligible&&n.reason===`runtime-unavailable`&&t===`run`?fY:hY(e.snapshot,e.hasLiveInventory)}var hQe={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},yY=[`codex`,`claudeAgent`,`apex`];function bY(e){for(let t of yY){let n=e.find(e=>e.provider===t);if(n&&SY(n))return t}return e.find(SY)?.provider??null}function xY(e,t){return e.find(e=>e.provider===t)?.models??[]}function SY(e){return BJ(e)}function CY(e,t){let n=t??bY(e)??`codex`,r=e.find(e=>e.provider===n);if(r&&SY(r)||n===`codex`)return n;for(let t of yY){let n=e.find(e=>e.provider===t);if(n&&SY(n))return t}return`codex`}function wY(e){return e.providers.filter(t=>pQe({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0}).state===`usable`)}function TY(e,t,n,r){let i=wY({providers:e,access:n,credentialMode:r});return t&&i.some(e=>e.provider===t)?t:bY(i)}function gQe(e,t,n,r){return t==null?TY(e,null,n,r):iY({providers:e,access:n,credentialMode:r}).some(e=>e.provider===t)?t:null}function EY(e,t,n){let r=aq(t,n);return e.find(e=>e.slug===r)?.capabilities??hQe}function DY(e,t,n){let r=xY(e,t).filter(e=>!e.isLegacy);return r.find(e=>e.slug===n)?.slug??r.find(e=>e.isDefault)?.slug??r.find(e=>e.slug===On[t])?.slug??r.find(e=>!e.isCustom)?.slug??r[0]?.slug??On[t]}function OY(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=EY(r,n,t),s=a?.[t],c=tq(o,s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null)??null,l=t===`codex`?uYe(o,s):dYe(o,s),u=o.promptInjectedEffortLevels.length>0&&iq(i);return{provider:t,promptEffort:c,modelOptionsForDispatch:l,...u?{composerFrameClassName:`ultrathink-frame`}:{},...u?{composerSurfaceClassName:`shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]`}:{},...u?{modelPickerIconClassName:`ultrathink-chroma`}:{}}}function kY(e,t,n,r){return xY(t,n).map(({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i})=>({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i}))}function AY(e,t,n,r,i){let a=oq(e,r,kY(t,n,e,r));if(a&&!sq(a,e))return a;let o=jY(n,e,i),s=oq(o,r,kY(t,n,o,r))??DY(n,o);return e&&sq(s,e)?DY(n,e):s}function jY(e,t,n){return!t||!YJ(t,n)?CY(e,`codex`):CY(e,t)}function _Qe(e,t,n,r){return{codex:kY(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:kY(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:kY(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:kY(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:kY(e,t,`apex`,n===`apex`?r:void 0),cursor:kY(e,t,`cursor`,n===`cursor`?r:void 0),opencode:kY(e,t,`opencode`,n===`opencode`?r:void 0)}}function vQe(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:one.codex},i=jY(t,r.provider,n),a=AY(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=OY({provider:i,model:a,models:xY(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function MY(e){return e?.options?{[e.provider]:e.options}:null}function yQe(e){if(!e)return null;let t={};for(let[n,r]of Object.entries(e))r?.options&&(t[n]=r.options);return Object.keys(t).length>0?t:null}function bQe(e){if(e.activeSelection&&`providerAccountId`in e.activeSelection)return e.activeSelection.providerAccountId;for(let t of e.candidates)if(t?.provider===e.selectedProvider&&`providerAccountId`in t)return t.providerAccountId}function xQe(e){let t=t=>t!==void 0&&sq(t,e.selectedProvider)?void 0:t,n=t(e.threadModelSelection?.provider===e.selectedProvider?e.threadModelSelection.model:void 0),r=t(e.projectModelSelection?.provider===e.selectedProvider?e.projectModelSelection.model:void 0),i=aq(n??r,e.selectedProvider)??DY(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=bQe({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?AY(e.selectedProvider,e.settings,e.providers,s):i,l=yQe(e.draft?.modelSelectionByProvider)??MY(e.threadModelSelection)??MY(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var NY=nr({id:j,name:j,mimeType:j,sizeBytes:Ln,dataUrl:j}),PY=nr({id:j,name:j,mimeType:j,sizeBytes:Ln}),FY=nr({id:j,threadId:Vn,createdAt:j,terminalId:j,terminalLabel:j,lineStart:Ln,lineEnd:Ln}),SQe=nr({prompt:j,attachments:Jn(NY),files:cn(Jn(PY)),terminalContexts:Jn(FY),startedAt:j,commandId:cn(sn),messageId:cn(Hn),modelSelection:cn(Qn),runtimeMode:cn(Pn),interactionMode:cn(Gn),executionIntent:cn(nr({runtimeId:j,intentId:cn(j)}))});function IY(e,t){return Array.isArray(e)?e.flatMap(e=>t(e)??[]):[]}function CQe(e){if(!(!e||typeof e.runtimeId!=`string`))return{runtimeId:e.runtimeId,...typeof e.intentId==`string`?{intentId:e.intentId}:{}}}function wQe(e){return{...typeof e.commandId==`string`?{commandId:sn.make(e.commandId)}:{},...typeof e.messageId==`string`?{messageId:Hn.make(e.messageId)}:{}}}function TQe(e,t){let n=t.modelSelection(e.modelSelection);return{...n?{modelSelection:n}:{},...t.runtimeMode(e.runtimeMode)?{runtimeMode:e.runtimeMode}:{},...e.interactionMode==="default"||e.interactionMode===`plan`?{interactionMode:e.interactionMode}:{}}}function EQe(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.prompt!=`string`||typeof n.startedAt!=`string`)return null;let r=CQe(n.executionIntent);return{prompt:n.prompt,attachments:IY(n.attachments,t.attachment),files:IY(n.files,t.file),terminalContexts:IY(n.terminalContexts,t.terminalContext),startedAt:n.startedAt,...wQe(n),...TQe(n,t),...r?{executionIntent:r}:{}}}function DQe(e){return{id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}}function OQe(e){return{prompt:e.prompt,attachments:[...e.attachments],files:[...e.files],terminalContexts:e.terminalContexts.map(DQe),startedAt:e.startedAt,...e.commandId?{commandId:e.commandId}:{},...e.messageId?{messageId:e.messageId}:{},...e.modelSelection?{modelSelection:e.modelSelection}:{},...e.runtimeMode?{runtimeMode:e.runtimeMode}:{},...e.interactionMode?{interactionMode:e.interactionMode}:{},...e.executionIntent?{executionIntent:e.executionIntent}:{}}}function kQe(e){return e?{...e,attachments:[...e.attachments],files:[...e.files??[]],terminalContexts:e.terminalContexts.map(e=>({...e,text:``}))}:null}function AQe(e,t,n,r){let i=e[t];if(i?.stagedSubmission)return null;let a=MQe(i??jQe(),r,n);return a?{previousDraft:i,restoredDraft:a,drafts:{...e,[t]:a}}:null}function jQe(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function LY(e){return`${e.mimeType}\u0000${e.sizeBytes}\u0000${e.name}`}function RY(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function zY(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim(),i=gJ(t.text);if(!n||!r)return null;let a=Math.max(1,Math.floor(t.lineStart));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:a,lineEnd:Math.max(a,Math.floor(t.lineEnd)),text:i}}function BY(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=zY(e,a);if(!t)continue;let o=RY(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function MQe(e,t,n){let r=PQe(e,t);if(!r)return null;let i=NQe(e.files??[],t.files);if(r.images.length+i.length>8)return null;let a=FQe(e,t,n),o=[e.prompt,t.prompt].filter(e=>e.length>0).join(`
1014
- `);return{...e,prompt:xJ(o,a.contexts.length),images:r.images,files:i,persistedAttachments:r.attachments,terminalContexts:a.contexts,stashTerminalContexts:[...e.stashTerminalContexts??[],...a.restoredSnapshots]}}function NQe(e,t){let n=new Set(e.map(e=>e.id));return[...e,...t.filter(e=>!n.has(e.id))]}function PQe(e,t){let n=new Map(t.attachments.map(e=>[e.id,e])),r=[...e.images],i=e.persistedAttachments.filter(t=>e.images.some(e=>e.id===t.id)),a=new Set(r.map(e=>e.id)),o=new Set(r.map(LY));for(let e of t.images){let t=n.get(e.id);if(!t)return null;let s=LY(e);a.has(e.id)||o.has(s)||(r.push(e),i.push(t),a.add(e.id),o.add(s))}return r.length>8?null:{images:r,attachments:i}}function FQe(e,t,n){let r=[...e.terminalContexts],i=new Set(r.map(e=>e.id)),a=new Set(r.map(RY)),o=[];for(let e of t.terminalContexts){let t=zY(n,e);!t||i.has(t.id)||a.has(RY(t))||(r.push(t),o.push(t),i.add(t.id),a.add(RY(t)))}return{contexts:r,restoredSnapshots:o}}function IQe(e,t){return e.prompt===t.prompt&&JSON.stringify(e.attachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.files??[])===JSON.stringify((t.files??[]).map(({file:e,type:t,...n})=>n))&&JSON.stringify(e.terminalContexts??[])===JSON.stringify(t.terminalContexts.map(({text:e,...t})=>t))&&JSON.stringify(e.stashTerminalContexts??[])===JSON.stringify(t.stashTerminalContexts??[])}function VY(e){typeof URL<`u`&&e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function HY(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isFinite(i)||typeof a!=`string`||t.length===0||a.length===0?null:{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}}function UY(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i}=e;return typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,mimeType:r,sizeBytes:i}}async function LQe(e,t){let n=await Promise.all(e.map(async e=>{let n=await t.read(e);return{...e,type:`file`,file:n}}));return n.length===e.length?n:null}function RQe(e){let t=zQe(e.dataUrl,e.mimeType);return t?new File([t.content],e.name,{type:t.mimeType}):null}function zQe(e,t){let n=e.indexOf(`,`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);if(i.length===0)return null;try{return r.includes(`;base64`)?{content:HQe(i),mimeType:t}:{content:VQe(i),mimeType:BQe(r,t)}}catch{return null}}function BQe(e,t){return!e.startsWith(`data:`)||!e.includes(`;`)?t:e.slice(5,e.indexOf(`;`))||t}function VQe(e){return decodeURIComponent(e)}function HQe(e){let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function WY(e){return e.flatMap(e=>{let t=RQe(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function UQe(e){return{prompt:e.prompt,images:[...e.images],files:[...e.files??[]],persistedAttachments:[...e.persistedAttachments],terminalContexts:[...e.terminalContexts]}}function GY({file:e,previewUrl:t,...n}){return n}function WQe(e,t){return e.prompt===t.prompt&&JSON.stringify(e.images.map(GY))===JSON.stringify(t.images.map(GY))&&JSON.stringify((e.files??[]).map(({file:e,...t})=>t))===JSON.stringify(t.files.map(({file:e,...t})=>t))&&JSON.stringify(e.persistedAttachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.terminalContexts)===JSON.stringify(t.terminalContexts)}function KY(e){let{lastGeneratedPullRequestPrompt:t,...n}=e;return{...n,prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],stashTerminalContexts:[]}}function qY(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===0&&(e.files?.length??0)===0&&e.persistedAttachments.length===0&&e.terminalContexts.length===0&&Object.keys(e.modelSelectionByProvider).length===0&&e.activeProvider===null&&e.runtimeMode===null&&e.interactionMode===null&&e.stagedSubmission==null}function JY(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function YY(e){return Rn.some(t=>t===e)}function GQe(e){return gne.some(t=>t===e)}function XY(e,t,n){let r=e&&typeof e==`object`?e:null,i=r?.codex&&typeof r.codex==`object`?r.codex:null,a=r?.claudeAgent&&typeof r.claudeAgent==`object`?r.claudeAgent:null,o=YY(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&YY(n?.effort)?n.effort:void 0,s=i?.fastMode===!0?!0:i?.fastMode===!1?!1:t===`codex`&&n?.codexFastMode===!0||typeof n?.serviceTier==`string`&&n.serviceTier===`fast`||void 0,c=o!==void 0||s!==void 0?{...o===void 0?{}:{reasoningEffort:o},...s===void 0?{}:{fastMode:s}}:void 0,l=a?.thinking===!0||a?.thinking!==!1&&void 0,u=GQe(a?.effort)?a.effort:void 0,d=a?.fastMode===!0||a?.fastMode!==!1&&void 0,f=typeof a?.contextWindow==`string`&&a.contextWindow.length>0?a.contextWindow:void 0,p=l!==void 0||u!==void 0||d!==void 0||f!==void 0?{...l===void 0?{}:{thinking:l},...u===void 0?{}:{effort:u},...d===void 0?{}:{fastMode:d},...f===void 0?{}:{contextWindow:f}}:void 0;return!c&&!p?null:{...c?{codex:c}:{},...p?{claudeAgent:p}:{}}}function ZY(e,t){let n=e&&typeof e==`object`?e:null,r=JY(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=aq(i,r);if(!a)return null;let o=XY(n?.options?{[r]:n.options}:t?.modelOptions,r,r===`codex`?t?.legacyCodex:void 0),s=r===`codex`?o?.codex:o?.claudeAgent,c=n?.providerAccountId,l=typeof c==`string`&&c.trim().length>0?c.trim():void 0;return{provider:r,model:a,...l?{providerAccountId:l}:{},...s?{options:s}:{}}}function QY(e,t){if(e===null)return null;let n=t?.[e.provider];return{provider:e.provider,model:e.model,...`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...n?{options:n}:{}}}function $Y(e,t){return e?.options===void 0?XY(t):KQe(XY(t),e.provider,e.options)}function KQe(e,t,n){let{[t]:r,...i}=e??{},a=XY({[t]:n},t);return XY({...i,...a||{}})}function eX(e,t){let n={};if(t)for(let r of[`codex`,`claudeAgent`]){let i=t[r];i&&Object.keys(i).length>0&&(n[r]={provider:r,model:e?.provider===r?e.model:On[r],options:i})}return e&&(n[e.provider]=e),n}var tX=`forge:composer-drafts:v1`,nX=5,qQe=Fn([`local`,`worktree`]),rX=zte(Pn),iX=ZXe(aZe({storage:typeof localStorage<`u`?localStorage:kJ(),version:nX,canMigrate:ZQe}),300);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{iX.flush()});var JQe=nr({prompt:j,lastGeneratedPullRequestPrompt:cn(j),attachments:Jn(NY),files:cn(Jn(PY)),terminalContexts:cn(Jn(FY)),stashTerminalContexts:cn(Jn(nr({...FY.fields,text:j}))),modelSelectionByProvider:cn(In(er,cn(Qn))),activeProvider:cn(Kn(er)),runtimeMode:cn(Pn),interactionMode:cn(Gn),stagedSubmission:cn(SQe)});nr({effort:cn(Fn(Rn)),codexFastMode:cn(Xn),serviceTier:cn(j)}),nr({provider:cn(er),model:cn(j),modelOptions:cn(Kn(bn))}),nr({stickyProvider:cn(er),stickyModel:cn(j),stickyModelOptions:cn(Kn(bn))});var YQe=nr({threadId:Vn,environmentId:j,projectId:tn,logicalProjectKey:cn(j),createdAt:j,runtimeMode:Pn,interactionMode:Gn,branch:Kn(j),worktreePath:Kn(j),envMode:qQe,promotedTo:cn(Kn(nr({environmentId:j,threadId:j}))),anchorKind:cn(Qte),anchorCmmdId:cn(Kn(j)),linkedPullRequest:cn(Kn(rne))}),XQe=nr({draftsByThreadKey:In(j,JQe),draftThreadsByThreadKey:In(j,YQe),logicalProjectDraftThreadKeyByLogicalProjectKey:In(j,j),stickyModelSelectionByProvider:cn(In(er,cn(Qn))),stickyActiveProvider:cn(Kn(er))}),aX=nr({version:Ln,state:XQe}),oX=vn(aX);function ZQe(e,t){if(e===null)return!0;try{let n=JSON.parse(e);if(!n||typeof n!=`object`)return!1;let r=n;return r.version===t?(oX(n),!0):typeof r.version==`number`&&Number.isInteger(r.version)&&r.version>=1&&r.version<t&&r.state!==null&&typeof r.state==`object`}catch{return!1}}function QQe(e){if(e===null)return new Set;try{let t=oX(JSON.parse(e));if(t.version!==nX)return null;let n=new Set;for(let e of Object.values(t.state.draftsByThreadKey)){for(let t of e.files??[])n.add(t.id);for(let t of e.stagedSubmission?.files??[])n.add(t.id)}return n}catch{return null}}function $Qe(){iX.flush()}var sX=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),cX=[],e$e=[],lX=[],uX=[],t$e=[];Object.freeze(cX),Object.freeze(lX),Object.freeze(uX);var dX=Object.freeze({}),n$e=Object.freeze({activeProvider:null,modelSelectionByProvider:dX}),r$e=Object.freeze({prompt:``,images:cX,files:e$e,nonPersistedImageIds:lX,persistedAttachments:uX,terminalContexts:t$e,modelSelectionByProvider:dX,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function fX(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function pX(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.threadId,i=t.createdAt,a=t.lineStart,o=t.lineEnd;if(typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0||typeof i!=`string`||i.length===0||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`number`||!Number.isFinite(o))return null;let s=typeof t.terminalId==`string`?t.terminalId.trim():``,c=typeof t.terminalLabel==`string`?t.terminalLabel.trim():``;if(s.length===0||c.length===0)return null;let l=Math.max(1,Math.floor(a));return{id:n,threadId:r,createdAt:i,terminalId:s,terminalLabel:c,lineStart:l,lineEnd:Math.max(l,Math.floor(o))}}function i$e(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function mX(e){return Bo(e)}function hX(e){return e.trim()}function gX(e){return typeof e==`string`?e.trim():Vo(e)}function _X(e,t){let n=Wo(e);return n?gX(n):t?.environmentId?gX(Lo(t.environmentId,e)):e}function a$e(e){return Wo(e)}function vX(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?qt.make(e):null}return t}function yX(e,t){let n=vX(e,t);if(!n)return null;if(typeof n!=`string`){let t=gX(n);if(e.draftsByThreadKey[t])return t;for(let[t,r]of Object.entries(e.draftThreadsByThreadKey))if(r.environmentId===n.environmentId&&r.threadId===n.threadId)return t;return t}let r=gX(n);return r.length>0?r:null}function bX(e,t){let n=vX(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??Vn.make(n):n.threadId:null}function xX(e,t){let n=yX(e,t);return n?e.draftsByThreadKey[n]??null:null}function o$e(e,t){return Object.values(e).includes(t)}function SX(e,t){return{draftId:e,...t}}function s$e(e,t,n,r,i){let a=r!==void 0&&(r.environmentId!==e.environmentId||r.projectId!==e.projectId),o=i?.worktreePath===void 0?a?null:r?.worktreePath??null:i.worktreePath??null,s=i?.branch===void 0?a?null:r?.branch??null:i.branch??null,c=i?.anchorKind===void 0?r?.anchorKind:i.anchorKind??void 0;return{threadId:t,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:n,createdAt:i?.createdAt??r?.createdAt??new Date().toISOString(),runtimeMode:i?.runtimeMode??r?.runtimeMode??`full-access`,interactionMode:i?.interactionMode??r?.interactionMode??`default`,branch:s,worktreePath:o,envMode:i?.envMode??(o?`worktree`:a?`local`:r?.envMode??`local`),promotedTo:null,cmmdTaskId:i?.cmmdTaskId===void 0?r?.cmmdTaskId??null:i.cmmdTaskId,anchorCmmdId:i?.anchorCmmdId===void 0?r?.anchorCmmdId??null:i.anchorCmmdId,linkedPullRequest:i?.linkedPullRequest===void 0?r?.linkedPullRequest??null:i.linkedPullRequest,...c===void 0?{}:{anchorKind:c}}}function CX(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function wX(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function c$e(e,t){return!!e&&e.threadId===t.threadId&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.logicalProjectKey===t.logicalProjectKey&&e.createdAt===t.createdAt&&e.runtimeMode===t.runtimeMode&&e.interactionMode===t.interactionMode&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.envMode===t.envMode&&(e.anchorKind??void 0)===(t.anchorKind??void 0)&&(e.anchorCmmdId??null)===(t.anchorCmmdId??null)&&TX(e.linkedPullRequest,t.linkedPullRequest)&&CX(e.promotedTo,t.promotedTo)}function TX(e,t){return(e?.projectId??null)===(t?.projectId??null)&&(e?.projectRepositoryId??null)===(t?.projectRepositoryId??null)&&(e?.provider??null)===(t?.provider??null)&&(e?.host??null)===(t?.host??null)&&(e?.repository??null)===(t?.repository??null)&&(e?.number??null)===(t?.number??null)&&(e?.url??null)===(t?.url??null)}function EX(e,t){let n=Object.fromEntries(Object.entries(e.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(([,e])=>e!==t)),{[t]:r,...i}=e.draftThreadsByThreadKey,{[t]:a,...o}=e.draftsByThreadKey;return{draftsByThreadKey:o,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n}}function DX(e,t){let n={},r=new Map;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(typeof n!=`string`||n.length===0)continue;let t=Uo(e);if(!t)continue;let i=Wo(n);if(i){r.set(i.threadId,i.environmentId);continue}r.set(n,t.environmentId)}if(e&&typeof e==`object`)for(let[t,i]of Object.entries(e)){if(typeof t!=`string`||t.length===0||!i||typeof i!=`object`)continue;let e=i,a=Wo(t),o=_X(t),s=a?.threadId??(typeof e.threadId==`string`&&e.threadId.length>0?e.threadId:t),c=a?.environmentId??(typeof e.environmentId==`string`&&e.environmentId.length>0?e.environmentId:r.get(t)),l=e.projectId,u=e.createdAt,d=e.branch,f=e.worktreePath,p=typeof f==`string`?f:null,m=e.promotedTo,h=m&&typeof m==`object`?m:null,g=h&&typeof h.environmentId==`string`&&h.environmentId.length>0&&typeof h.threadId==`string`&&h.threadId.length>0?Lo(h.environmentId,h.threadId):null;if(typeof l!=`string`||l.length===0||c===void 0)continue;let _=c;n[o]={threadId:s,environmentId:_,projectId:l,logicalProjectKey:typeof e.logicalProjectKey==`string`&&e.logicalProjectKey.length>0?e.logicalProjectKey:a?mX(Io(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:rX(e.runtimeMode)?e.runtimeMode:pJ,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:mJ,branch:typeof d==`string`?d:null,worktreePath:p,envMode:i$e(e.envMode,p),promotedTo:g}}let i={};if(t&&typeof t==`object`)for(let[e,a]of Object.entries(t)){if(typeof a!=`string`||a.length===0)continue;let t=Uo(e),o=Wo(a),s=_X(a);if(i[e]=s,o&&r.set(o.threadId,o.environmentId),!t){let t=n[s];t&&!t.logicalProjectKey&&(n[s]={...t,logicalProjectKey:e});continue}n[s]?(n[s]?.projectId!==t.projectId||n[s]?.environmentId!==t.environmentId)&&(n[s]={...n[s],threadId:n[s].threadId,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e}):n[s]={threadId:o?.threadId??s,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e,createdAt:new Date().toISOString(),runtimeMode:pJ,interactionMode:mJ,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function OX(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=a$e(e);t&&n.set(t.threadId,r.environmentId)}let r={};for(let[i,a]of Object.entries(e)){if(typeof i!=`string`||i.length===0||!a||typeof a!=`object`)continue;let e=a,o=typeof e.prompt==`string`?e.prompt:``,s=typeof e.lastGeneratedPullRequestPrompt==`string`?e.lastGeneratedPullRequestPrompt:void 0,c=Array.isArray(e.attachments)?e.attachments.flatMap(e=>{let t=HY(e);return t?[t]:[]}):[],l=Array.isArray(e.files)?e.files.flatMap(e=>{let t=UY(e);return t?[t]:[]}):[],u=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=pX(e);return t?[t]:[]}):[],d=Array.isArray(e.stashTerminalContexts)?e.stashTerminalContexts.flatMap(e=>{let t=pX(e),n=typeof e.text==`string`?e.text:``;return t&&n.length>0?[{...t,text:n}]:[]}):[],f=rX(e.runtimeMode)?e.runtimeMode:null,p=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,m=EQe(e.stagedSubmission,{attachment:HY,file:UY,terminalContext:pX,modelSelection:e=>ZY(e)??null,runtimeMode:rX}),h=xJ(o,u.length),g=a,_={},v=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)_=e.modelSelectionByProvider,v=JY(e.activeProvider);else{let e=XY(g.modelOptions,void 0,g)??null,t=ZY(g.modelSelection,{provider:g.provider,model:g.model,modelOptions:e??g.modelOptions,legacyCodex:g}),n=$Y(t,e),r=QY(t,n);_=eX(r,n),v=r?.provider??null}let y=Object.keys(_).length>0||v!==null;if(o.length===0&&c.length===0&&l.length===0&&u.length===0&&d.length===0&&!y&&!f&&!p&&!m)continue;let b=Wo(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?_X(i,{environmentId:e}):i})():i:_X(i);r[b]={prompt:h,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{files:l}:{},...u.length>0?{terminalContexts:u}:{},...d.length>0?{stashTerminalContexts:d}:{},...y?{modelSelectionByProvider:_,activeProvider:v}:{},...f?{runtimeMode:f}:{},...p?{interactionMode:p}:{},...m?{stagedSubmission:m}:{}}}return r}function l$e(e){if(!e||typeof e!=`object`)return sX;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=XY(t.stickyModelOptions)??{},o=ZY(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=$Y(o,a),c=eX(QY(o,s),s),l=JY(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=DX(r,i);return{draftsByThreadKey:OX(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function u$e(e){let t={};for(let[n,r]of Object.entries(e.draftsByThreadKey)){if(typeof n!=`string`||n.length===0)continue;let e=Object.keys(r.modelSelectionByProvider).length>0||r.activeProvider!==null;r.prompt.length===0&&r.lastGeneratedPullRequestPrompt===void 0&&r.persistedAttachments.length===0&&(r.files?.length??0)===0&&r.terminalContexts.length===0&&!e&&r.runtimeMode===null&&r.interactionMode===null&&r.stagedSubmission==null||(t[n]={prompt:r.prompt,...r.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:r.lastGeneratedPullRequestPrompt},attachments:r.persistedAttachments,...(r.files?.length??0)>0?{files:r.files.map(({file:e,type:t,...n})=>n)}:{},...r.terminalContexts.length>0?{terminalContexts:r.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}))}:{},...r.stashTerminalContexts&&r.stashTerminalContexts.length>0?{stashTerminalContexts:r.stashTerminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd,text:e.text}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:OQe(r.stagedSubmission)}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function d$e(e){if(!e||typeof e!=`object`)return sX;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=DX(t.draftThreadsByThreadKey??t.draftThreadsByThreadId,t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId),i={},a=null;if(t.stickyModelSelectionByProvider&&typeof t.stickyModelSelectionByProvider==`object`)i=t.stickyModelSelectionByProvider,a=JY(t.stickyActiveProvider);else{let e=XY(t.stickyModelOptions)??{},n=ZY(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=$Y(n,e);i=eX(QY(n,r),r),a=JY(t.stickyProvider)}return{draftsByThreadKey:OX(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function f$e(e){if(e.length===0)return[];try{let t=yl(tX,aX);return!t||t.version!==nX?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function p$e(e){if(e.length===0)return null;try{let t=iX.getItem(tX);if(typeof t!=`string`)return null;let n=oX(JSON.parse(t));return!n||n.version!==nX?null:n.state.draftsByThreadKey[e]??null}catch{return null}}function m$e(e,t,n){let r=new Set;try{iX.flush(),r=new Set(f$e(e))}catch{r=new Set}n(n=>{let i=n.draftsByThreadKey[e];if(!i)return n;let a=new Set(i.images.map(e=>e.id)),o=t.filter(e=>a.has(e.id)&&r.has(e.id)),s=i.images.map(e=>e.id).filter(e=>!r.has(e)),c={...i,persistedAttachments:o,nonPersistedImageIds:s},l={...n.draftsByThreadKey};return qY(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function h$e(e,t){return e.length>0?e:t?.prompt??``}function kX(e,t){return e?.length?e:t??[]}function g$e(e){let t=e.stagedSubmission;return{prompt:h$e(e.prompt,t),attachments:kX(e.attachments,t?.attachments),files:kX(e.files,t?.files),terminalContexts:kX(e.terminalContexts,t?.terminalContexts)}}function _$e(e){let t=e.modelSelectionByProvider??{},n=JY(e.activeProvider)??null,r=g$e(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:WY(r.attachments),files:r.files.map(e=>({...e,type:`file`,file:null})),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],terminalContexts:r.terminalContexts.map(t=>{let n=e.stashTerminalContexts?.find(e=>e.id===t.id);return Object.assign({},t,{text:n?.text??``})}),...e.stashTerminalContexts&&e.stashTerminalContexts.length>0?{stashTerminalContexts:e.stashTerminalContexts.map(e=>({...e}))}:{},modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:kQe(e.stagedSubmission)}}function v$e(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??mX(Io(e.environmentId,e.projectId)),createdAt:e.createdAt,runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,branch:e.branch,worktreePath:e.worktreePath,envMode:e.envMode,promotedTo:e.promotedTo?Lo(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var AX=Xt()(wJ((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>xX(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=hX(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||wX(i)?null:SX(qt.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!wX(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return SX(qt.make(n),r);return null},getDraftSession:e=>t().draftThreadsByThreadKey[e]??null,getDraftSessionByRef:e=>{for(let n of Object.values(t().draftThreadsByThreadKey))if(n.environmentId===e.environmentId&&n.threadId===e.threadId)return n;return null},getDraftThread:e=>typeof e==`string`?t().getDraftSession(qt.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Vo(Lo(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=hX(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=s$e(t,i?.threadId??n?.threadId??Vn.make(r),a,n,i);if(o===r&&c$e(n,s))return e;let c={...e.logicalProjectDraftThreadKeyByLogicalProjectKey,[a]:r},l={...e.draftThreadsByThreadKey,[r]:s},u=e.draftsByThreadKey,d=o===void 0?void 0:l[o];return o&&o!==r&&!o$e(c,o)&&!wX(d)&&(delete l[o],e.draftsByThreadKey[o]!==void 0&&(u={...e.draftsByThreadKey},delete u[o])),{draftsByThreadKey:u,draftThreadsByThreadKey:l,logicalProjectDraftThreadKeyByLogicalProjectKey:c}})},setProjectDraftThreadId:(e,n,r)=>{t().setLogicalProjectDraftThreadId(mX(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r.projectRef??{environmentId:t.environmentId,projectId:t.projectId};if(n.projectId.length===0||n.environmentId.length===0)return e;let a=n.environmentId!==t.environmentId||n.projectId!==t.projectId,o=r.worktreePath===void 0?a?null:t.worktreePath:r.worktreePath??null,s=r.branch===void 0?a?null:t.branch:r.branch??null,c=r.anchorKind===void 0?t.anchorKind:r.anchorKind??void 0,l={threadId:t.threadId,environmentId:n.environmentId,projectId:n.projectId,logicalProjectKey:t.logicalProjectKey,createdAt:r.createdAt===void 0?t.createdAt:r.createdAt||t.createdAt,runtimeMode:r.runtimeMode??t.runtimeMode,interactionMode:r.interactionMode??t.interactionMode,branch:s,worktreePath:o,envMode:r.envMode??(o?`worktree`:a?`local`:t.envMode??`local`),promotedTo:t.promotedTo??null,cmmdTaskId:r.cmmdTaskId===void 0?t.cmmdTaskId??null:r.cmmdTaskId,anchorCmmdId:r.anchorCmmdId===void 0?t.anchorCmmdId??null:r.anchorCmmdId,linkedPullRequest:r.linkedPullRequest===void 0?t.linkedPullRequest??null:r.linkedPullRequest,...c===void 0?{}:{anchorKind:c}};return l.environmentId===t.environmentId&&l.projectId===t.projectId&&l.logicalProjectKey===t.logicalProjectKey&&l.createdAt===t.createdAt&&l.runtimeMode===t.runtimeMode&&l.interactionMode===t.interactionMode&&l.branch===t.branch&&l.worktreePath===t.worktreePath&&l.envMode===t.envMode&&(l.anchorKind??void 0)===(t.anchorKind??void 0)&&(l.anchorCmmdId??null)===(t.anchorCmmdId??null)&&TX(l.linkedPullRequest,t.linkedPullRequest)&&CX(l.promotedTo,t.promotedTo)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:l}}})},clearProjectDraftThreadId:e=>{n(t=>{let n=Object.entries(t.draftThreadsByThreadKey).find(([,t])=>t.projectId===e.projectId&&t.environmentId===e.environmentId);return n?EX(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=yX(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:EX(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=yX(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??Lo(t.environmentId,t.threadId);return CX(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!wX(t))return e;let n=gX(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return EX(a?{...e,draftsByThreadKey:{...e.draftsByThreadKey,[n]:i?{...i,modelSelectionByProvider:{...i.modelSelectionByProvider,...a.modelSelectionByProvider},activeProvider:a.activeProvider,runtimeMode:a.runtimeMode,interactionMode:a.interactionMode}:a}}:e,r)})},clearDraftThread:e=>{let r=yX(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)VY(e.previewUrl);n(e=>{let t=e.draftThreadsByThreadKey[r]!==void 0,n=Object.values(e.logicalProjectDraftThreadKeyByLogicalProjectKey).includes(r),i=e.draftsByThreadKey[r]!==void 0;return!t&&!n&&!i?e:EX(e,r)})},setStickyModelSelection:e=>{let t=ZY(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return Qe(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.stickyModelSelectionByProvider,n=e.stickyActiveProvider;if(Object.keys(t).length===0&&n===null)return e;let i=e.draftsByThreadKey[r]??fX(),a={...i.modelSelectionByProvider};for(let[e,n]of Object.entries(t))if(n){let t=a[e];a[e]={...n,model:t?.model??n.model}}if(Qe(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return qY(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return qY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return qY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r,i,a,o,s,c)=>{let l=yX(t(),e)??``;l.length!==0&&(n(e=>{let t=e.draftsByThreadKey[l];if(!t)return e;let n={prompt:t.prompt,attachments:[...c??t.persistedAttachments],files:(t.files??[]).map(({file:e,type:t,...n})=>n),terminalContexts:[...t.terminalContexts],startedAt:r,commandId:i,messageId:a,...o?{executionIntent:o}:{},...s},u={...e.draftsByThreadKey};return u[l]={...t,stagedSubmission:n},{draftsByThreadKey:u}}),iX.flush())},setStagedComposerExecutionIntent:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&(n(e=>{let t=e.draftsByThreadKey[i];return t?.stagedSubmission?{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,stagedSubmission:{...t.stagedSubmission,executionIntent:r}}}}:e}),iX.flush())},clearStagedComposerSubmission:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t?.stagedSubmission)return e;let n={...t,stagedSubmission:null},i={...e.draftsByThreadKey};return qY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r,i)=>{let a=yX(t(),e),o=bX(t(),e);if(!a||!o)return;let s=BY(o,r);n(e=>{let t=e.draftsByThreadKey[a]??fX(),n={...t,prompt:xJ(t.prompt,s.length),terminalContexts:s,...i?.preserveTextForReload?{stashTerminalContexts:s}:{stashTerminalContexts:[]}},r={...e.draftsByThreadKey};return qY(n)?delete r[a]:r[a]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return;let a=ZY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??fX(),r={...n.modelSelectionByProvider};if(a){let e=r[a.provider];a.options===void 0?r[a.provider]={provider:a.provider,model:a.model,...`providerAccountId`in a&&a.providerAccountId?{providerAccountId:a.providerAccountId}:e&&`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...e?.options?{options:e.options}:{}}:r[a.provider]=a}let o=a?.provider??n.activeProvider;if(Qe(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return qY(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return;let a=XY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??fX(),r={...n.modelSelectionByProvider};for(let e of[`codex`,`claudeAgent`]){if(!a||!(e in a))continue;let t=a[e],n=r[e];if(t)r[e]={provider:e,model:n?.model??On[e],...n&&`providerAccountId`in n&&n.providerAccountId?{providerAccountId:n.providerAccountId}:{},options:t};else if(n?.options){let{options:t,...i}=n;r[e]=i}}if(Qe(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return qY(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=yX(t(),e)??``;if(o.length===0)return;let s=JY(r);if(s===null)return;let c=XY({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??fX(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??On[s],...r&&`providerAccountId`in r&&r.providerAccountId?{providerAccountId:r.providerAccountId}:{},options:c};else if(r?.options){let{options:e,...t}=r;n[s]=t}let i=e.stickyModelSelectionByProvider,l=e.stickyActiveProvider;if(a?.persistSticky===!0){i={...e.stickyModelSelectionByProvider};let n=i[s]??t.modelSelectionByProvider[s]??{provider:s,model:On[s]};if(c)i[s]={...n,provider:s,options:c};else if(n.options){let{options:e,...t}=n;i[s]=t}l=t.activeProvider??s}if(Qe(t.modelSelectionByProvider,n)&&Qe(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return qY(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return;let a=rX(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??fX();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return qY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return;let a=r===`plan`||r==="default"?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??fX();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return qY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=yX(t(),e),i=bX(t(),e);!r||!i||t().addImages(typeof e==`string`?qt.make(r):e,[n])},addImages:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX(),n=new Set(t.images.map(e=>e.id)),a=new Set(t.images.map(e=>LY(e))),o=new Set(t.images.map(e=>e.previewUrl)),s=[];for(let e of r){let t=LY(e);if(n.has(e.id)||a.has(t)){o.has(e.previewUrl)||VY(e.previewUrl);continue}s.push(e),n.add(e.id),a.add(t),o.add(e.previewUrl)}return s.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,images:[...t.images,...s]}}}})},addFiles:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX(),n=new Set((t.files??[]).map(e=>e.id)),a=Math.max(0,8-t.images.length-(t.files?.length??0)),o=r.filter(e=>!n.has(e.id)).slice(0,a);return o.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...t.files??[],...o]}}}})},setFiles:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??fX();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...r]}}}})},removeImage:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return;let a=t().draftsByThreadKey[i];if(!a)return;let o=a.images.find(e=>e.id===r);o&&VY(o.previewUrl),n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,images:t.images.filter(e=>e.id!==r),nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>e!==r),persistedAttachments:t.persistedAttachments.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return qY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=yX(t(),e),s=bX(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??fX(),n=zY(s,i);if(!n)return e;let l=RY(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>RY(e)===l))return e;c=!0;let u=Math.max(0,Math.min(t.terminalContexts.length,a)),d={...t,prompt:r,terminalContexts:[...t.terminalContexts.slice(0,u),n,...t.terminalContexts.slice(u)]};return{draftsByThreadKey:{...e.draftsByThreadKey,[o]:d}}}),c},addTerminalContext:(e,n)=>{let r=yX(t(),e),i=bX(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?qt.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=yX(t(),e),a=bX(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??fX(),n=BY(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:xJ(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=yX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,terminalContexts:t.terminalContexts.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return qY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t||t.terminalContexts.length===0)return e;let n={...t,terminalContexts:[]},i={...e.draftsByThreadKey};return qY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n={...t,persistedAttachments:[],nonPersistedImageIds:[]},i={...e.draftsByThreadKey};return qY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=yX(t(),e);if(!i)return;let a=new Set(r.map(e=>e.id));n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,persistedAttachments:r,nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>!a.has(e))},o={...e.draftsByThreadKey};return qY(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{m$e(i,r,n)})},moveComposerDraft:(e,r)=>{let i=yXe(t().draftsByThreadKey,e,r);return i!==null&&(n({draftsByThreadKey:i}),iX.flush(),!0)},clearComposerContent:e=>{let r=yX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n=KY(t),i={...e.draftsByThreadKey};return qY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearComposerContentIfUnchanged:(e,r)=>{let i=yX(t(),e)??``;if(i.length===0)return!1;let a=!1;return n(e=>{let t=e.draftsByThreadKey[i];if(!t||!WQe(t,r))return e;let n=KY(t),o={...e.draftsByThreadKey};return qY(n)?delete o[i]:o[i]=n,a=!0,{draftsByThreadKey:o}}),a},restoreComposerStash:(e,r)=>{let i=yX(t(),e)??``,a=bX(t(),e);if(i.length===0||!a)return!1;let o,s;if(n(e=>{let t=AQe(e.draftsByThreadKey,i,a,r);return t?(o=t.previousDraft,s=t.restoredDraft,{draftsByThreadKey:t.drafts}):e}),!s)return!1;let c=!1;try{iX.flush();let e=p$e(i),n=t().draftsByThreadKey[i];e!==null&&n===s&&IQe(e,n)&&(c=!0)}catch{}if(c&&(r.onPersisted?.()??!0))return!0;n(e=>{if(e.draftsByThreadKey[i]!==s)return e;let t={...e.draftsByThreadKey};return o?t[i]=o:delete t[i],{draftsByThreadKey:t}});try{iX.flush()}catch{}return!1}}},{name:tX,version:nX,storage:SJ(()=>iX),migrate:l$e,partialize:u$e,merge:(e,t)=>{let n=d$e(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,_$e(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,v$e(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function y$e(e){let t=(0,cl.c)(2),n;return t[0]===e?n=t[1]:(n=t=>xX(t,e)??r$e,t[0]=e,t[1]=n),AX(n)}function b$e(e){let t=(0,cl.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=xX(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:n$e},t[0]=e,t[1]=n),AX(OJ(n))}function jX(e){let t=AX.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(qt.make(n),e)}function x$e(e){for(let t of e)jX(t)}function S$e(e){let t=AX.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(qt.make(n))}function C$e(e){let t=new Set,n=new Map(e.snapshotThreads.map(e=>[e.key,e]));for(let n of e.snapshotThreads)n.deletedAt===null&&n.archivedAt===null&&t.add(n.key);for(let r of e.draftThreadKeys){let e=n.get(r);e&&(e.deletedAt!==null||e.archivedAt!==null)||t.add(r)}return t}function w$e(e){let t=new Map,n=!1;for(let r of e)switch(r.type){case`thread.turn-diff-completed`:case`thread.reverted`:n=!0;break;case`thread.created`:t.set(r.payload.threadId,{clearPromotedDraft:!0,clearDeletedThread:!1,removeTerminalState:!1});break;case`thread.deleted`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!0,removeTerminalState:!0});break;case`thread.archived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!0});break;case`thread.unarchived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!1})}let r=[],i=[],a=[];for(let[e,n]of t)n.clearPromotedDraft&&r.push(e),n.clearDeletedThread&&i.push(e),n.removeTerminalState&&a.push(e);return{promoteDraftThreadIds:r,clearDeletedThreadIds:i,removeTerminalStateThreadIds:a,needsProviderInvalidation:n}}var MX={all:[`projects`],searchContents:(e,t,n,r,i,a,o)=>[`projects`,`search-contents`,e??null,t,n,r,i,a,o],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},NX={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function T$e(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function E$e(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:T$e(e.cursors)}}}var PX={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,E$e(t)],stats:(e,t)=>[`pullRequests`,e,`stats`,[...t].toSorted((e,t)=>`${e.projectId}:${e.repository}#${e.number}`.localeCompare(`${t.projectId}:${t.repository}#${t.number}`))],detail:(e,t)=>[`pullRequests`,e,`detail`,t],activity:(e,t)=>[`pullRequests`,e,`activity`,t],diff:(e,t)=>[`pullRequests`,e,`diff`,t],threadComments:(e,t)=>[`pullRequests`,e,`thread-comments`,t],diffFileContents:(e,t)=>[`pullRequests`,e,`diff-file-contents`,t],reviewerCandidates:(e,t)=>[`pullRequests`,e,`reviewer-candidates`,t]},D$e=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function O$e(e,t){let n=new URL(e);return n.pathname=`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${t.startsWith(`/`)?t:`/${t}`}`,n.search=``,n.hash=``,n.toString()}async function k$e(e,t){let n=await e.text();if(!n)return t;try{let e=JSON.parse(n);if(typeof e.error==`string`&&e.error.length>0)return e.error}catch{}return n}async function FX(e){let t=O$e(e.httpBaseUrl,e.pathname),n;try{n=await fetch(t,{method:e.method??`GET`,headers:{...e.body===void 0?{}:{"content-type":`application/json`},...e.bearerToken?{authorization:`Bearer ${e.bearerToken}`}:{}},...e.body===void 0?{}:{body:JSON.stringify(e.body)},...e.signal?{signal:e.signal}:{}})}catch(e){throw Error(`Failed to fetch remote auth endpoint ${t} (${e.message}).`,{cause:e})}if(!n.ok)throw new D$e(await k$e(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function IX(e){return FX({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function A$e(e){return FX({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function j$e(e){return FX({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function LX(e){let t=new URL(e.wsBaseUrl,window.location.origin);if(e.runtimeTicket)return t.searchParams.set(`runtimeTicket`,e.runtimeTicket),t.searchParams.delete(`wsToken`),t.toString();let n=await j$e({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}var M$e=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null}),RX=()=>({...M$e}),zX=Xt()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:RX()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??RX(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})}));function N$e(e){return new Promise(t=>globalThis.setTimeout(t,e))}function BX(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function VX(e){if(e?.aborted)throw BX()}function HX(e,t){return t?t.aborted?Promise.reject(BX()):new Promise((n,r)=>{let i=()=>r(BX());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function UX(e,t){return t?t.aborted?Promise.reject(BX()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(BX())};t.addEventListener(`abort`,a,{once:!0})}):N$e(e)}function WX(e){let t=GK(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=zX.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}function GX(e){return!!e.runtimeId?.trim()||Dl(e.environmentId).isCloud}function P$e(e){let t=e.replacesEnvironmentId?an.make(e.replacesEnvironmentId):null,n=t&&t!==e.environmentId?GK(t):null;return{existing:GK(e.environmentId)??n,replacedRecord:n}}async function F$e(e){return{records:WK(),bearerToken:e?await XK(e.environmentId):null}}async function KX(e){let t=e.replacedRecord?.environmentId??e.record.environmentId;await zl(e.rollback.records),await ZK(e.record.environmentId).catch(()=>void 0),e.rollback.bearerToken&&await iYe(t,e.rollback.bearerToken)}async function I$e(e){try{e.replacedRecord?await rYe(e.replacedRecord.environmentId,e.record):await YK(e.record),VX(e.signal),await ZK(e.record.environmentId),e.replacedRecord&&await ZK(e.replacedRecord.environmentId),VX(e.signal)}catch(t){try{await KX(e)}catch(e){let n=AggregateError([t,e],`Cloud Environment rollback failed.`);throw n.cause=t,n}throw t}}function L$e(e,t){if(t){Rne(t,e);return}zne(e)}function R$e(e){let t=null,n=[];for(let r of e.split(/\r?\n/)){if(r.startsWith(`event:`)){t=r.slice(6).trim();continue}r.startsWith(`data:`)&&n.push(r.slice(5).trimStart())}return{eventName:t,data:n.join(`
1015
- `)}}function z$e(e,t){let n=R$e(e);if(n.eventName!==`phase`||!n.data)return!1;try{let e=JSON.parse(n.data);return L$e(e,t),e.phase===`app-ready`||e.phase===`error`}catch{return!1}}async function B$e(e,t,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``;for(;!n.aborted;){let{done:e,value:n}=await r.read();if(e)break;a+=i.decode(n,{stream:!0});let o=a.indexOf(`
1012
+ `)){let e=/^- (.+):$/.exec(t);if(e){r(),n={header:e[1],bodyLines:[]};continue}if(n){if(t.startsWith(` `)){n.bodyLines.push(t.slice(2));continue}t.length===0&&n.bodyLines.push(``)}}return r(),t}function yJ(e){let t=0;for(let n of e)n===``&&(t+=1);return t}function bJ(e,t){let n=t-yJ(e);return n<=0?e:`${``.repeat(n)}${e}`}function WXe(e){return e===void 0||e===` `||e===`
1013
+ `||e===` `||e===`\r`}function GXe(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${WXe(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:yJ(e.slice(0,n))}}function KXe(e){return e.replaceAll(``,``)}function qXe(e,t){if(t<0)return{prompt:e,cursor:e.length};let n=0;for(let r=0;r<e.length;r+=1)if(e[r]===``){if(n===t)return{prompt:e.slice(0,r)+e.slice(r+1),cursor:r};n+=1}return{prompt:e,cursor:e.length}}function xJ(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var SJ=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return SJ(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return SJ(t)(e)}}}},CJ=(e,t)=>(n,r,i)=>{let a={storage:xJ(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return SJ(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p},wJ=e=>Symbol.iterator in e,TJ=e=>`entries`in e,EJ=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},JXe=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function YXe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:wJ(e)&&wJ(t)?TJ(e)&&TJ(t)?EJ(e,t):JXe(e,t):EJ({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function DJ(e){let t=F.useRef(void 0);return n=>{let r=e(n);return YXe(t.current,r)?t.current:t.current=r}}function OJ(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function XXe(e){return e!=null&&typeof e.getItem==`function`&&typeof e.setItem==`function`&&typeof e.removeItem==`function`}function kJ(e){return XXe(e)?e:OJ()}var AJ=OJ();function jJ(){return globalThis.localStorage||globalThis.window?.localStorage}var MJ={getItem:e=>{try{let t=jJ()?.getItem(e);if(t!==void 0)return t}catch{}return AJ.getItem(e)},setItem:(e,t)=>{try{let n=jJ();if(n){n.setItem(e,t);return}}catch{}AJ.setItem(e,t)},removeItem:e=>{try{let t=jJ();if(t){t.removeItem(e);return}}catch{}AJ.removeItem(e)}};function NJ(e){let t=MJ.getItem(e);return typeof t==`string`?t:null}function PJ(e,t){MJ.setItem(e,t)}function ZXe(e){MJ.removeItem(e)}function QXe(e,t=300){let n=kJ(e),r=new Qt((e,t)=>{n.setItem(e,t)},{wait:t});return{getItem:e=>n.getItem(e),setItem:(e,t)=>{r.maybeExecute(e,t)},removeItem:e=>{r.cancel(),n.removeItem(e)},flush:()=>{r.flush()}}}var FJ=[`draftsByThreadKey`,`draftThreadsByThreadKey`,`logicalProjectDraftThreadKeyByLogicalProjectKey`],$Xe=[`stickyModelSelectionByProvider`,`stickyActiveProvider`];function eZe(e){let t=IJ(e.nextLocal,e.version,!1);if(!t)return e.currentStored??e.nextLocal;if(e.currentStored!==null&&e.canMigrate!==void 0&&!e.canMigrate(e.currentStored,e.version))return e.currentStored;if(e.previousLocal===e.currentStored&&(e.canMigrate??tZe)(e.currentStored,e.version))return e.nextLocal;let n=IJ(e.previousLocal,e.version,!0),r=IJ(e.currentStored,e.version,!0);if(!r||!n)return e.currentStored??e.nextLocal;let i={...r.state};for(let e of FJ)i[e]=aZe(n.state[e],r.state[e],t.state[e]);for(let e of $Xe)LJ(n.state[e],t.state[e])||(i[e]=t.state[e]);return JSON.stringify({...r,version:e.version,state:i})}function tZe(e,t){if(e===null)return!0;try{let n=JSON.parse(e);return!RJ(n)||!RJ(n.state)||typeof n.version!=`number`||!Number.isInteger(n.version)?!1:n.version>=1&&n.version<t}catch{return!1}}function IJ(e,t,n){if(e===null)return n?{version:t,state:iZe()}:null;let r=nZe(e);return r&&rZe(r,t)?{version:t,state:r.state}:null}function nZe(e){try{let t=JSON.parse(e);return RJ(t)?t:null}catch{return null}}function rZe(e,t){let n=e.state;return e.version!==t||!RJ(n)?!1:FJ.every(e=>RJ(n[e]))}function iZe(){return Object.fromEntries(FJ.map(e=>[e,{}]))}function aZe(e,t,n){let r={...t};for(let t of new Set([...Object.keys(e),...Object.keys(n)]))LJ(e[t],n[t])||(t in n?r[t]=n[t]:delete r[t]);return r}function LJ(e,t){return JSON.stringify(e)===JSON.stringify(t)}function RJ(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function oZe(e){let t;return{getItem:n=>{let r=e.storage.getItem(n);return t===void 0&&(t=r),r},setItem:(n,r)=>{let i=e.storage.getItem(n),a=eZe({previousLocal:t??null,currentStored:i,nextLocal:r,version:e.version,...e.canMigrate===void 0?{}:{canMigrate:e.canMigrate}});(a!==i||i===r)&&(e.storage.setItem(n,a),t=r)},removeItem:n=>{e.storage.removeItem(n),t=null}}}function zJ(e){let t=e.auth.status!==`unauthenticated`||e.auth.provenance?.credentialScope===`proxied`;return e.enabled&&e.installed&&e.status===`ready`&&t&&e.models.length>0}var BJ={providers:{codex:!0,claude:!1,cmmd:!0},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function VJ(e){if(e==null)return BJ;let t=e.providers,n=e.allowedWallets;return{providers:{...BJ.providers,...t},allowedWallets:Array.isArray(n)&&n.length>0?n:BJ.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:BJ.updatedAt}}function sZe(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var cZe=[`codex`,`claudeAgent`,`cmmd`];function lZe(e,t){if(t==null)return null;let n=t.providers;if(typeof n!=`object`||!n)return null;let r=n[e];return typeof r==`boolean`?r:null}function HJ(e,t){let n=sZe(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=lZe(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:VJ(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function UJ(e,t){return HJ(e,t).offered}function uZe(e,t){return WJ(e,t).offered}function WJ(e,t){return t===null?{offered:!0}:HJ(e,t)}function GJ(e,t){return VJ(t).allowedWallets.includes(e)}function KJ(e){return GJ(`personal`,e)}function dZe(e){return e===`claudeAgent`||e===`codex`}function fZe(e,t){return e!==`claudeAgent`||KJ(t)||UJ(`claudeAgent`,t)}function pZe(e){return e.isDebugDisclosureEnabled||dZe(e.provider)&&KJ(e.policy)?!1:!UJ(e.provider===`apex`?`apex`:e.provider,e.policy)}function mZe(e){if(!YJ(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(hZe)}}function hZe(e){return YJ(e)?_Ze(e.provider)&&qJ(e.providerAccountId)&&gZe(e)&&JJ(e.accountEmail)&&JJ(e.accountDisplayName)&&JJ(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function gZe(e){return(e.credentialTarget===`primary`||e.credentialTarget===`linked`)&&Array.isArray(e.legacyProviderAccountIds)&&e.legacyProviderAccountIds.every(qJ)}function _Ze(e){return e===`codex`||e===`claudeAgent`}function qJ(e){return typeof e==`string`&&e.trim().length>0}function JJ(e){return typeof e==`string`||e===null}function YJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vZe(e){let t=Dl(e);return t.legacyRuntimeId===null?t.shape===`durable-environment`&&typeof e==`string`?e:null:t.legacyRuntimeId}var XJ=class extends Error{constructor(e){super(e===`auth`?`Your CMMD session expired. Sign in again to verify Claude runtime readiness.`:`CMMD denied access to verify Claude runtime readiness. Check your organization permissions.`),this.name=`ForgeProviderAccessAuthorityError`}};async function yZe(e){if(!e.enabled||e.readinessTargetId===null)return null;try{return SZe(await e.load(e.readinessTargetId),e.readinessTargetId)}catch(e){if(e instanceof gr&&(e.kind===`auth`||e.kind===`permission`))throw new XJ(e.kind);return null}}var bZe=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),xZe=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`];function SZe(e,t){if(!ZJ(e)||!OZe(e)||!CZe(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function CZe(e,t){if(e.deliveryReceipt===null)return e.nativeExecutable!==!0;if(!ZJ(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=ZJ(n.identity)?n.identity:null;return r!==null&&wZe(n,t)&&DZe(r,e.generationId)}function wZe(e,t){return TZe(e,t)&&EZe(e)}function TZe(e,t){return typeof e.receiptId==`string`&&e.receiptId.trim().length>0&&e.runtimeId===t&&typeof e.machineId==`string`&&e.machineId.trim().length>0&&typeof e.credentialEpoch==`number`&&Number.isSafeInteger(e.credentialEpoch)&&e.credentialEpoch>=0}function EZe(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function DZe(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function OZe(e){return typeof e.connected==`boolean`&&bZe.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&xZe.every(t=>kZe(e[t]))}function kZe(e){return e===null||typeof e==`string`}function ZJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var QJ={credential_expired_refreshing:`CREDENTIAL_EXPIRED_REFRESHING`,credential_reconnect_required:`CREDENTIAL_RECONNECT_REQUIRED`,credential_not_connected:`CREDENTIAL_RECONNECT_REQUIRED`,credential_generation_not_applied:`CREDENTIAL_GENERATION_NOT_APPLIED`,runtime_unavailable:`RUNTIME_UNAVAILABLE`};function AZe(e){return typeof e!=`string`||!Object.hasOwn(QJ,e)?null:QJ[e]??null}var jZe=new Set([`pending`,`claimed`,`activating`]),MZe=2e3;function $J(e){return{readinessTargetId:e,dataUpdatedAt:0,consecutiveUnavailableResponses:0,consecutiveFailedResponses:0}}function NZe(e){let t=e.current.readinessTargetId===e.readinessTargetId?e.current:$J(e.readinessTargetId);return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{readinessTargetId:e.readinessTargetId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0,consecutiveFailedResponses:e.deliveryStatus===`failed`?t.consecutiveFailedResponses+1:0}}function PZe(e,t){if(!e.claudeOffered||!e.claudeConnected)return!1;let n=AZe(e.reason);return n===`CREDENTIAL_EXPIRED_REFRESHING`?!0:e.deliveryStatus===`failed`?n!==`CREDENTIAL_RECONNECT_REQUIRED`&&t.consecutiveFailedResponses<16:e.deliveryStatus===null?t.consecutiveUnavailableResponses>0&&t.consecutiveUnavailableResponses<3:jZe.has(e.deliveryStatus)}function eY(e){return e.credentialMode===`runtime`?e.provider&&zJ(e.provider)?{eligible:!0}:{eligible:!1,reason:`runtime-unavailable`}:e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`?{eligible:!1,reason:`access-error`}:FZe({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function FZe(e){return!e.provider||!zJ(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:UJ(e.providerKind,e.policy)?nY({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function tY(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:UJ(e.providerKind,e.access.policy)?nY({providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness,stage:`provisioning`}):{eligible:!1,reason:`not-offered`}}function nY(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:IZe({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:GJ(`workspace`,e.policy),stage:e.stage})}function IZe(e){return LZe(e.workspaceWalletAllowed)?{eligible:!0}:RZe(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:zZe(e.providerKind,e.personalConnections)?HZe(e)?{eligible:!1,reason:`environment-not-running`}:BZe(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function LZe(e){return e&&!1}function RZe(e,t){return e===`codex`&&t?.codex===!0}function zZe(e,t){return t?.[e]===!0}function BZe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||UZe(e.claudeRuntimeReadiness)}var VZe=`runtime_unavailable`;function HZe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`?!1:e.claudeRuntimeReadiness?.reason===VZe}function UZe(e){if(!WZe(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function WZe(e){return e?.connected===!0&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function GZe(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=GJ(`workspace`,e.policy);return t.cmmd?!0:GJ(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var KZe={providers:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},rY=[`cmmd`,`forge-provider-access`],qZe=MZe;function JZe(e,t){return!(t instanceof XJ)&&e<3}function YZe(e,t=null){return[...rY,e,t]}async function XZe(e){e.queryClient.setQueriesData({queryKey:rY},t=>ZZe(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:rY,refetchType:`all`})}function ZZe(e,t,n){return e?.status!==`ready`||e.personalConnections===null?e:{...e,personalConnections:{...e.personalConnections,[t]:n},...t===`codex`?{personalReconnectRequired:{codex:!1}}:{},...t===`claudeAgent`?{claudeRuntimeReadiness:null}:{}}}async function iY(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=qG(),r=rQe(await n.getOrgProviderPolicy());GJ(`workspace`,r);let[i,a,o,s]=await Promise.all([eQe(()=>n.getProviderAccounts()),aY({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),aY({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),yZe({enabled:r.providers.claude,readinessTargetId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=QZe(c),u=l.codex||a.connected,d=l.claudeAgent||o.connected,f=c.some(e=>e.provider===`codex`&&e.needsReconnect)||a.reconnectRequired;return{status:`ready`,policy:r,personalConnections:{codex:u,claudeAgent:d},providerAccounts:c,...f?{personalReconnectRequired:{codex:!0}}:{},claudeRuntimeReadiness:s}}function QZe(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function $Ze(e,t){if(e.status!==`ready`)return;let n=e.providerAccounts??[];return(n.find(e=>e.provider===t&&e.isDefault&&!e.needsReconnect)??n.find(e=>e.provider===t&&!e.needsReconnect))?.providerAccountId}async function eQe(e){try{return mZe(await e())}catch{return{accounts:[]}}}async function aY(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return oQe(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function tQe(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,reason:e?.claudeRuntimeReadiness?.reason??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function nQe(e){let t=(0,cl.c)(21),n;t[0]!==e.environmentId||t[1]!==e.runtimeId?(n=e.environmentId==null?e.runtimeId??null:vZe(e.environmentId),t[0]=e.environmentId,t[1]=e.runtimeId,t[2]=n):n=t[2];let r=n,i;t[3]===r?i=t[4]:(i=$J(r),t[3]=r,t[4]=i);let a=(0,F.useRef)(i),o;t[5]!==e.credentialMode||t[6]!==r?(o=YZe(e.credentialMode,r),t[5]=e.credentialMode,t[6]=r,t[7]=o):o=t[7];let s;t[8]===r?s=t[9]:(s=()=>iY(`cmmd-cloud`,r),t[8]=r,t[9]=s);let c=e.enabled&&e.credentialMode===`cmmd-cloud`,l;t[10]===r?l=t[11]:(l=e=>{if(e.state.error instanceof XJ)return!1;let t=tQe(e.state.data);return a.current=NZe({current:a.current,readinessTargetId:r,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:r!==null&&t.readinessUnavailable,deliveryStatus:t.deliveryStatus}),r!==null&&PZe(t,a.current)?qZe:!1},t[10]=r,t[11]=l);let u;t[12]!==o||t[13]!==s||t[14]!==c||t[15]!==l?(u={queryKey:o,queryFn:s,enabled:c,retry:JZe,staleTime:3e4,refetchInterval:l},t[12]=o,t[13]=s,t[14]=c,t[15]=l,t[16]=u):u=t[16];let d=ji(u);if(!e.enabled){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[17]=e):e=t[17],e}if(e.credentialMode===`runtime`){let e;return t[18]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[18]=e):e=t[18],e}if(d.isPending){let e;return t[19]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[19]=e):e=t[19],e}if(d.isError||!d.data){let e;return t[20]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[20]=e):e=t[20],e}return d.data}function rQe(e){if(!oY(e)||!oY(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,allowedWallets:n,updatedAt:r}=e,i=aQe(n,r);if(!iQe(t)||i===null)throw Error(`CMMD returned an invalid organization provider policy.`);return{providers:{codex:t.codex,claude:t.claude,cmmd:t.cmmd},allowedWallets:[...new Set(i.allowedWallets)],updatedAt:i.updatedAt}}function iQe(e){return typeof e.codex==`boolean`&&typeof e.claude==`boolean`&&typeof e.cmmd==`boolean`}function aQe(e,t){return Array.isArray(e)&&e.length>0&&e.every(sQe)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function oQe(e,t){if(!oY(e)||typeof e.connected!=`boolean`)throw Error(`CMMD returned an invalid ${t} connection state.`);if(!e.connected)return{connected:!1,reconnectRequired:!1};if(t===`codex`){if(typeof e.needsReconnect!=`boolean`)throw Error(`CMMD returned an invalid Codex connection state.`);return{connected:!e.needsReconnect,reconnectRequired:e.needsReconnect}}if(typeof e.generationId!=`string`||e.generationId.trim().length===0)throw Error(`CMMD returned an invalid Claude connection state.`);return{connected:!0,reconnectRequired:!1}}function sQe(e){return e===`personal`||e===`workspace`}function oY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cQe(e){return e.status===`ready`?e.policy:KZe}var sY=[`cursor`,`opencode`,`gemini`],cY={state:`usable`},lY={state:`withheld`,reason:`unbuilt`},uY={state:`withheld`,reason:`not-on-this-environment`};function dY(e){return sY.includes(e)}function fY(e){return e===`gemini`?null:e}function pY(e,t){if(e===void 0)return t?uY:cY;if(e.availability===`unavailable`){let t=e.unavailableReason??`not-on-this-environment`;return e.unavailableDetail===void 0?{state:`withheld`,reason:t}:{state:`withheld`,reason:t,detail:e.unavailableDetail}}return e.availability===`available`||zJ(e)||lQe(e)?cY:uY}function lQe(e){return e.installed&&e.auth.status===`unauthenticated`&&e.auth.provenance?.credentialScope!==`proxied`}function uQe(e,t){let n=tY({providerKind:e,access:t});return n.eligible?null:dQe(n.reason)}function dQe(e){switch(e){case`access-loading`:return{state:`unresolved`,cause:`loading`};case`access-error`:return{state:`unresolved`,cause:`error`};case`not-offered`:return{state:`withheld`,reason:`not-offered`};case`personal-credential-required`:return{state:`withheld`,reason:`not-usable`,detail:`no-connection`};case`personal-credential-reconnect-required`:return{state:`withheld`,reason:`not-usable`,detail:`reconnect-required`};case`native-runtime-not-ready`:return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};case`environment-not-running`:return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};case`runtime-unavailable`:return null}}function fQe(e){if(dY(e.provider))return{pick:lY,run:lY};let t=fY(e.provider);return t===null?{pick:lY,run:lY}:mY({...e,providerKind:t})}function mY(e){return{pick:gY(e,`pick`),run:gY(e,`run`)}}function pQe(e){return gY(e,`pick`)}function hY(e){return e.providers.filter(t=>gY({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0},`run`).state===`usable`)}function gY(e,t){let{providerKind:n}=e;if(e.snapshot?.unavailableReason===`unbuilt`)return lY;if(e.credentialMode===`runtime`)return _Y({...e,providerKind:n},t);if(e.access.status!==`ready`)return{state:`unresolved`,cause:e.access.status};if(!WJ(n,e.access.policy).offered)return{state:`withheld`,reason:`not-offered`};let r=uQe(n,e.access);return r===null?_Y({...e,providerKind:n},t):r}function _Y(e,t){let n=eY({provider:e.snapshot,providerKind:e.providerKind,access:e.access,credentialMode:e.credentialMode});return!n.eligible&&n.reason===`environment-not-running`?{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`}:!n.eligible&&n.reason===`native-runtime-not-ready`?{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`}:!n.eligible&&n.reason===`runtime-unavailable`&&t===`run`?uY:pY(e.snapshot,e.hasLiveInventory)}var mQe={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},vY=[`codex`,`claudeAgent`,`apex`];function yY(e){for(let t of vY){let n=e.find(e=>e.provider===t);if(n&&xY(n))return t}return e.find(xY)?.provider??null}function bY(e,t){return e.find(e=>e.provider===t)?.models??[]}function xY(e){return zJ(e)}function SY(e,t){let n=t??yY(e)??`codex`,r=e.find(e=>e.provider===n);if(r&&xY(r)||n===`codex`)return n;for(let t of vY){let n=e.find(e=>e.provider===t);if(n&&xY(n))return t}return`codex`}function CY(e){return e.providers.filter(t=>pQe({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0}).state===`usable`)}function wY(e,t,n,r){let i=CY({providers:e,access:n,credentialMode:r});return t&&i.some(e=>e.provider===t)?t:yY(i)}function hQe(e,t,n,r){return t==null?wY(e,null,n,r):hY({providers:e,access:n,credentialMode:r}).some(e=>e.provider===t)?t:null}function TY(e,t,n){let r=aq(t,n);return e.find(e=>e.slug===r)?.capabilities??mQe}function EY(e,t,n){let r=bY(e,t).filter(e=>!e.isLegacy);return r.find(e=>e.slug===n)?.slug??r.find(e=>e.isDefault)?.slug??r.find(e=>e.slug===On[t])?.slug??r.find(e=>!e.isCustom)?.slug??r[0]?.slug??On[t]}function DY(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=TY(r,n,t),s=a?.[t],c=tq(o,s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null)??null,l=t===`codex`?uYe(o,s):dYe(o,s),u=o.promptInjectedEffortLevels.length>0&&iq(i);return{provider:t,promptEffort:c,modelOptionsForDispatch:l,...u?{composerFrameClassName:`ultrathink-frame`}:{},...u?{composerSurfaceClassName:`shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]`}:{},...u?{modelPickerIconClassName:`ultrathink-chroma`}:{}}}function OY(e,t,n,r){return bY(t,n).map(({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i})=>({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i}))}function kY(e,t,n,r,i){let a=oq(e,r,OY(t,n,e,r));if(a&&!sq(a,e))return a;let o=AY(n,e,i),s=oq(o,r,OY(t,n,o,r))??EY(n,o);return e&&sq(s,e)?EY(n,e):s}function AY(e,t,n){return!t||!UJ(t,n)?SY(e,`codex`):SY(e,t)}function gQe(e,t,n,r){return{codex:OY(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:OY(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:OY(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:OY(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:OY(e,t,`apex`,n===`apex`?r:void 0),cursor:OY(e,t,`cursor`,n===`cursor`?r:void 0),opencode:OY(e,t,`opencode`,n===`opencode`?r:void 0)}}function _Qe(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:one.codex},i=AY(t,r.provider,n),a=kY(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=DY({provider:i,model:a,models:bY(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function jY(e){return e?.options?{[e.provider]:e.options}:null}function vQe(e){if(!e)return null;let t={};for(let[n,r]of Object.entries(e))r?.options&&(t[n]=r.options);return Object.keys(t).length>0?t:null}function yQe(e){if(e.activeSelection&&`providerAccountId`in e.activeSelection)return e.activeSelection.providerAccountId;for(let t of e.candidates)if(t?.provider===e.selectedProvider&&`providerAccountId`in t)return t.providerAccountId}function bQe(e){let t=t=>t!==void 0&&sq(t,e.selectedProvider)?void 0:t,n=t(e.threadModelSelection?.provider===e.selectedProvider?e.threadModelSelection.model:void 0),r=t(e.projectModelSelection?.provider===e.selectedProvider?e.projectModelSelection.model:void 0),i=aq(n??r,e.selectedProvider)??EY(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=yQe({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?kY(e.selectedProvider,e.settings,e.providers,s):i,l=vQe(e.draft?.modelSelectionByProvider)??jY(e.threadModelSelection)??jY(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var MY=nr({id:j,name:j,mimeType:j,sizeBytes:Ln,dataUrl:j}),NY=nr({id:j,name:j,mimeType:j,sizeBytes:Ln}),PY=nr({id:j,threadId:Vn,createdAt:j,terminalId:j,terminalLabel:j,lineStart:Ln,lineEnd:Ln}),xQe=nr({prompt:j,attachments:Jn(MY),files:cn(Jn(NY)),terminalContexts:Jn(PY),startedAt:j,commandId:cn(sn),messageId:cn(Hn),modelSelection:cn(Qn),runtimeMode:cn(Pn),interactionMode:cn(Gn),executionIntent:cn(nr({runtimeId:j,intentId:cn(j)}))});function FY(e,t){return Array.isArray(e)?e.flatMap(e=>t(e)??[]):[]}function SQe(e){if(!(!e||typeof e.runtimeId!=`string`))return{runtimeId:e.runtimeId,...typeof e.intentId==`string`?{intentId:e.intentId}:{}}}function CQe(e){return{...typeof e.commandId==`string`?{commandId:sn.make(e.commandId)}:{},...typeof e.messageId==`string`?{messageId:Hn.make(e.messageId)}:{}}}function wQe(e,t){let n=t.modelSelection(e.modelSelection);return{...n?{modelSelection:n}:{},...t.runtimeMode(e.runtimeMode)?{runtimeMode:e.runtimeMode}:{},...e.interactionMode==="default"||e.interactionMode===`plan`?{interactionMode:e.interactionMode}:{}}}function TQe(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.prompt!=`string`||typeof n.startedAt!=`string`)return null;let r=SQe(n.executionIntent);return{prompt:n.prompt,attachments:FY(n.attachments,t.attachment),files:FY(n.files,t.file),terminalContexts:FY(n.terminalContexts,t.terminalContext),startedAt:n.startedAt,...CQe(n),...wQe(n,t),...r?{executionIntent:r}:{}}}function EQe(e){return{id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}}function DQe(e){return{prompt:e.prompt,attachments:[...e.attachments],files:[...e.files],terminalContexts:e.terminalContexts.map(EQe),startedAt:e.startedAt,...e.commandId?{commandId:e.commandId}:{},...e.messageId?{messageId:e.messageId}:{},...e.modelSelection?{modelSelection:e.modelSelection}:{},...e.runtimeMode?{runtimeMode:e.runtimeMode}:{},...e.interactionMode?{interactionMode:e.interactionMode}:{},...e.executionIntent?{executionIntent:e.executionIntent}:{}}}function OQe(e){return e?{...e,attachments:[...e.attachments],files:[...e.files??[]],terminalContexts:e.terminalContexts.map(e=>({...e,text:``}))}:null}function kQe(e,t,n,r){let i=e[t];if(i?.stagedSubmission)return null;let a=jQe(i??AQe(),r,n);return a?{previousDraft:i,restoredDraft:a,drafts:{...e,[t]:a}}:null}function AQe(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function IY(e){return`${e.mimeType}\u0000${e.sizeBytes}\u0000${e.name}`}function LY(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function RY(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim(),i=hJ(t.text);if(!n||!r)return null;let a=Math.max(1,Math.floor(t.lineStart));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:a,lineEnd:Math.max(a,Math.floor(t.lineEnd)),text:i}}function zY(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=RY(e,a);if(!t)continue;let o=LY(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function jQe(e,t,n){let r=NQe(e,t);if(!r)return null;let i=MQe(e.files??[],t.files);if(r.images.length+i.length>8)return null;let a=PQe(e,t,n),o=[e.prompt,t.prompt].filter(e=>e.length>0).join(`
1014
+ `);return{...e,prompt:bJ(o,a.contexts.length),images:r.images,files:i,persistedAttachments:r.attachments,terminalContexts:a.contexts,stashTerminalContexts:[...e.stashTerminalContexts??[],...a.restoredSnapshots]}}function MQe(e,t){let n=new Set(e.map(e=>e.id));return[...e,...t.filter(e=>!n.has(e.id))]}function NQe(e,t){let n=new Map(t.attachments.map(e=>[e.id,e])),r=[...e.images],i=e.persistedAttachments.filter(t=>e.images.some(e=>e.id===t.id)),a=new Set(r.map(e=>e.id)),o=new Set(r.map(IY));for(let e of t.images){let t=n.get(e.id);if(!t)return null;let s=IY(e);a.has(e.id)||o.has(s)||(r.push(e),i.push(t),a.add(e.id),o.add(s))}return r.length>8?null:{images:r,attachments:i}}function PQe(e,t,n){let r=[...e.terminalContexts],i=new Set(r.map(e=>e.id)),a=new Set(r.map(LY)),o=[];for(let e of t.terminalContexts){let t=RY(n,e);!t||i.has(t.id)||a.has(LY(t))||(r.push(t),o.push(t),i.add(t.id),a.add(LY(t)))}return{contexts:r,restoredSnapshots:o}}function FQe(e,t){return e.prompt===t.prompt&&JSON.stringify(e.attachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.files??[])===JSON.stringify((t.files??[]).map(({file:e,type:t,...n})=>n))&&JSON.stringify(e.terminalContexts??[])===JSON.stringify(t.terminalContexts.map(({text:e,...t})=>t))&&JSON.stringify(e.stashTerminalContexts??[])===JSON.stringify(t.stashTerminalContexts??[])}function BY(e){typeof URL<`u`&&e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function VY(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isFinite(i)||typeof a!=`string`||t.length===0||a.length===0?null:{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}}function HY(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i}=e;return typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,mimeType:r,sizeBytes:i}}async function IQe(e,t){let n=await Promise.all(e.map(async e=>{let n=await t.read(e);return{...e,type:`file`,file:n}}));return n.length===e.length?n:null}function LQe(e){let t=RQe(e.dataUrl,e.mimeType);return t?new File([t.content],e.name,{type:t.mimeType}):null}function RQe(e,t){let n=e.indexOf(`,`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);if(i.length===0)return null;try{return r.includes(`;base64`)?{content:VQe(i),mimeType:t}:{content:BQe(i),mimeType:zQe(r,t)}}catch{return null}}function zQe(e,t){return!e.startsWith(`data:`)||!e.includes(`;`)?t:e.slice(5,e.indexOf(`;`))||t}function BQe(e){return decodeURIComponent(e)}function VQe(e){let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function UY(e){return e.flatMap(e=>{let t=LQe(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function HQe(e){return{prompt:e.prompt,images:[...e.images],files:[...e.files??[]],persistedAttachments:[...e.persistedAttachments],terminalContexts:[...e.terminalContexts]}}function WY({file:e,previewUrl:t,...n}){return n}function UQe(e,t){return e.prompt===t.prompt&&JSON.stringify(e.images.map(WY))===JSON.stringify(t.images.map(WY))&&JSON.stringify((e.files??[]).map(({file:e,...t})=>t))===JSON.stringify(t.files.map(({file:e,...t})=>t))&&JSON.stringify(e.persistedAttachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.terminalContexts)===JSON.stringify(t.terminalContexts)}function GY(e){let{lastGeneratedPullRequestPrompt:t,...n}=e;return{...n,prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],stashTerminalContexts:[]}}function KY(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===0&&(e.files?.length??0)===0&&e.persistedAttachments.length===0&&e.terminalContexts.length===0&&Object.keys(e.modelSelectionByProvider).length===0&&e.activeProvider===null&&e.runtimeMode===null&&e.interactionMode===null&&e.stagedSubmission==null}function qY(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function JY(e){return Rn.some(t=>t===e)}function WQe(e){return gne.some(t=>t===e)}function YY(e,t,n){let r=e&&typeof e==`object`?e:null,i=r?.codex&&typeof r.codex==`object`?r.codex:null,a=r?.claudeAgent&&typeof r.claudeAgent==`object`?r.claudeAgent:null,o=JY(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&JY(n?.effort)?n.effort:void 0,s=i?.fastMode===!0?!0:i?.fastMode===!1?!1:t===`codex`&&n?.codexFastMode===!0||typeof n?.serviceTier==`string`&&n.serviceTier===`fast`||void 0,c=o!==void 0||s!==void 0?{...o===void 0?{}:{reasoningEffort:o},...s===void 0?{}:{fastMode:s}}:void 0,l=a?.thinking===!0||a?.thinking!==!1&&void 0,u=WQe(a?.effort)?a.effort:void 0,d=a?.fastMode===!0||a?.fastMode!==!1&&void 0,f=typeof a?.contextWindow==`string`&&a.contextWindow.length>0?a.contextWindow:void 0,p=l!==void 0||u!==void 0||d!==void 0||f!==void 0?{...l===void 0?{}:{thinking:l},...u===void 0?{}:{effort:u},...d===void 0?{}:{fastMode:d},...f===void 0?{}:{contextWindow:f}}:void 0;return!c&&!p?null:{...c?{codex:c}:{},...p?{claudeAgent:p}:{}}}function XY(e,t){let n=e&&typeof e==`object`?e:null,r=qY(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=aq(i,r);if(!a)return null;let o=YY(n?.options?{[r]:n.options}:t?.modelOptions,r,r===`codex`?t?.legacyCodex:void 0),s=r===`codex`?o?.codex:o?.claudeAgent,c=n?.providerAccountId,l=typeof c==`string`&&c.trim().length>0?c.trim():void 0;return{provider:r,model:a,...l?{providerAccountId:l}:{},...s?{options:s}:{}}}function ZY(e,t){if(e===null)return null;let n=t?.[e.provider];return{provider:e.provider,model:e.model,...`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...n?{options:n}:{}}}function QY(e,t){return e?.options===void 0?YY(t):GQe(YY(t),e.provider,e.options)}function GQe(e,t,n){let{[t]:r,...i}=e??{},a=YY({[t]:n},t);return YY({...i,...a||{}})}function $Y(e,t){let n={};if(t)for(let r of[`codex`,`claudeAgent`]){let i=t[r];i&&Object.keys(i).length>0&&(n[r]={provider:r,model:e?.provider===r?e.model:On[r],options:i})}return e&&(n[e.provider]=e),n}var eX=`forge:composer-drafts:v1`,tX=5,KQe=Fn([`local`,`worktree`]),nX=zte(Pn),rX=QXe(oZe({storage:typeof localStorage<`u`?localStorage:OJ(),version:tX,canMigrate:XQe}),300);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{rX.flush()});var qQe=nr({prompt:j,lastGeneratedPullRequestPrompt:cn(j),attachments:Jn(MY),files:cn(Jn(NY)),terminalContexts:cn(Jn(PY)),stashTerminalContexts:cn(Jn(nr({...PY.fields,text:j}))),modelSelectionByProvider:cn(In(er,cn(Qn))),activeProvider:cn(Kn(er)),runtimeMode:cn(Pn),interactionMode:cn(Gn),stagedSubmission:cn(xQe)});nr({effort:cn(Fn(Rn)),codexFastMode:cn(Xn),serviceTier:cn(j)}),nr({provider:cn(er),model:cn(j),modelOptions:cn(Kn(bn))}),nr({stickyProvider:cn(er),stickyModel:cn(j),stickyModelOptions:cn(Kn(bn))});var JQe=nr({threadId:Vn,environmentId:j,projectId:tn,logicalProjectKey:cn(j),createdAt:j,runtimeMode:Pn,interactionMode:Gn,branch:Kn(j),worktreePath:Kn(j),envMode:KQe,promotedTo:cn(Kn(nr({environmentId:j,threadId:j}))),anchorKind:cn(Qte),anchorCmmdId:cn(Kn(j)),linkedPullRequest:cn(Kn(rne))}),YQe=nr({draftsByThreadKey:In(j,qQe),draftThreadsByThreadKey:In(j,JQe),logicalProjectDraftThreadKeyByLogicalProjectKey:In(j,j),stickyModelSelectionByProvider:cn(In(er,cn(Qn))),stickyActiveProvider:cn(Kn(er))}),iX=nr({version:Ln,state:YQe}),aX=vn(iX);function XQe(e,t){if(e===null)return!0;try{let n=JSON.parse(e);if(!n||typeof n!=`object`)return!1;let r=n;return r.version===t?(aX(n),!0):typeof r.version==`number`&&Number.isInteger(r.version)&&r.version>=1&&r.version<t&&r.state!==null&&typeof r.state==`object`}catch{return!1}}function ZQe(e){if(e===null)return new Set;try{let t=aX(JSON.parse(e));if(t.version!==tX)return null;let n=new Set;for(let e of Object.values(t.state.draftsByThreadKey)){for(let t of e.files??[])n.add(t.id);for(let t of e.stagedSubmission?.files??[])n.add(t.id)}return n}catch{return null}}function QQe(){rX.flush()}var oX=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),sX=[],$Qe=[],cX=[],lX=[],e$e=[];Object.freeze(sX),Object.freeze(cX),Object.freeze(lX);var uX=Object.freeze({}),t$e=Object.freeze({activeProvider:null,modelSelectionByProvider:uX}),n$e=Object.freeze({prompt:``,images:sX,files:$Qe,nonPersistedImageIds:cX,persistedAttachments:lX,terminalContexts:e$e,modelSelectionByProvider:uX,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function dX(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function fX(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.threadId,i=t.createdAt,a=t.lineStart,o=t.lineEnd;if(typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0||typeof i!=`string`||i.length===0||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`number`||!Number.isFinite(o))return null;let s=typeof t.terminalId==`string`?t.terminalId.trim():``,c=typeof t.terminalLabel==`string`?t.terminalLabel.trim():``;if(s.length===0||c.length===0)return null;let l=Math.max(1,Math.floor(a));return{id:n,threadId:r,createdAt:i,terminalId:s,terminalLabel:c,lineStart:l,lineEnd:Math.max(l,Math.floor(o))}}function r$e(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function pX(e){return Bo(e)}function mX(e){return e.trim()}function hX(e){return typeof e==`string`?e.trim():Vo(e)}function gX(e,t){let n=Wo(e);return n?hX(n):t?.environmentId?hX(Lo(t.environmentId,e)):e}function i$e(e){return Wo(e)}function _X(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?qt.make(e):null}return t}function vX(e,t){let n=_X(e,t);if(!n)return null;if(typeof n!=`string`){let t=hX(n);if(e.draftsByThreadKey[t])return t;for(let[t,r]of Object.entries(e.draftThreadsByThreadKey))if(r.environmentId===n.environmentId&&r.threadId===n.threadId)return t;return t}let r=hX(n);return r.length>0?r:null}function yX(e,t){let n=_X(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??Vn.make(n):n.threadId:null}function bX(e,t){let n=vX(e,t);return n?e.draftsByThreadKey[n]??null:null}function a$e(e,t){return Object.values(e).includes(t)}function xX(e,t){return{draftId:e,...t}}function o$e(e,t,n,r,i){let a=r!==void 0&&(r.environmentId!==e.environmentId||r.projectId!==e.projectId),o=i?.worktreePath===void 0?a?null:r?.worktreePath??null:i.worktreePath??null,s=i?.branch===void 0?a?null:r?.branch??null:i.branch??null,c=i?.anchorKind===void 0?r?.anchorKind:i.anchorKind??void 0;return{threadId:t,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:n,createdAt:i?.createdAt??r?.createdAt??new Date().toISOString(),runtimeMode:i?.runtimeMode??r?.runtimeMode??`full-access`,interactionMode:i?.interactionMode??r?.interactionMode??`default`,branch:s,worktreePath:o,envMode:i?.envMode??(o?`worktree`:a?`local`:r?.envMode??`local`),promotedTo:null,cmmdTaskId:i?.cmmdTaskId===void 0?r?.cmmdTaskId??null:i.cmmdTaskId,anchorCmmdId:i?.anchorCmmdId===void 0?r?.anchorCmmdId??null:i.anchorCmmdId,linkedPullRequest:i?.linkedPullRequest===void 0?r?.linkedPullRequest??null:i.linkedPullRequest,...c===void 0?{}:{anchorKind:c}}}function SX(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function CX(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function s$e(e,t){return!!e&&e.threadId===t.threadId&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.logicalProjectKey===t.logicalProjectKey&&e.createdAt===t.createdAt&&e.runtimeMode===t.runtimeMode&&e.interactionMode===t.interactionMode&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.envMode===t.envMode&&(e.anchorKind??void 0)===(t.anchorKind??void 0)&&(e.anchorCmmdId??null)===(t.anchorCmmdId??null)&&wX(e.linkedPullRequest,t.linkedPullRequest)&&SX(e.promotedTo,t.promotedTo)}function wX(e,t){return(e?.projectId??null)===(t?.projectId??null)&&(e?.projectRepositoryId??null)===(t?.projectRepositoryId??null)&&(e?.provider??null)===(t?.provider??null)&&(e?.host??null)===(t?.host??null)&&(e?.repository??null)===(t?.repository??null)&&(e?.number??null)===(t?.number??null)&&(e?.url??null)===(t?.url??null)}function TX(e,t){let n=Object.fromEntries(Object.entries(e.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(([,e])=>e!==t)),{[t]:r,...i}=e.draftThreadsByThreadKey,{[t]:a,...o}=e.draftsByThreadKey;return{draftsByThreadKey:o,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n}}function EX(e,t){let n={},r=new Map;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(typeof n!=`string`||n.length===0)continue;let t=Uo(e);if(!t)continue;let i=Wo(n);if(i){r.set(i.threadId,i.environmentId);continue}r.set(n,t.environmentId)}if(e&&typeof e==`object`)for(let[t,i]of Object.entries(e)){if(typeof t!=`string`||t.length===0||!i||typeof i!=`object`)continue;let e=i,a=Wo(t),o=gX(t),s=a?.threadId??(typeof e.threadId==`string`&&e.threadId.length>0?e.threadId:t),c=a?.environmentId??(typeof e.environmentId==`string`&&e.environmentId.length>0?e.environmentId:r.get(t)),l=e.projectId,u=e.createdAt,d=e.branch,f=e.worktreePath,p=typeof f==`string`?f:null,m=e.promotedTo,h=m&&typeof m==`object`?m:null,g=h&&typeof h.environmentId==`string`&&h.environmentId.length>0&&typeof h.threadId==`string`&&h.threadId.length>0?Lo(h.environmentId,h.threadId):null;if(typeof l!=`string`||l.length===0||c===void 0)continue;let _=c;n[o]={threadId:s,environmentId:_,projectId:l,logicalProjectKey:typeof e.logicalProjectKey==`string`&&e.logicalProjectKey.length>0?e.logicalProjectKey:a?pX(Io(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:nX(e.runtimeMode)?e.runtimeMode:fJ,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:pJ,branch:typeof d==`string`?d:null,worktreePath:p,envMode:r$e(e.envMode,p),promotedTo:g}}let i={};if(t&&typeof t==`object`)for(let[e,a]of Object.entries(t)){if(typeof a!=`string`||a.length===0)continue;let t=Uo(e),o=Wo(a),s=gX(a);if(i[e]=s,o&&r.set(o.threadId,o.environmentId),!t){let t=n[s];t&&!t.logicalProjectKey&&(n[s]={...t,logicalProjectKey:e});continue}n[s]?(n[s]?.projectId!==t.projectId||n[s]?.environmentId!==t.environmentId)&&(n[s]={...n[s],threadId:n[s].threadId,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e}):n[s]={threadId:o?.threadId??s,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e,createdAt:new Date().toISOString(),runtimeMode:fJ,interactionMode:pJ,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function DX(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=i$e(e);t&&n.set(t.threadId,r.environmentId)}let r={};for(let[i,a]of Object.entries(e)){if(typeof i!=`string`||i.length===0||!a||typeof a!=`object`)continue;let e=a,o=typeof e.prompt==`string`?e.prompt:``,s=typeof e.lastGeneratedPullRequestPrompt==`string`?e.lastGeneratedPullRequestPrompt:void 0,c=Array.isArray(e.attachments)?e.attachments.flatMap(e=>{let t=VY(e);return t?[t]:[]}):[],l=Array.isArray(e.files)?e.files.flatMap(e=>{let t=HY(e);return t?[t]:[]}):[],u=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=fX(e);return t?[t]:[]}):[],d=Array.isArray(e.stashTerminalContexts)?e.stashTerminalContexts.flatMap(e=>{let t=fX(e),n=typeof e.text==`string`?e.text:``;return t&&n.length>0?[{...t,text:n}]:[]}):[],f=nX(e.runtimeMode)?e.runtimeMode:null,p=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,m=TQe(e.stagedSubmission,{attachment:VY,file:HY,terminalContext:fX,modelSelection:e=>XY(e)??null,runtimeMode:nX}),h=bJ(o,u.length),g=a,_={},v=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)_=e.modelSelectionByProvider,v=qY(e.activeProvider);else{let e=YY(g.modelOptions,void 0,g)??null,t=XY(g.modelSelection,{provider:g.provider,model:g.model,modelOptions:e??g.modelOptions,legacyCodex:g}),n=QY(t,e),r=ZY(t,n);_=$Y(r,n),v=r?.provider??null}let y=Object.keys(_).length>0||v!==null;if(o.length===0&&c.length===0&&l.length===0&&u.length===0&&d.length===0&&!y&&!f&&!p&&!m)continue;let b=Wo(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?gX(i,{environmentId:e}):i})():i:gX(i);r[b]={prompt:h,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{files:l}:{},...u.length>0?{terminalContexts:u}:{},...d.length>0?{stashTerminalContexts:d}:{},...y?{modelSelectionByProvider:_,activeProvider:v}:{},...f?{runtimeMode:f}:{},...p?{interactionMode:p}:{},...m?{stagedSubmission:m}:{}}}return r}function c$e(e){if(!e||typeof e!=`object`)return oX;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=YY(t.stickyModelOptions)??{},o=XY(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=QY(o,a),c=$Y(ZY(o,s),s),l=qY(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=EX(r,i);return{draftsByThreadKey:DX(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function l$e(e){let t={};for(let[n,r]of Object.entries(e.draftsByThreadKey)){if(typeof n!=`string`||n.length===0)continue;let e=Object.keys(r.modelSelectionByProvider).length>0||r.activeProvider!==null;r.prompt.length===0&&r.lastGeneratedPullRequestPrompt===void 0&&r.persistedAttachments.length===0&&(r.files?.length??0)===0&&r.terminalContexts.length===0&&!e&&r.runtimeMode===null&&r.interactionMode===null&&r.stagedSubmission==null||(t[n]={prompt:r.prompt,...r.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:r.lastGeneratedPullRequestPrompt},attachments:r.persistedAttachments,...(r.files?.length??0)>0?{files:r.files.map(({file:e,type:t,...n})=>n)}:{},...r.terminalContexts.length>0?{terminalContexts:r.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}))}:{},...r.stashTerminalContexts&&r.stashTerminalContexts.length>0?{stashTerminalContexts:r.stashTerminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd,text:e.text}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:DQe(r.stagedSubmission)}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function u$e(e){if(!e||typeof e!=`object`)return oX;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=EX(t.draftThreadsByThreadKey??t.draftThreadsByThreadId,t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId),i={},a=null;if(t.stickyModelSelectionByProvider&&typeof t.stickyModelSelectionByProvider==`object`)i=t.stickyModelSelectionByProvider,a=qY(t.stickyActiveProvider);else{let e=YY(t.stickyModelOptions)??{},n=XY(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=QY(n,e);i=$Y(ZY(n,r),r),a=qY(t.stickyProvider)}return{draftsByThreadKey:DX(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function d$e(e){if(e.length===0)return[];try{let t=yl(eX,iX);return!t||t.version!==tX?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function f$e(e){if(e.length===0)return null;try{let t=rX.getItem(eX);if(typeof t!=`string`)return null;let n=aX(JSON.parse(t));return!n||n.version!==tX?null:n.state.draftsByThreadKey[e]??null}catch{return null}}function p$e(e,t,n){let r=new Set;try{rX.flush(),r=new Set(d$e(e))}catch{r=new Set}n(n=>{let i=n.draftsByThreadKey[e];if(!i)return n;let a=new Set(i.images.map(e=>e.id)),o=t.filter(e=>a.has(e.id)&&r.has(e.id)),s=i.images.map(e=>e.id).filter(e=>!r.has(e)),c={...i,persistedAttachments:o,nonPersistedImageIds:s},l={...n.draftsByThreadKey};return KY(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function m$e(e,t){return e.length>0?e:t?.prompt??``}function OX(e,t){return e?.length?e:t??[]}function h$e(e){let t=e.stagedSubmission;return{prompt:m$e(e.prompt,t),attachments:OX(e.attachments,t?.attachments),files:OX(e.files,t?.files),terminalContexts:OX(e.terminalContexts,t?.terminalContexts)}}function g$e(e){let t=e.modelSelectionByProvider??{},n=qY(e.activeProvider)??null,r=h$e(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:UY(r.attachments),files:r.files.map(e=>({...e,type:`file`,file:null})),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],terminalContexts:r.terminalContexts.map(t=>{let n=e.stashTerminalContexts?.find(e=>e.id===t.id);return Object.assign({},t,{text:n?.text??``})}),...e.stashTerminalContexts&&e.stashTerminalContexts.length>0?{stashTerminalContexts:e.stashTerminalContexts.map(e=>({...e}))}:{},modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:OQe(e.stagedSubmission)}}function _$e(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??pX(Io(e.environmentId,e.projectId)),createdAt:e.createdAt,runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,branch:e.branch,worktreePath:e.worktreePath,envMode:e.envMode,promotedTo:e.promotedTo?Lo(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var kX=Xt()(CJ((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>bX(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=mX(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||CX(i)?null:xX(qt.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!CX(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return xX(qt.make(n),r);return null},getDraftSession:e=>t().draftThreadsByThreadKey[e]??null,getDraftSessionByRef:e=>{for(let n of Object.values(t().draftThreadsByThreadKey))if(n.environmentId===e.environmentId&&n.threadId===e.threadId)return n;return null},getDraftThread:e=>typeof e==`string`?t().getDraftSession(qt.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Vo(Lo(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=mX(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=o$e(t,i?.threadId??n?.threadId??Vn.make(r),a,n,i);if(o===r&&s$e(n,s))return e;let c={...e.logicalProjectDraftThreadKeyByLogicalProjectKey,[a]:r},l={...e.draftThreadsByThreadKey,[r]:s},u=e.draftsByThreadKey,d=o===void 0?void 0:l[o];return o&&o!==r&&!a$e(c,o)&&!CX(d)&&(delete l[o],e.draftsByThreadKey[o]!==void 0&&(u={...e.draftsByThreadKey},delete u[o])),{draftsByThreadKey:u,draftThreadsByThreadKey:l,logicalProjectDraftThreadKeyByLogicalProjectKey:c}})},setProjectDraftThreadId:(e,n,r)=>{t().setLogicalProjectDraftThreadId(pX(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r.projectRef??{environmentId:t.environmentId,projectId:t.projectId};if(n.projectId.length===0||n.environmentId.length===0)return e;let a=n.environmentId!==t.environmentId||n.projectId!==t.projectId,o=r.worktreePath===void 0?a?null:t.worktreePath:r.worktreePath??null,s=r.branch===void 0?a?null:t.branch:r.branch??null,c=r.anchorKind===void 0?t.anchorKind:r.anchorKind??void 0,l={threadId:t.threadId,environmentId:n.environmentId,projectId:n.projectId,logicalProjectKey:t.logicalProjectKey,createdAt:r.createdAt===void 0?t.createdAt:r.createdAt||t.createdAt,runtimeMode:r.runtimeMode??t.runtimeMode,interactionMode:r.interactionMode??t.interactionMode,branch:s,worktreePath:o,envMode:r.envMode??(o?`worktree`:a?`local`:t.envMode??`local`),promotedTo:t.promotedTo??null,cmmdTaskId:r.cmmdTaskId===void 0?t.cmmdTaskId??null:r.cmmdTaskId,anchorCmmdId:r.anchorCmmdId===void 0?t.anchorCmmdId??null:r.anchorCmmdId,linkedPullRequest:r.linkedPullRequest===void 0?t.linkedPullRequest??null:r.linkedPullRequest,...c===void 0?{}:{anchorKind:c}};return l.environmentId===t.environmentId&&l.projectId===t.projectId&&l.logicalProjectKey===t.logicalProjectKey&&l.createdAt===t.createdAt&&l.runtimeMode===t.runtimeMode&&l.interactionMode===t.interactionMode&&l.branch===t.branch&&l.worktreePath===t.worktreePath&&l.envMode===t.envMode&&(l.anchorKind??void 0)===(t.anchorKind??void 0)&&(l.anchorCmmdId??null)===(t.anchorCmmdId??null)&&wX(l.linkedPullRequest,t.linkedPullRequest)&&SX(l.promotedTo,t.promotedTo)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:l}}})},clearProjectDraftThreadId:e=>{n(t=>{let n=Object.entries(t.draftThreadsByThreadKey).find(([,t])=>t.projectId===e.projectId&&t.environmentId===e.environmentId);return n?TX(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=vX(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:TX(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=vX(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??Lo(t.environmentId,t.threadId);return SX(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!CX(t))return e;let n=hX(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return TX(a?{...e,draftsByThreadKey:{...e.draftsByThreadKey,[n]:i?{...i,modelSelectionByProvider:{...i.modelSelectionByProvider,...a.modelSelectionByProvider},activeProvider:a.activeProvider,runtimeMode:a.runtimeMode,interactionMode:a.interactionMode}:a}}:e,r)})},clearDraftThread:e=>{let r=vX(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)BY(e.previewUrl);n(e=>{let t=e.draftThreadsByThreadKey[r]!==void 0,n=Object.values(e.logicalProjectDraftThreadKeyByLogicalProjectKey).includes(r),i=e.draftsByThreadKey[r]!==void 0;return!t&&!n&&!i?e:TX(e,r)})},setStickyModelSelection:e=>{let t=XY(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return Qe(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.stickyModelSelectionByProvider,n=e.stickyActiveProvider;if(Object.keys(t).length===0&&n===null)return e;let i=e.draftsByThreadKey[r]??dX(),a={...i.modelSelectionByProvider};for(let[e,n]of Object.entries(t))if(n){let t=a[e];a[e]={...n,model:t?.model??n.model}}if(Qe(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return KY(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return KY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return KY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r,i,a,o,s,c)=>{let l=vX(t(),e)??``;l.length!==0&&(n(e=>{let t=e.draftsByThreadKey[l];if(!t)return e;let n={prompt:t.prompt,attachments:[...c??t.persistedAttachments],files:(t.files??[]).map(({file:e,type:t,...n})=>n),terminalContexts:[...t.terminalContexts],startedAt:r,commandId:i,messageId:a,...o?{executionIntent:o}:{},...s},u={...e.draftsByThreadKey};return u[l]={...t,stagedSubmission:n},{draftsByThreadKey:u}}),rX.flush())},setStagedComposerExecutionIntent:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&(n(e=>{let t=e.draftsByThreadKey[i];return t?.stagedSubmission?{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,stagedSubmission:{...t.stagedSubmission,executionIntent:r}}}}:e}),rX.flush())},clearStagedComposerSubmission:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t?.stagedSubmission)return e;let n={...t,stagedSubmission:null},i={...e.draftsByThreadKey};return KY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r,i)=>{let a=vX(t(),e),o=yX(t(),e);if(!a||!o)return;let s=zY(o,r);n(e=>{let t=e.draftsByThreadKey[a]??dX(),n={...t,prompt:bJ(t.prompt,s.length),terminalContexts:s,...i?.preserveTextForReload?{stashTerminalContexts:s}:{stashTerminalContexts:[]}},r={...e.draftsByThreadKey};return KY(n)?delete r[a]:r[a]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return;let a=XY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??dX(),r={...n.modelSelectionByProvider};if(a){let e=r[a.provider];a.options===void 0?r[a.provider]={provider:a.provider,model:a.model,...`providerAccountId`in a&&a.providerAccountId?{providerAccountId:a.providerAccountId}:e&&`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...e?.options?{options:e.options}:{}}:r[a.provider]=a}let o=a?.provider??n.activeProvider;if(Qe(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return KY(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return;let a=YY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??dX(),r={...n.modelSelectionByProvider};for(let e of[`codex`,`claudeAgent`]){if(!a||!(e in a))continue;let t=a[e],n=r[e];if(t)r[e]={provider:e,model:n?.model??On[e],...n&&`providerAccountId`in n&&n.providerAccountId?{providerAccountId:n.providerAccountId}:{},options:t};else if(n?.options){let{options:t,...i}=n;r[e]=i}}if(Qe(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return KY(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=vX(t(),e)??``;if(o.length===0)return;let s=qY(r);if(s===null)return;let c=YY({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??dX(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??On[s],...r&&`providerAccountId`in r&&r.providerAccountId?{providerAccountId:r.providerAccountId}:{},options:c};else if(r?.options){let{options:e,...t}=r;n[s]=t}let i=e.stickyModelSelectionByProvider,l=e.stickyActiveProvider;if(a?.persistSticky===!0){i={...e.stickyModelSelectionByProvider};let n=i[s]??t.modelSelectionByProvider[s]??{provider:s,model:On[s]};if(c)i[s]={...n,provider:s,options:c};else if(n.options){let{options:e,...t}=n;i[s]=t}l=t.activeProvider??s}if(Qe(t.modelSelectionByProvider,n)&&Qe(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return KY(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return;let a=nX(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??dX();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return KY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return;let a=r===`plan`||r==="default"?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??dX();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return KY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=vX(t(),e),i=yX(t(),e);!r||!i||t().addImages(typeof e==`string`?qt.make(r):e,[n])},addImages:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX(),n=new Set(t.images.map(e=>e.id)),a=new Set(t.images.map(e=>IY(e))),o=new Set(t.images.map(e=>e.previewUrl)),s=[];for(let e of r){let t=IY(e);if(n.has(e.id)||a.has(t)){o.has(e.previewUrl)||BY(e.previewUrl);continue}s.push(e),n.add(e.id),a.add(t),o.add(e.previewUrl)}return s.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,images:[...t.images,...s]}}}})},addFiles:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX(),n=new Set((t.files??[]).map(e=>e.id)),a=Math.max(0,8-t.images.length-(t.files?.length??0)),o=r.filter(e=>!n.has(e.id)).slice(0,a);return o.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...t.files??[],...o]}}}})},setFiles:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??dX();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...r]}}}})},removeImage:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return;let a=t().draftsByThreadKey[i];if(!a)return;let o=a.images.find(e=>e.id===r);o&&BY(o.previewUrl),n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,images:t.images.filter(e=>e.id!==r),nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>e!==r),persistedAttachments:t.persistedAttachments.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return KY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=vX(t(),e),s=yX(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??dX(),n=RY(s,i);if(!n)return e;let l=LY(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>LY(e)===l))return e;c=!0;let u=Math.max(0,Math.min(t.terminalContexts.length,a)),d={...t,prompt:r,terminalContexts:[...t.terminalContexts.slice(0,u),n,...t.terminalContexts.slice(u)]};return{draftsByThreadKey:{...e.draftsByThreadKey,[o]:d}}}),c},addTerminalContext:(e,n)=>{let r=vX(t(),e),i=yX(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?qt.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=vX(t(),e),a=yX(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??dX(),n=zY(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:bJ(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=vX(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,terminalContexts:t.terminalContexts.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return KY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t||t.terminalContexts.length===0)return e;let n={...t,terminalContexts:[]},i={...e.draftsByThreadKey};return KY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n={...t,persistedAttachments:[],nonPersistedImageIds:[]},i={...e.draftsByThreadKey};return KY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=vX(t(),e);if(!i)return;let a=new Set(r.map(e=>e.id));n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,persistedAttachments:r,nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>!a.has(e))},o={...e.draftsByThreadKey};return KY(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{p$e(i,r,n)})},moveComposerDraft:(e,r)=>{let i=bXe(t().draftsByThreadKey,e,r);return i!==null&&(n({draftsByThreadKey:i}),rX.flush(),!0)},clearComposerContent:e=>{let r=vX(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n=GY(t),i={...e.draftsByThreadKey};return KY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearComposerContentIfUnchanged:(e,r)=>{let i=vX(t(),e)??``;if(i.length===0)return!1;let a=!1;return n(e=>{let t=e.draftsByThreadKey[i];if(!t||!UQe(t,r))return e;let n=GY(t),o={...e.draftsByThreadKey};return KY(n)?delete o[i]:o[i]=n,a=!0,{draftsByThreadKey:o}}),a},restoreComposerStash:(e,r)=>{let i=vX(t(),e)??``,a=yX(t(),e);if(i.length===0||!a)return!1;let o,s;if(n(e=>{let t=kQe(e.draftsByThreadKey,i,a,r);return t?(o=t.previousDraft,s=t.restoredDraft,{draftsByThreadKey:t.drafts}):e}),!s)return!1;let c=!1;try{rX.flush();let e=f$e(i),n=t().draftsByThreadKey[i];e!==null&&n===s&&FQe(e,n)&&(c=!0)}catch{}if(c&&(r.onPersisted?.()??!0))return!0;n(e=>{if(e.draftsByThreadKey[i]!==s)return e;let t={...e.draftsByThreadKey};return o?t[i]=o:delete t[i],{draftsByThreadKey:t}});try{rX.flush()}catch{}return!1}}},{name:eX,version:tX,storage:xJ(()=>rX),migrate:c$e,partialize:l$e,merge:(e,t)=>{let n=u$e(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,g$e(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,_$e(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function v$e(e){let t=(0,cl.c)(2),n;return t[0]===e?n=t[1]:(n=t=>bX(t,e)??n$e,t[0]=e,t[1]=n),kX(n)}function y$e(e){let t=(0,cl.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=bX(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:t$e},t[0]=e,t[1]=n),kX(DJ(n))}function AX(e){let t=kX.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(qt.make(n),e)}function b$e(e){for(let t of e)AX(t)}function x$e(e){let t=kX.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(qt.make(n))}function S$e(e){let t=new Set,n=new Map(e.snapshotThreads.map(e=>[e.key,e]));for(let n of e.snapshotThreads)n.deletedAt===null&&n.archivedAt===null&&t.add(n.key);for(let r of e.draftThreadKeys){let e=n.get(r);e&&(e.deletedAt!==null||e.archivedAt!==null)||t.add(r)}return t}function C$e(e){let t=new Map,n=!1;for(let r of e)switch(r.type){case`thread.turn-diff-completed`:case`thread.reverted`:n=!0;break;case`thread.created`:t.set(r.payload.threadId,{clearPromotedDraft:!0,clearDeletedThread:!1,removeTerminalState:!1});break;case`thread.deleted`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!0,removeTerminalState:!0});break;case`thread.archived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!0});break;case`thread.unarchived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!1})}let r=[],i=[],a=[];for(let[e,n]of t)n.clearPromotedDraft&&r.push(e),n.clearDeletedThread&&i.push(e),n.removeTerminalState&&a.push(e);return{promoteDraftThreadIds:r,clearDeletedThreadIds:i,removeTerminalStateThreadIds:a,needsProviderInvalidation:n}}var jX={all:[`projects`],searchContents:(e,t,n,r,i,a,o)=>[`projects`,`search-contents`,e??null,t,n,r,i,a,o],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},MX={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function w$e(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function T$e(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:w$e(e.cursors)}}}var NX={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,T$e(t)],stats:(e,t)=>[`pullRequests`,e,`stats`,[...t].toSorted((e,t)=>`${e.projectId}:${e.repository}#${e.number}`.localeCompare(`${t.projectId}:${t.repository}#${t.number}`))],detail:(e,t)=>[`pullRequests`,e,`detail`,t],activity:(e,t)=>[`pullRequests`,e,`activity`,t],diff:(e,t)=>[`pullRequests`,e,`diff`,t],threadComments:(e,t)=>[`pullRequests`,e,`thread-comments`,t],diffFileContents:(e,t)=>[`pullRequests`,e,`diff-file-contents`,t],reviewerCandidates:(e,t)=>[`pullRequests`,e,`reviewer-candidates`,t]},E$e=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function D$e(e,t){let n=new URL(e);return n.pathname=`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${t.startsWith(`/`)?t:`/${t}`}`,n.search=``,n.hash=``,n.toString()}async function O$e(e,t){let n=await e.text();if(!n)return t;try{let e=JSON.parse(n);if(typeof e.error==`string`&&e.error.length>0)return e.error}catch{}return n}async function PX(e){let t=D$e(e.httpBaseUrl,e.pathname),n;try{n=await fetch(t,{method:e.method??`GET`,headers:{...e.body===void 0?{}:{"content-type":`application/json`},...e.bearerToken?{authorization:`Bearer ${e.bearerToken}`}:{}},...e.body===void 0?{}:{body:JSON.stringify(e.body)},...e.signal?{signal:e.signal}:{}})}catch(e){throw Error(`Failed to fetch remote auth endpoint ${t} (${e.message}).`,{cause:e})}if(!n.ok)throw new E$e(await O$e(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function FX(e){return PX({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function k$e(e){return PX({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function A$e(e){return PX({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function IX(e){let t=new URL(e.wsBaseUrl,window.location.origin);if(e.runtimeTicket)return t.searchParams.set(`runtimeTicket`,e.runtimeTicket),t.searchParams.delete(`wsToken`),t.toString();let n=await A$e({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}var j$e=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null}),LX=()=>({...j$e}),RX=Xt()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:LX()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??LX(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})}));function M$e(e){return new Promise(t=>globalThis.setTimeout(t,e))}function zX(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function BX(e){if(e?.aborted)throw zX()}function VX(e,t){return t?t.aborted?Promise.reject(zX()):new Promise((n,r)=>{let i=()=>r(zX());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function HX(e,t){return t?t.aborted?Promise.reject(zX()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(zX())};t.addEventListener(`abort`,a,{once:!0})}):M$e(e)}function UX(e){let t=GK(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=RX.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}function WX(e){return!!e.runtimeId?.trim()||Dl(e.environmentId).isCloud}function N$e(e){let t=e.replacesEnvironmentId?an.make(e.replacesEnvironmentId):null,n=t&&t!==e.environmentId?GK(t):null;return{existing:GK(e.environmentId)??n,replacedRecord:n}}async function P$e(e){return{records:WK(),bearerToken:e?await XK(e.environmentId):null}}async function GX(e){let t=e.replacedRecord?.environmentId??e.record.environmentId;await zl(e.rollback.records),await ZK(e.record.environmentId).catch(()=>void 0),e.rollback.bearerToken&&await iYe(t,e.rollback.bearerToken)}async function F$e(e){try{e.replacedRecord?await rYe(e.replacedRecord.environmentId,e.record):await YK(e.record),BX(e.signal),await ZK(e.record.environmentId),e.replacedRecord&&await ZK(e.replacedRecord.environmentId),BX(e.signal)}catch(t){try{await GX(e)}catch(e){let n=AggregateError([t,e],`Cloud Environment rollback failed.`);throw n.cause=t,n}throw t}}function I$e(e,t){if(t){Rne(t,e);return}zne(e)}function L$e(e){let t=null,n=[];for(let r of e.split(/\r?\n/)){if(r.startsWith(`event:`)){t=r.slice(6).trim();continue}r.startsWith(`data:`)&&n.push(r.slice(5).trimStart())}return{eventName:t,data:n.join(`
1015
+ `)}}function R$e(e,t){let n=L$e(e);if(n.eventName!==`phase`||!n.data)return!1;try{let e=JSON.parse(n.data);return I$e(e,t),e.phase===`app-ready`||e.phase===`error`}catch{return!1}}async function z$e(e,t,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``;for(;!n.aborted;){let{done:e,value:n}=await r.read();if(e)break;a+=i.decode(n,{stream:!0});let o=a.indexOf(`
1016
1016
 
1017
- `);for(;o!==-1;){let e=a.slice(0,o);if(a=a.slice(o+2),z$e(e,t))return;o=a.indexOf(`
1017
+ `);for(;o!==-1;){let e=a.slice(0,o);if(a=a.slice(o+2),R$e(e,t))return;o=a.indexOf(`
1018
1018
 
1019
- `)}}}var V$e=(e=`/api/workspace/readiness`)=>{if(typeof fetch>`u`)return{close:()=>{}};let t=typeof e==`string`?{url:e}:e,n=!1,r=new AbortController;return fetch(t.url,{credentials:t.bearerToken?`omit`:`include`,signal:r.signal,...t.bearerToken?{headers:{Authorization:`Bearer ${t.bearerToken}`}}:{}}).then(e=>{if(e.ok)return B$e(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},H$e=6e4;function U$e(e){let t=new URL(e.target.httpBaseUrl);return t.pathname=`${t.pathname.endsWith(`/`)?t.pathname.slice(0,-1):t.pathname}/api/workspace/readiness`,t.search=``,t.hash=``,t.toString()}function W$e(e){let t=new Set,n=null,r=!1,i=!1;return{hasWaiters:()=>t.size>0,wait:()=>{if(r)return Promise.reject(n);if(i)return Promise.resolve();let a=null,o=null,s=new Promise((e,n)=>{o={resolve:e,reject:n},t.add(o)}),c=new Promise((t,n)=>{a=globalThis.setTimeout(()=>{n(Error(`Timed out while waiting for ${e.label} (${e.environmentId}) to stream its shell snapshot.`))},e.timeoutMs)});return Promise.race([s,c]).finally(()=>{a!==null&&globalThis.clearTimeout(a),o!==null&&t.delete(o)})},resolve:()=>{r=!1,n=null,i=!0;let e=[...t];t.clear();for(let t of e)t.resolve()},reject:e=>{r=!0,n=e,i=!1;let a=[...t];t.clear();for(let t of a)t.reject(e)},reset:()=>{r=!1,n=null,i=!1}}}function qX(e){let t=e.knownEnvironment.environmentId;if(!t)throw Error(`Known environment ${e.knownEnvironment.label} is missing its environmentId.`);let n=!1,r=!1,i=null,a=null,o=W$e({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??H$e}),s=e.readiness?(e.readiness.openStream??V$e)({url:U$e(e.knownEnvironment),environmentId:t,...e.readiness.bearerToken?{bearerToken:e.readiness.bearerToken}:{}}):null,c=t=>{if(!r){r=!0;let n=Error(t);_(),e.client.dispose(),e.onIdentityMismatch?.(n)}return!1},l=(n,r)=>{if(e.tolerateReportedEnvironmentIdentity)return a===null?(a=n,!0):a===n||c(`Environment connection ${t} reported a changed runtime identity (${a} -> ${n}) via ${r}.`);let i=e.resolveEnvironmentId?.()??t;return i===n||c(`Environment connection ${i} changed identity to ${n} via ${r}.`)},u=()=>e.resolveEnvironmentId?.()??t,d=e.client.server.subscribeLifecycle(t=>{t.type===`welcome`&&l(t.payload.environment.environmentId,`server lifecycle welcome`)&&e.onWelcome?.(t.payload,u())}),f=e.client.server.subscribeConfig(t=>{if(t.type===`snapshot`){if(!l(t.config.environment.environmentId,`server config snapshot`))return;i=t.config,e.onConfigSnapshot?.(t.config);return}if(t.type!==`providerStatuses`||!i)return;let n={...i,providers:t.payload.providers};i=n,e.onConfigSnapshot?.(n)}),p=e.client.orchestration.subscribeShell(t=>{if(t.kind===`snapshot`){e.syncShellSnapshot(t.snapshot,u()),o.resolve();return}e.applyShellEvent(t,u())},{onResubscribe:()=>{n||o.reset()},onError:t=>{if(!n){if(o.hasWaiters()){o.reject(t);return}e.onShellSubscriptionError?.(t,u())}}}),m=e.client.terminal.onEvent(t=>{e.applyTerminalEvent(t,u())}),h=e.client.browser?.onEvent({},t=>{e.applyBrowserEvent(t,u())}),g=e.client.server.subscribeWorkspaceReadiness(e=>{n||N(async()=>{let{setWorkspaceReadinessPhaseForEnvironment:e}=await import(`./workspaceReadinessAtom-D6bgTvKb.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([3,1,4,5])).then(({setWorkspaceReadinessPhaseForEnvironment:t})=>{n||t(u(),e)})}),_=()=>{n||(n=!0,e.onDispose?.(),s?.close(),p(),m(),h?.(),d(),f(),g())};return{kind:e.kind,environmentId:t,knownEnvironment:e.knownEnvironment,client:e.client,ensureBootstrapped:()=>o.wait(),reconnect:async()=>{o.reset();try{await e.client.reconnect(),await e.refreshMetadata?.(),await o.wait()}catch(e){throw o.reject(e),e}},...e.ensureProviderAuthority?{ensureProviderAuthority:e.ensureProviderAuthority}:{},dispose:async()=>{_(),await e.client.dispose()}}}function G$e(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var K$e=3e4,q$e=1e4,J$e=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,JX=/https?:\/\/[^\s"'`<>]+/gu,Y$e=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),X$e=/(https?:\/\/(?:localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|192\.168(?:\.\d{1,3}){2}):)\s+(\d{1,5})(?=[/?#\s]|$)/giu;function YX(e){let t=e.trim();if(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t))return null;let n=t.split(/[/:?#]/,1)[0]??``,r=J$e.test(t)||ZX(n)?`http`:`https`,i=/^https?:\/\//i.test(t)?t:`${r}://${t}`;try{let e=new URL(i);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function Z$e(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function XX(e){try{let t=new URL(e);return Dne(t.hostname)}catch{return!1}}function ZX(e){return Tne(e)}function QX(e){try{let t=new URL(e);if(t.protocol!==`http:`||!XX(t.toString())&&!ZX(t.hostname)||!t.port)return null;let n=Number(t.port);return Number.isInteger(n)&&n>0&&n<=65535?n:null}catch{return null}}function Q$e(e){let t=e.replace(/[.,;!?]+$/u,``);for(;t.endsWith(`)`)||t.endsWith(`]`)||t.endsWith(`}`);){let e=t.at(-1);if(!e)break;let n=e===`)`?`(`:e===`]`?`[`:`{`;if(t.split(n).length-1>=t.split(e).length-1)break;t=t.slice(0,-1)}return t}function $$e(e){return e.replace(Y$e,``).replaceAll(/./gsu,e=>e1e(e)?``:e).replace(X$e,`$1$2`)}function e1e(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function $X(e){let t=null,n=null,r=$$e(e);JX.lastIndex=0;for(let e of r.matchAll(JX)){let r=YX(Q$e(e[0]));!r||!QX(r)||(t=r,XX(r)&&(n=r))}return n??t}function t1e(e){let t=null;for(let n of e){let e=n.event,r=$X(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function n1e(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var r1e=`forge:terminal-state:v1`,eZ=[],i1e=200,tZ=8;function a1e(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:dZ(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!Wo(e)&&typeof t?.url==`string`&&!!QX(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function o1e(){return AJ(typeof window<`u`?window.localStorage:void 0)}function s1e(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[hJ]}function c1e(e,t){if(e.length===0)return[];let n=new Set(t);return[...new Set(e)].map(e=>e.trim()).filter(e=>e.length>0&&n.has(e))}function nZ(e){return`group-${e}`}function rZ(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}-${r}`,r+=1;return t.add(n),n}function iZ(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function l1e(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function u1e(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=l1e(t.terminalIds).filter(e=>!(!n.has(e)||r.has(e)));if(e.length===0)continue;for(let t of e)r.add(t);let o=t.id.trim().length>0?t.id.trim():nZ(e[0]??`default`);i.push({id:rZ(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:rZ(nZ(e),a),terminalIds:[e]});return i.length===0?[{id:nZ(hJ),terminalIds:[hJ]}]:i}function aZ(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function d1e(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||!aZ(r.terminalIds,i.terminalIds))return!1}return!0}function oZ(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&aZ(e.terminalIds,t.terminalIds)&&aZ(e.runningTerminalIds,t.runningTerminalIds)&&d1e(e.terminalGroups,t.terminalGroups)}var sZ=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[hJ],runningTerminalIds:[],activeTerminalId:hJ,terminalGroups:[{id:nZ(hJ),terminalIds:[hJ]}],activeTerminalGroupId:nZ(hJ)});function cZ(){return{...sZ,terminalIds:[...sZ.terminalIds],runningTerminalIds:[...sZ.runningTerminalIds],terminalGroups:yZ(sZ.terminalGroups)}}function lZ(){return sZ}function uZ(e){let t=s1e(e.terminalIds),n=t.length>0?t:[hJ],r=c1e(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=u1e(e.terminalGroups,n),o=a.some(t=>t.id===e.activeTerminalGroupId)?e.activeTerminalGroupId:null,s=a.find(e=>e.terminalIds.includes(i))?.id??null,c={terminalOpen:e.terminalOpen,terminalHeight:Number.isFinite(e.terminalHeight)&&e.terminalHeight>0?e.terminalHeight:280,terminalIds:n,runningTerminalIds:r,activeTerminalId:i,terminalGroups:a,activeTerminalGroupId:o??s??a[0]?.id??nZ(`default`)};return oZ(e,c)?e:c}function f1e(e){let t=uZ(e);if(t.terminalIds.length<=tZ)return t;let n=new Set,r=e=>{!e||n.size>=tZ||t.terminalIds.includes(e)&&n.add(e)};r(hJ),r(t.activeTerminalId);for(let e of t.runningTerminalIds)r(e);for(let e of t.terminalIds.toReversed())r(e);let i=t.terminalIds.filter(e=>n.has(e)),a=i[i.length-1]??i[0]??`default`,o=i.includes(t.activeTerminalId)?t.activeTerminalId:a;return uZ({...t,terminalIds:i.length>0?i:[hJ],runningTerminalIds:t.runningTerminalIds.filter(e=>n.has(e)),activeTerminalId:o,terminalGroups:t.terminalGroups.map(e=>({id:e.id,terminalIds:e.terminalIds.filter(e=>n.has(e))})).filter(e=>e.terminalIds.length>0)})}function dZ(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>Wo(e)?[[e,f1e(t)]]:[]))}function p1e(e){return oZ(uZ(e),sZ)}function m1e(e){return e.trim().length>0}function fZ(e){return Vo(e)}function pZ(e,t){return`${fZ(e)}\u0000${t}`}function mZ(e,t){return pZ(e,t)}function hZ(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function gZ(e,t){let n=$X(e);return n?{url:n,observedAt:t}:null}function h1e(e){return gZ(e.history,e.updatedAt)}function _Z(e){return e.type===`output`?gZ(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?gZ(e.snapshot.history,e.snapshot.updatedAt):null}function vZ(e,t,n){if(!n)return e;let r=fZ(t),i=e[r];return i&&hZ(i.observedAt)>hZ(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function yZ(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function bZ(e,t,n,r){let i=pZ(n,r.terminalId),a=e[i]??eZ,o={id:t,event:r},s=a.length>=i1e?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function xZ(e,t,n,r){let i=pZ(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function SZ(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function CZ(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function wZ(e,t){let n={...e},r=!1;for(let e of Object.keys(n))e.startsWith(`${t}\u0000`)&&(delete n[e],r=!0);return r?n:e}function g1e(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function _1e(e,t){let n=g1e(t);return e?.runtimeEnv&&e.cwd===n.cwd&&e.worktreePath===n.worktreePath&&(e.terminalId===void 0||e.terminalId===t.terminalId)?{...n,runtimeEnv:e.runtimeEnv}:n}function TZ(e,t,n){let r=uZ(e);if(!m1e(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=yZ(r.terminalGroups),s=iZ(o,t);if(s>=0&&(o[s].terminalIds=o[s].terminalIds.filter(e=>e!==t),o[s].terminalIds.length===0&&o.splice(s,1)),n===`new`){let e=new Set(o.map(e=>e.id)),n=rZ(nZ(t),e);return o.push({id:n,terminalIds:[t]}),uZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=iZ(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=rZ(nZ(r.activeTerminalId),e);o.push({id:t,terminalIds:[r.activeTerminalId]}),c=o.length-1}let l=o[c];if(!l||i&&!l.terminalIds.includes(t)&&l.terminalIds.length>=4)return r;if(!l.terminalIds.includes(t)){let e=l.terminalIds.indexOf(r.activeTerminalId);e>=0?l.terminalIds.splice(e+1,0,t):l.terminalIds.push(t)}return uZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function EZ(e,t){let n=uZ(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function v1e(e,t){let n=uZ(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function y1e(e,t){return TZ(e,t,`split`)}function DZ(e,t,n){let r=TZ(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function OZ(e,t){let n=uZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalGroups.find(e=>e.terminalIds.includes(t))?.id??n.activeTerminalGroupId;return n.activeTerminalId===t&&n.activeTerminalGroupId===r?n:{...n,activeTerminalId:t,activeTerminalGroupId:r}}function b1e(e,t){let n=uZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return cZ();let i=n.terminalIds.indexOf(t),a=n.activeTerminalId===t?r[Math.min(i,r.length-1)]??r[0]??`default`:n.activeTerminalId,o=n.terminalGroups.map(e=>({...e,terminalIds:e.terminalIds.filter(e=>e!==t)})).filter(e=>e.terminalIds.length>0),s=o.find(e=>e.terminalIds.includes(a))?.id??o[0]?.id??nZ(a);return uZ({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function kZ(e,t,n){let r=uZ(e);if(!r.terminalIds.includes(t)||n===r.runningTerminalIds.includes(t))return r;let i=new Set(r.runningTerminalIds);return n?i.add(t):i.delete(t),{...r,runningTerminalIds:[...i]}}function AZ(e,t){return!t||t.threadId.length===0?lZ():e[fZ(t)]??lZ()}function jZ(e,t,n){if(t.threadId.length===0)return e;let r=fZ(t),i=AZ(e,t),a=n(i);if(a===i)return e;if(p1e(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function x1e(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?eZ:e[pZ(t,n)]??eZ}function S1e(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[mZ(t,n)]??null}function C1e(e,t){if(!t||t.threadId.length===0)return[];let n=`${fZ(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function w1e(e,t){return!t||t.threadId.length===0?null:e[fZ(t)]??null}var MZ=Xt()(wJ(e=>{let t=(t,n)=>{e(e=>{let r=jZ(e.terminalStateByThreadKey,t,n);return r===e.terminalStateByThreadKey?e:{terminalStateByThreadKey:r}})};return{terminalStateByThreadKey:{},terminalLaunchContextByThreadKey:{},terminalEventEntriesByKey:{},terminalSessionSnapshotByKey:{},terminalStreamCursorByKey:{},terminalPreviewUrlByThreadKey:{},nextTerminalEventId:1,setTerminalOpen:(e,n)=>t(e,e=>EZ(e,n)),setTerminalHeight:(e,n)=>t(e,e=>v1e(e,n)),splitTerminal:(e,n)=>t(e,e=>y1e(e,n)),newTerminal:(e,n,r)=>t(e,e=>DZ(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=DZ(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=OZ(t,n)),r?.open&&(t=EZ(t,!0)),uZ(t)}),setActiveTerminal:(e,n)=>t(e,e=>OZ(e,n)),closeTerminal:(e,n)=>t(e,e=>b1e(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[fZ(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=fZ(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>kZ(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=mZ(t,n.terminalId),i=SZ(n),a=n.type===`started`||n.type===`restarted`;if(CZ(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?xZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):bZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=vZ(e.terminalPreviewUrlByThreadKey,t,_Z(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[mZ(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=fZ(t),i=mZ(t,n.terminalId),a=SZ(n),o=n.type===`started`||n.type===`restarted`;if(CZ(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=vZ(e.terminalPreviewUrlByThreadKey,t,_Z(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[mZ(t,n.terminalId)]:n.snapshot},s=jZ(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=DZ(r,n.terminalId)),t?(r=OZ(r,n.terminalId),r=EZ(r,!0)):(r=OZ(r,e.activeTerminalId),r=EZ(r,e.terminalOpen)),uZ(r)}),c={...c,[r]:_1e(c[r],n)});let d=n1e(n);d!==null&&(s=jZ(s,t,e=>kZ(e,n.terminalId,d)));let f=o&&a?xZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):bZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),p=a?{...e.terminalStreamCursorByKey,[i]:a}:e.terminalStreamCursorByKey;return{terminalStateByThreadKey:s,terminalLaunchContextByThreadKey:c,terminalSessionSnapshotByKey:l,terminalStreamCursorByKey:p,terminalPreviewUrlByThreadKey:u,...f}}),setTerminalSessionSnapshot:(t,n)=>e(e=>({terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[mZ(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:vZ(e.terminalPreviewUrlByThreadKey,t,h1e(n))})),clearTerminalState:t=>e(e=>{let n=fZ(t),r=jZ(e.terminalStateByThreadKey,t,()=>cZ()),i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,{[n]:o,...s}=e.terminalLaunchContextByThreadKey,{[n]:c,...l}=e.terminalPreviewUrlByThreadKey,u={...e.terminalEventEntriesByKey},d=!1;for(let e of Object.keys(u))e.startsWith(`${n}\u0000`)&&(delete u[e],d=!0);let f={...e.terminalSessionSnapshotByKey},p=!1;for(let e of Object.keys(f))e.startsWith(`${n}\u0000`)&&(delete f[e],p=!0);let m=wZ(e.terminalStreamCursorByKey,n);return r===e.terminalStateByThreadKey&&!i&&!a&&!d&&!p&&m===e.terminalStreamCursorByKey?e:{terminalStateByThreadKey:r,terminalLaunchContextByThreadKey:s,terminalPreviewUrlByThreadKey:l,terminalEventEntriesByKey:u,terminalSessionSnapshotByKey:f,terminalStreamCursorByKey:m}}),removeTerminalState:t=>e(e=>{let n=fZ(t),r=e.terminalStateByThreadKey[n]!==void 0,i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,o={...e.terminalEventEntriesByKey},s=!1;for(let e of Object.keys(o))e.startsWith(`${n}\u0000`)&&(delete o[e],s=!0);let c={...e.terminalSessionSnapshotByKey},l=!1;for(let e of Object.keys(c))e.startsWith(`${n}\u0000`)&&(delete c[e],l=!0);let u=wZ(e.terminalStreamCursorByKey,n);if(!r&&!i&&!a&&!s&&!l&&u===e.terminalStreamCursorByKey)return e;let d={...e.terminalStateByThreadKey};delete d[n];let f={...e.terminalLaunchContextByThreadKey};delete f[n];let p={...e.terminalPreviewUrlByThreadKey};return delete p[n],{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:o,terminalSessionSnapshotByKey:c,terminalStreamCursorByKey:u}}),removeOrphanedTerminalStates:t=>e(e=>{let n=Object.keys(e.terminalStateByThreadKey).filter(e=>!t.has(e)),r=Object.keys(e.terminalLaunchContextByThreadKey).filter(e=>!t.has(e)),i=Object.keys(e.terminalPreviewUrlByThreadKey).filter(e=>!t.has(e)),a={...e.terminalEventEntriesByKey},o=!1;for(let e of Object.keys(a)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete a[e],o=!0)}let s={...e.terminalSessionSnapshotByKey},c=!1;for(let e of Object.keys(s)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete s[e],c=!0)}let l={...e.terminalStreamCursorByKey},u=!1;for(let e of Object.keys(l)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete l[e],u=!0)}if(n.length===0&&r.length===0&&i.length===0&&!o&&!c&&!u)return e;let d={...e.terminalStateByThreadKey};for(let e of n)delete d[e];let f={...e.terminalLaunchContextByThreadKey};for(let e of r)delete f[e];let p={...e.terminalPreviewUrlByThreadKey};for(let e of i)delete p[e];return{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:a,terminalSessionSnapshotByKey:s,terminalStreamCursorByKey:l}})}},{name:r1e,version:4,storage:SJ(o1e),migrate:a1e,partialize:e=>({terminalStateByThreadKey:dZ(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function T1e(e){return typeof e==`string`?e:typeof e==`object`&&e&&`detail`in e&&typeof e.detail==`string`?e.detail:e instanceof Error?e.message:String(e)}function E1e(e){return e.match(/blocked by policy for\s+([^.\s]+(?:\.[^.\s]+)*)\.?/i)?.[1]||(e.match(/navigation to\s+([^.\s]+(?:\.[^.\s]+)*)\s+is restricted/i)?.[1]??null)}function NZ(e){let t=T1e(e).trim()||`Unknown browser error.`,n=E1e(t);return/blocked by policy|restricted to allowed domains/i.test(t)?{title:`Browser navigation blocked`,cause:`${n??`This URL`} is not allowed by the current browser policy.`,nextAction:`Use an allowed URL or update the browser allowed-domain setting.`,technicalDetail:t}:/does not match thread|session .*not found|no active browser tab|tab .*not found/i.test(t)?{title:`Browser session is stale`,cause:`Forge no longer has a matching live browser session for this thread.`,nextAction:`Restart the browser session from the Browser options menu.`,technicalDetail:t}:/screenshot|capture|Page\.capture/i.test(t)?{title:`Browser screenshot failed`,cause:`The browser could not capture the current page frame.`,nextAction:`Reload the page, then try the screenshot again.`,technicalDetail:t}:/timed out|timeout/i.test(t)?{title:`Browser action timed out`,cause:`Forge did not receive a response from the browser runtime in time.`,nextAction:`Retry the action. If it keeps failing, restart the browser session.`,technicalDetail:t}:/runtime is not available|browser.*unavailable|not supported|disabled/i.test(t)?{title:`Browser session unavailable`,cause:`This environment does not currently expose the in-app browser runtime.`,nextAction:`Use a workspace with browser support or restart Forge after browser support is enabled.`,technicalDetail:t}:/navigate|navigation|net::|ERR_/i.test(t)?{title:`Browser navigation failed`,cause:`The browser could not load the requested page.`,nextAction:`Check the URL and network access, then try again.`,technicalDetail:t}:{title:`Browser action failed`,cause:`Forge could not complete the browser action.`,nextAction:`Retry the action. If it keeps failing, restart the browser session from the Browser options menu.`,technicalDetail:t}}function D1e(e){let t=NZ(e);return`${t.cause} ${t.nextAction}`}function O1e(e){let t=NZ(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var PZ={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function FZ(e){return Vo(e)}function k1e(e){let t=e.status===`reconnecting`&&e.reason===`network_unreachable`;return e.transport===`remote-webrtc`&&(e.status===`connected`||e.status===`connecting`||e.status===`reconnecting`)&&(e.reason!==`network_unreachable`||t)&&e.reason!==`unsupported_host`}function A1e(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function IZ(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!k1e(t.display)||!A1e(n.display)?n:{...n,display:{...t.display,viewport:n.display.viewport??n.viewport??t.display.viewport,devicePixelRatio:n.display.devicePixelRatio??t.display.devicePixelRatio,iceServers:n.display.iceServers??t.display.iceServers,reconnect:t.display.reconnect??n.display.reconnect}}}function j1e(e){let{storedSession:t,nextSession:n}=e;if(!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId)return!1;let r=n.tabs.some(e=>e.navigationStatus===`pending`),i=t.tabs.some(e=>e.navigationStatus===`complete`||e.navigationStatus===`failed`);if(!r||!i)return!1;let a=Date.parse(t.updatedAt),o=Date.parse(n.updatedAt);return Number.isNaN(a)||Number.isNaN(o)?!1:o<a}function LZ(e,t,n){return e[t]===n?e:{...e,[t]:n}}function M1e(e){switch(e.type){case`tab.updated`:return e.payload.tab.tabId;case`tab.closed`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`console.logs.ready`:case`display.iceCandidate`:case`display.metrics`:return e.payload.tabId;case`action.failed`:return e.payload.tabId??null;case`display.updated`:case`session.started`:case`session.updated`:case`session.closed`:return null}}function N1e(e,t){let n=M1e(t);return n?{...e,lastActivityByTabId:{...e.lastActivityByTabId,[n]:{actor:t.agentId?`agent`:`human`,agentId:t.agentId,browserId:t.browserId,eventType:t.type,...t.type===`action.failed`?{commandType:t.payload.commandType}:{},...t.type===`action.failed`?{message:t.payload.message}:{},createdAt:t.createdAt}}}:e}function P1e(e){switch(e.type){case`session.started`:case`session.updated`:case`tab.updated`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`display.updated`:return!0;case`session.closed`:case`tab.closed`:case`console.logs.ready`:case`action.failed`:case`display.iceCandidate`:case`display.metrics`:return!1}}function RZ(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function F1e(e,t){let n=RZ(t);return e.some(e=>RZ(e)===n)?e:[...e,t]}function I1e(e){if(e.type!==`session.closed`)return null;switch(e.payload.reason){case`idle_timeout`:return`The browser was closed after being idle. Reopen the preview to restore this thread's browser.`;case`runtime_shutdown`:return`The browser runtime shut down. Reopen the preview to restore this thread's browser.`;case`thread_archived`:case`clear_browsing_data`:case`user_closed`:case void 0:return null}}function L1e(e){let t=e.event.payload.display;return t.status===`failed`||t.status===`unsupported`?t.detail??`Browser display is unavailable.`:e.currentLastError&&/browser display/i.test(e.currentLastError)?null:e.currentLastError}function R1e(e,t){let n=e.sessionsByBrowserId[t.browserId]??(e.session?.browserId===t.browserId?e.session:null);if(!n)return!0;let r=n.sessionId===t.payload.sessionId,i=!t.sessionEpoch||!n.sessionEpoch||t.sessionEpoch===n.sessionEpoch;return r&&i}function z1e(e,t){let n=e.lastFrameSequenceByTabId[t]??0;return{acceptedSequence:n,observedSequence:e.lastObservedFrameSequenceByTabId[t]??n,...e.lastFrameStreamIdByTabId[t]?{streamId:e.lastFrameStreamIdByTabId[t]}:{},...e.lastFrameStreamGenerationByTabId[t]===void 0?{}:{streamGeneration:e.lastFrameStreamGenerationByTabId[t]},...e.lastFrameMetaByTabId[t]?.capturedAt?{acceptedCapturedAt:e.lastFrameMetaByTabId[t].capturedAt}:{},gapCount:e.frameGapCountByTabId[t]??0}}function B1e(e,t){let n=t.payload.tabId,r=Ice(z1e(e,n),{sequence:t.payload.sequence,capturedAt:t.payload.capturedAt,...t.payload.streamId?{streamId:t.payload.streamId}:{},...t.payload.streamGeneration===void 0?{}:{streamGeneration:t.payload.streamGeneration},...t.payload.keyframe===void 0?{}:{keyframe:t.payload.keyframe}});return{decision:r,observedSequence:r.state.observedSequence,frameGapCount:r.state.gapCount}}function V1e(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function H1e(e,t){let n=t.payload.tabId;return{...e,lastFrameByTabId:{...e.lastFrameByTabId,[n]:t.payload.imageDataUrl},lastFrameSequenceByTabId:{...e.lastFrameSequenceByTabId,[n]:t.payload.sequence},lastFrameStreamIdByTabId:t.payload.streamId?{...e.lastFrameStreamIdByTabId,[n]:t.payload.streamId}:e.lastFrameStreamIdByTabId,lastFrameStreamGenerationByTabId:t.payload.streamGeneration===void 0?e.lastFrameStreamGenerationByTabId:{...e.lastFrameStreamGenerationByTabId,[n]:t.payload.streamGeneration},lastFrameMetaByTabId:{...e.lastFrameMetaByTabId,[n]:{capturedAt:t.payload.capturedAt,url:t.payload.url,viewport:t.payload.viewport}},lastError:null}}function U1e(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!R1e(t,n))return i;let o=B1e(t,n);if(!o.decision.observe)return i;let s=V1e(t,n,o),c=o.decision.accept?H1e(s,n):s;return{browserStateByThreadKey:LZ(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var zZ=Xt(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=FZ(t),i=e.browserStateByThreadKey[r]??PZ,a=n?IZ({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...i,session:a,selectedBrowserId:a?.browserId??i.selectedBrowserId,sessionsByBrowserId:a?{...i.sessionsByBrowserId,[a.browserId]:a}:i.sessionsByBrowserId,lastError:a?null:i.lastError})}}),selectBrowserSession:(t,n)=>e(e=>{let r=FZ(t),i=e.browserStateByThreadKey[r]??PZ,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=FZ(t),i=P1e(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=N1e(e.browserStateByThreadKey[r]??PZ,n);switch(n.type){case`session.started`:{if(j1e({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=IZ({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:t,selectedBrowserId:a.selectedBrowserId??t.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.updated`:{let t=IZ({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:a.selectedBrowserId&&a.selectedBrowserId!==n.payload.snapshot.browserId?a.session:t,selectedBrowserId:a.selectedBrowserId??n.payload.snapshot.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.closed`:let t=a.selectedBrowserId===n.browserId||a.session?.browserId===n.browserId;return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:t?null:a.session,selectedBrowserId:t?null:a.selectedBrowserId,sessionsByBrowserId:Object.fromEntries(Object.entries(a.sessionsByBrowserId).filter(([e])=>e!==n.browserId)),lastError:I1e(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:L1e({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o=t.tabs.map(e=>e.tabId===n.payload.tab.tabId?{...n.payload.tab,isActive:e.tabId===t.activeTabId}:{...e,isActive:e.tabId===t.activeTabId}).concat(t.tabs.some(e=>e.tabId===n.payload.tab.tabId)?[]:[{...n.payload.tab,isActive:n.payload.tab.tabId===t.activeTabId}]);return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:o},lastError:null}),pendingAutoRevealKeys:i}}case`tab.closed`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return e;let i=t.tabs.filter(e=>e.tabId!==n.payload.tabId);return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:i,activeTabId:t.activeTabId===n.payload.tabId?i[0]?.tabId??null:t.activeTabId}})}}case`snapshot.ready`:return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,lastScreenshotDataUrlByTabId:{...a.lastScreenshotDataUrlByTabId,[n.payload.tabId]:n.payload.imageDataUrl},lastScreenshotMetaByTabId:{...a.lastScreenshotMetaByTabId,[n.payload.tabId]:{captureId:n.payload.captureId,capturedAt:n.payload.capturedAt,url:n.payload.url,viewport:n.payload.viewport}},lastError:null}),pendingAutoRevealKeys:i};case`frame.ready`:return U1e({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,lastConsoleLogsByTabId:{...a.lastConsoleLogsByTabId,[n.payload.tabId]:n.payload.logs},lastConsoleLogsMetaByTabId:{...a.lastConsoleLogsMetaByTabId,[n.payload.tabId]:{capturedAt:n.createdAt,tabId:n.payload.tabId,count:n.payload.logs.length}},lastError:null})};case`display.iceCandidate`:{let t=a.displayIceCandidatesByClientId[n.payload.clientId]??[];return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:F1e(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:LZ(e.browserStateByThreadKey,r,{...a,lastError:O1e(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=FZ(t);if(!(n in e.browserStateByThreadKey))return e;let{[n]:r,...i}=e.browserStateByThreadKey;return{browserStateByThreadKey:i}}),consumeAutoReveal:t=>e(e=>{if(!e.pendingAutoRevealKeys.has(t))return e;let n=new Set(e.pendingAutoRevealKeys);return n.delete(t),{pendingAutoRevealKeys:n}})}));function W1e(e,t){return t?e[FZ(t)]??null:null}var G1e={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function K1e(e){return{x:Math.max(12,Math.min(e.position.x,e.viewportWidth-e.width-12)),y:Math.max(12,Math.min(e.position.y,e.viewportHeight-e.height-12))}}function q1e(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function J1e(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}var BZ=`forge:ui-state:v1`,VZ=[`t3code:ui-state:v1`,`t3code:renderer-state:v8`,`t3code:renderer-state:v7`,`t3code:renderer-state:v6`,`t3code:renderer-state:v5`,`t3code:renderer-state:v4`,`t3code:renderer-state:v3`,`codething:renderer-state:v4`,`codething:renderer-state:v3`,`codething:renderer-state:v2`,`codething:renderer-state:v1`],HZ=`months`,Y1e=new Set([`weeks`,`months`,`quarters`]);function X1e(e){return typeof e==`string`&&Y1e.has(e)?e:HZ}function UZ(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var WZ={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:HZ,projectLeadCompanion:G1e},GZ=new Set,KZ=[],qZ=new Map,JZ=!1;function Z1e(){if(typeof window>`u`)return WZ;try{let e=window.localStorage.getItem(BZ);if(!e){for(let e of VZ){let t=window.localStorage.getItem(e);if(t)return YZ(JSON.parse(t)),WZ}return WZ}let t=JSON.parse(e);return YZ(t),{...WZ,projectGroupOrder:Q1e(t.projectGroupOrderKeys),threadChangedFilesExpandedById:t0e(t.threadChangedFilesExpandedById),pinnedThreadById:$1e(t.pinnedThreadKeys),threadLinkedPrById:e0e(t.threadLinkedPrById),timelineWorkColumnWidth:UZ(t.timelineWorkColumnWidth??360),timelineScale:X1e(t.timelineScale)}}catch{return WZ}}function Q1e(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function $1e(e){if(!Array.isArray(e))return{};let t={};for(let n of e)typeof n==`string`&&n.length>0&&(t[n]=!0);return t}function e0e(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length!==0&&typeof r==`string`&&r.trim().length!==0&&(t[n]=r);return t}function t0e(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!r||typeof r!=`object`)continue;let e={};for(let[t,n]of Object.entries(r))t&&typeof n==`boolean`&&n===!1&&(e[t]=!1);Object.keys(e).length>0&&(t[n]=e)}return t}function YZ(e){GZ.clear(),KZ.length=0;for(let t of e.expandedProjectCwds??[])typeof t==`string`&&t.length>0&&GZ.add(t);for(let t of e.projectOrderCwds??[])typeof t==`string`&&t.length>0&&!KZ.includes(t)&&KZ.push(t)}function n0e(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=qZ.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=qZ.get(e);return t?[t]:[]}),r=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).flatMap(([e,t])=>{let n=Object.fromEntries(Object.entries(t).filter(([,e])=>e===!1));return Object.keys(n).length>0?[[e,n]]:[]}));if(window.localStorage.setItem(BZ,JSON.stringify({expandedProjectCwds:t,projectOrderCwds:n,projectGroupOrderKeys:e.projectGroupOrder,threadChangedFilesExpandedById:r,pinnedThreadKeys:Object.keys(e.pinnedThreadById).filter(t=>e.pinnedThreadById[t]),threadLinkedPrById:e.threadLinkedPrById,timelineWorkColumnWidth:e.timelineWorkColumnWidth,timelineScale:e.timelineScale})),!JZ){JZ=!0;for(let e of VZ)window.localStorage.removeItem(e)}}catch{}}var XZ=new Qt(n0e,{wait:500});function ZZ(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(t[e]!==r)return!1;return!0}function QZ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function r0e(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(!(e in t)||!ZZ(r,t[e]))return!1;return!0}function i0e(e,t){let n=new Map(qZ),r=new Map([...n.entries()].map(([e,t])=>[t,e]));qZ.clear();for(let e of t)qZ.set(e.key,e.cwd);let i=n.size!==qZ.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(KZ.map((e,t)=>[e,t])),c=t.map((e,t)=>{let n=r.get(e.cwd),i=o[e.key]??(n?o[n]:void 0)??(GZ.size>0?GZ.has(e.cwd):!0);return a[e.key]=i,{id:e.key,cwd:e.cwd,incomingIndex:t}}),l=e.projectOrder.length>0?(()=>{let t=new Map(c.map(e=>[e.cwd,e.id])),r=new Set,i=[];for(let o of e.projectOrder){let e=(o in a?o:void 0)??(()=>{let e=n.get(o);return e?t.get(e):void 0})();!e||r.has(e)||(r.add(e),i.push(e))}for(let e of c)r.has(e.id)||i.push(e.id);return i})():c.map(e=>({id:e.id,incomingIndex:e.incomingIndex,orderIndex:s.get(e.cwd)??KZ.length+e.incomingIndex})).toSorted((e,t)=>{let n=e.orderIndex-t.orderIndex;return n===0?e.incomingIndex-t.incomingIndex:n}).map(e=>e.id);return ZZ(e.projectExpandedById,a)&&QZ(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function a0e(e,t){let n=new Set(t.map(e=>e.key)),r=Object.fromEntries(Object.entries(e.threadLastVisitedAtById).filter(([e])=>n.has(e)));for(let e of t)r[e.key]===void 0&&e.seedVisitedAt!==void 0&&e.seedVisitedAt.length>0&&(r[e.key]=e.seedVisitedAt);let i=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).filter(([e])=>n.has(e))),a=Object.fromEntries(Object.entries(e.pinnedThreadById).filter(([e,t])=>n.has(e)&&t)),o=Object.fromEntries(Object.entries(e.threadLinkedPrById).filter(([e])=>n.has(e)));return ZZ(e.threadLastVisitedAtById,r)&&r0e(e.threadChangedFilesExpandedById,i)&&ZZ(e.pinnedThreadById,a)&&ZZ(e.threadLinkedPrById,o)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o}}function o0e(e,t,n){let r=n??new Date().toISOString(),i=Date.parse(r),a=e.threadLastVisitedAtById[t],o=a?Date.parse(a):NaN;return Number.isFinite(o)&&Number.isFinite(i)&&o>=i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:r}}}function s0e(e,t,n){if(!n)return e;let r=Date.parse(n);if(Number.isNaN(r))return e;let i=new Date(r-1).toISOString();return e.threadLastVisitedAtById[t]===i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:i}}}function c0e(e,t){let n=t in e.threadLastVisitedAtById,r=t in e.threadChangedFilesExpandedById,i=t in e.pinnedThreadById,a=t in e.threadLinkedPrById;if(!n&&!r&&!i&&!a)return e;let o={...e.threadLastVisitedAtById},s={...e.threadChangedFilesExpandedById},c={...e.pinnedThreadById},l={...e.threadLinkedPrById};return delete o[t],delete s[t],delete c[t],delete l[t],{...e,threadLastVisitedAtById:o,threadChangedFilesExpandedById:s,pinnedThreadById:c,threadLinkedPrById:l}}function $Z(e,t,n){if(e.pinnedThreadById[t]===!0===n)return e;if(n)return{...e,pinnedThreadById:{...e.pinnedThreadById,[t]:!0}};let r={...e.pinnedThreadById};return delete r[t],{...e,pinnedThreadById:r}}function l0e(e,t){return $Z(e,t,e.pinnedThreadById[t]!==!0)}function u0e(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function d0e(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function f0e(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}function p0e(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function m0e(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function h0e(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function g0e(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function _0e(e,t,n){if(t.length===0)return e;let r=new Set(t),i=new Set(n);if(t.every(e=>i.has(e)))return e;let a=e.projectOrder.findIndex(e=>i.has(e));if(a<0)return e;let o=[...e.projectOrder],s=[],c=0;for(let e=o.length-1;e>=0;e--)r.has(o[e])&&(s.unshift(o.splice(e,1)[0]),e<a&&c++);if(s.length===0)return e;let l=a-Math.max(0,c-1);return o.splice(l,0,...s),{...e,projectOrder:o}}function v0e(e,t){let n=[...new Set(t)],r=new Set(n),i=e.projectGroupOrder.filter(e=>r.has(e)),a=new Set(i);for(let e of n)a.has(e)||i.push(e);return QZ(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function y0e(e,t,n){if(t===n)return e;let r=e.projectGroupOrder.indexOf(t),i=e.projectGroupOrder.indexOf(n);if(r<0||i<0)return e;let a=[...e.projectGroupOrder],[o]=a.splice(r,1);return o===void 0?e:(a.splice(i,0,o),{...e,projectGroupOrder:a})}var eQ=Xt(e=>({...Z1e(),syncProjects:t=>e(e=>i0e(e,t)),syncProjectGroups:t=>e(e=>v0e(e,t)),syncThreads:t=>e(e=>a0e(e,t)),markThreadVisited:(t,n)=>e(e=>o0e(e,t,n)),markThreadUnread:(t,n)=>e(e=>s0e(e,t,n)),clearThreadUi:t=>e(e=>c0e(e,t)),setThreadPinned:(t,n)=>e(e=>$Z(e,t,n)),toggleThreadPinned:t=>e(e=>l0e(e,t)),setThreadLinkedPr:(t,n)=>e(e=>u0e(e,t,n)),clearThreadLinkedPr:t=>e(e=>d0e(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>f0e(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>m0e(e,t,n)),toggleProject:t=>e(e=>h0e(e,t)),setProjectExpanded:(t,n)=>e(e=>g0e(e,t,n)),reorderProjects:(t,n)=>e(e=>_0e(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>y0e(e,t,n)),setLastActiveProject:t=>e(e=>p0e(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:UZ(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:q1e(e.projectLeadCompanion,t)})),closeProjectLeadCompanion:()=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,open:!1}})),setProjectLeadCompanionMinimized:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,minimized:t}})),setProjectLeadCompanionDock:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,dock:t}})),setProjectLeadCompanionPosition:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,position:t}}))}));function b0e(e){eQ.getState().openProjectLeadCompanion(e)}eQ.subscribe(e=>XZ.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{XZ.flush()});var x0e=$e(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),S0e=class extends yt()(`effect/http/FetchHttpClient/RequestInit`){},C0e=Zre(rt(Jre((e,t,n,r)=>{let i=r.getRef(x0e),a=r.context.mapUnsafe.get(S0e.key)??{},o=a.headers?En(dn(a.headers),e.headers):e.headers,s=r=>Ze(Fee({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new Zn({reason:new cne({request:e,cause:t})})}),t=>Wte(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return wt(fte(e.body.stream),s)}return s(void 0)}))),w0e=cte.pipe(b,Lt(e=>{if(kn(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=lee(e.reason.response.headers[`retry-after`]).pipe(pte(Nre),m(()=>5));return rt(re(t))}return rt(re(1))})),T0e=Xe(function*(e){let t=yield*Ot(),n=at(t,Mre),r=at(t,Me),a=We(t),o=d(Ne(e.exportInterval),_ee),s,c=Kre(at(t,Bi)).pipe(Vi(Oe(Wi,!1)),Yre({schedule:w0e,times:3})),u=Cn({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(u=En(dn(e.headers),u));let f=Lre(e.url,{headers:u}),p=[],m=At(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return ct;s!==void 0&&(s=void 0);let t=p;if(e.maxBatchSize!==`disabled`){if(p.length===0)return ct;p=[]}return c.execute(Ri(f,e.body(t))).pipe(mee,jee(!1))}).pipe(Ge(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,p=[],kee(`Disabling exporter for 60 seconds`,e)):ct),l({package:`@effect/opentelemetry`,module:e.label}));return yield*Bt(r,m.pipe(Dt,ft,Wee(e.shutdownTimeout))),yield*i(o).pipe(zt(m),et,Nt(r)),{push(t){s===void 0&&(p.push(t),e.maxBatchSize!==`disabled`&&p.length>=e.maxBatchSize&&pe(a(m),r))}}}),E0e=e=>{let t=e.attributes?tQ(Object.entries(e.attributes)):[];return t.push({key:`service.name`,value:{stringValue:e.serviceName}}),e.serviceVersion&&t.push({key:`service.version`,value:{stringValue:e.serviceVersion}}),{attributes:t,droppedAttributesCount:0}},D0e=Xe(function*(e){let t={...yield*Xl(jn(jle(j,j)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*Xl(j,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*Xl(jn(j),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],E0e({serviceName:n,serviceVersion:r,attributes:t})},c),O0e=e=>{let t=e.attributes.find(e=>e.key===`service.name`);if(!t||!t.value.stringValue)throw Error(`Resource does not contain a service name`);return t.value.stringValue},tQ=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:nQ(r)});return t},nQ=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(nQ)}};switch(typeof e){case`string`:return{stringValue:e};case`bigint`:return{intValue:Number(e)};case`number`:return Number.isInteger(e)?{intValue:e}:{doubleValue:e};case`boolean`:return{boolValue:e};default:return{stringValue:Kee(e)}}},rQ=class extends yt()(`effect/observability/OtlpSerialization`){},k0e=he(rQ,{traces:e=>Dn(e),metrics:e=>Dn(e),logs:e=>Dn(e)}),A0e=Xe(function*(e){let t=yield*D0e(e.resource),n=yield*rQ,r={name:O0e(t)},i=yield*T0e({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??re(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??re(3)});function a(e){e.sampled&&i.push(N0e(e))}return xe({span(e){return M0e({...e,status:{_tag:`Started`,startTime:e.startTime},attributes:new Map,export:a})},context:e.context?function(t,n){return n.currentSpan===void 0?t[`~effect/Effect/evaluate`](n):e.context(t,n.currentSpan)}:void 0})}),j0e={_tag:`Span`,end(e,t){this.status={_tag:`Ended`,startTime:this.status.startTime,endTime:e,exit:t},this.export(this)},attribute(e,t){this.attributes.set(e,t)},event(e,t,n){this.events.push([e,t,n])},addLinks(e){this.links.push(...e)}},M0e=e=>{let t=Object.assign(Object.create(j0e),e);return t.traceId=_t(t.parent)?t.parent.value.traceId:iQ(32),t.spanId=iQ(16),t.events=[],t},iQ=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},N0e=e=>{let t=e.status,n=tQ(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?tQ(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=F0e;else if(dt(t.exit.cause))i={code:aQ.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=lte(t.exit.cause);if(i={code:aQ.Error},e.length>0){i.message=e[0].message;for(let n of e)r.push({name:`exception`,timeUnixNano:String(t.endTime),droppedAttributesCount:0,attributes:[{key:`exception.type`,value:{stringValue:n.name}},{key:`exception.message`,value:{stringValue:n.message}},{key:`exception.stacktrace`,value:{stringValue:n.stack??`No stack trace available`}}]})}}return{traceId:e.traceId,spanId:e.spanId,parentSpanId:we(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:P0e[e.kind],startTimeUnixNano:String(t.startTime),endTimeUnixNano:String(t.endTime),attributes:n,droppedAttributesCount:0,events:r,droppedEventsCount:0,status:i,links:e.links.map(e=>({traceId:e.span.traceId,spanId:e.span.spanId,attributes:tQ(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},aQ={Unset:0,Ok:1,Error:2},P0e={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},F0e={code:aQ.Ok},I0e=1e4,L0e={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":Pr?`electron`:`browser`,"service.version":dl}},R0e=De(C0e,k0e,he(Ui,()=>!0)),oQ=null,sQ=null,cQ=null,lQ=null,uQ=0,dQ=Promise.resolve(),z0e=he(Hee,xe({span(e){return oQ?.span(e)??new s(e)}}));function B0e(e={}){return e.exportIntervalMs===void 0&&lQ!==null||(dQ=dQ.finally(()=>V0e(e))),dQ}async function V0e(e){let t=or(`/api/observability/v1/traces`),n=mr()?.bearerToken,r=Math.max(10,e.exportIntervalMs??I0e),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(lQ===i&&oQ!==null)return;lQ=i;let a=++uQ,o=sQ,s=cQ;oQ=null,sQ=null,cQ=null,await fQ(o,s);let c=rl(R0e),l=c.runSync(ze());try{let e=await c.runPromise(te(l)(A0e({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:L0e})));if(a!==uQ){await fQ(c,l);return}oQ=e,sQ=c,cQ=l}catch(e){await fQ(c,l),a===uQ&&console.warn(`Failed to configure client tracing exporter`,{error:H0e(e),otlpTracesUrl:t})}}async function fQ(e,t){e!==null&&t!==null&&await e.runPromise(He(t,Tt)).catch(()=>void 0).finally(()=>{e.dispose()})}function H0e(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var pQ=15e3,mQ=new Map,hQ=Wt([]).pipe(Ut,Vt(`slow-rpc-ack-requests`));function gQ(e){Ht.set(hQ,[...e])}function _Q(){return Ht.get(hQ)}var vQ=`global`;function U0e(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)}function W0e(e,t,n=vQ){if(!U0e(t))return;xQ(e,n),J0e();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:pQ},a=bQ(n,e),o=setTimeout(()=>{mQ.delete(a),q0e(i)},pQ);mQ.set(a,{request:i,timeoutId:o})}function G0e(e,t=vQ){xQ(e,t);let n=_Q();n.some(n=>n.clientId===t&&n.requestId===e)&&gQ(n.filter(n=>n.clientId!==t||n.requestId!==e))}function yQ(e){for(let[t,n]of mQ)n.request.clientId===e&&(clearTimeout(n.timeoutId),mQ.delete(t));gQ(_Q().filter(t=>t.clientId!==e))}function K0e(){for(let e of mQ.values())clearTimeout(e.timeoutId);mQ.clear(),gQ([])}function bQ(e,t){return`${e}:${t}`}function xQ(e,t){let n=bQ(t,e),r=mQ.get(n);r&&(clearTimeout(r.timeoutId),mQ.delete(n))}function q0e(e){let t=[..._Q(),e];if(t.length<=256){gQ(t);return}gQ(t.slice(-256))}function J0e(){for(;mQ.size>=256;){let e=mQ.keys().next().value;if(e===void 0)return;let t=mQ.get(e);if(!t)return;xQ(t.request.requestId,t.request.clientId)}}function Y0e(){return cr(hQ)}var X0e=ko(Mn),SQ=1;function Z0e(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function CQ(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)throw Error(`Unsupported websocket transport URL protocol: ${t.protocol}`);return t.pathname=`/ws`,t.toString()}function Q0e(){return{onAttempt:Lne,onOpen:One,onError:e=>{Ine(e)},onClose:e=>{kne(e)},trackGlobalConnection:!0}}function $0e(e){let t=Q0e(),n=e?.trackGlobalConnection??!0;return{onAttempt:r=>{n&&t.onAttempt(r),e?.onAttempt?.(r)},onOpen:()=>{n&&t.onOpen(),e?.onOpen?.()},onError:r=>{n&&t.onError(r),e?.onError?.(r)},onClose:r=>{n&&t.onClose(r),e?.onClose?.(r)},trackGlobalConnection:n}}function e2e(e,t){let n=SQ;SQ+=1;let r=$0e(t),i=typeof e==`function`?gt(()=>e()).pipe(Ze(e=>CQ(e)),ite(e=>pt(()=>{r.onError(Z0e(e))})),c):CQ(e),a=he(oa,(e,t)=>{r.onAttempt(e);let n=new globalThis.WebSocket(e,t);return n.addEventListener(`open`,()=>{r.onOpen()},{once:!0}),n.addEventListener(`error`,()=>{r.onError(`Unable to connect to the Forge server WebSocket.`)},{once:!0}),n.addEventListener(`close`,e=>{r.onClose({code:e.code,reason:e.reason})},{once:!0}),n}),o=sa(i).pipe(E(a)),s=Lt(_(10),e=>rt(Ue(Fne(e)??0)));return ht(Mo,Ze(No({retryPolicy:s,retryTransientErrors:!0}),e=>({...e,run:(t,r)=>{let i=`${n}:${String(t)}`;return e.run(t,e=>(e._tag===`Chunk`||e._tag===`Exit`?G0e(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&yQ(i),r(e))).pipe(Je(pt(()=>{yQ(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&W0e(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(E(De(o,Oo)))}var t2e=/^all fibers interrupted without error$/i;function n2e(e){return aG(e)||t2e.test(e.trim())}var r2e=Ue(250),wQ=()=>void 0,TQ=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=Be(Ne(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},i2e=new Set([`OrchestrationGetSnapshotError`]);function a2e(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&i2e.has(t)}function o2e(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?s2e(e):String(e)}function s2e(e){try{return JSON.stringify(e)}catch{let t=e;return[typeof t._tag==`string`?t._tag:void 0,typeof t.message==`string`?t.message:void 0].filter(Boolean).join(`: `)||Object.prototype.toString.call(e)}}var c2e=4e3,l2e=1e4,u2e=500,EQ=class{url;lifecycleHandlers;disposed=!1;hasReportedTransportDisconnect=!1;reconnectChain=Promise.resolve();session;heartbeatTimer=null;heartbeatInFlight=!1;protocol;timing;constructor(e,t,n,r){this.url=e,this.lifecycleHandlers=t,this.protocol=n??null,this.timing={heartbeatIntervalMs:r?.heartbeatIntervalMs??c2e,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??l2e,sessionCloseGraceMs:r?.sessionCloseGraceMs??u2e},this.session=this.createSession(),this.startHeartbeat()}startHeartbeat(){this.heartbeatTimer===null&&(this.heartbeatTimer=setInterval(()=>{if(this.disposed||this.heartbeatInFlight)return;this.heartbeatInFlight=!0;let e=this.session;this.request(e=>e[M.serverHeartbeat]({}),{timeout:this.timing.heartbeatTimeoutMs}).catch(async()=>{this.disposed||e!==this.session||await this.reconnect()}).finally(()=>{this.heartbeatInFlight=!1})},this.timing.heartbeatIntervalMs))}async request(e,t){if(this.disposed)throw Error(`Transport disposed`);let n=this.session,i=await n.clientPromise,a=At(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(Mt({duration:o,orElse:()=>r(new TQ(o))}));return await n.runtime.runPromise(s,{signal:t?.signal})}async requestStream(e,t,n){if(this.disposed)throw Error(`Transport disposed`);let r=this.session,i=this.runStreamOnSession(r,e,t,()=>!0,()=>void 0),a=()=>i.cancel();n?.signal?.aborted&&a(),n?.signal?.addEventListener(`abort`,a,{once:!0});try{await i.completed}catch(e){if(n?.signal?.aborted){let e=Error(`RPC stream request was cancelled.`);throw e.name=`AbortError`,e}throw e}finally{n?.signal?.removeEventListener(`abort`,a)}}subscribe(e,t,n){if(this.disposed)return()=>void 0;let r={active:!0,hasReceivedValue:!1,cancelCurrentStream:wQ},i=Be(Ne(n?.retryDelay??r2e));return this.runSubscriptionLoop(e,t,n,r,i),()=>{r.active=!1,r.cancelCurrentStream()}}async runSubscriptionLoop(e,t,n,r,i){for(;r.active&&!this.disposed;){let a=this.session;try{this.notifyResubscribe(r,n);let i=this.startSubscriptionStream(a,e,t,r);r.cancelCurrentStream=i.cancel,await i.completed,r.cancelCurrentStream=wQ}catch(e){if(r.cancelCurrentStream=wQ,!await this.handleSubscriptionFailure(e,a,r,n,i))return}}}notifyResubscribe(e,t){if(e.hasReceivedValue)try{t?.onResubscribe?.()}catch{}}startSubscriptionStream(e,t,n,r){return this.runStreamOnSession(e,t,n,()=>r.active,()=>{this.hasReportedTransportDisconnect=!1,r.hasReceivedValue=!0})}async handleSubscriptionFailure(e,t,n,r,i){if(!n.active||this.disposed)return!1;if(t!==this.session)return!0;let a=o2e(e);return n2e(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await d2e(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){a2e(e)||gG(e,{route:`ws-subscribe`,reason:`non-transport-error`}),t?.onError?.(e)}async reconnect(){if(this.disposed)throw Error(`Transport disposed`);let e=this.reconnectChain.then(async()=>{if(this.disposed)throw Error(`Transport disposed`);let e=this.session;this.session=this.createSession(),await this.closeSession(e)});this.reconnectChain=e.catch(e=>{gG(e,{route:`ws-reconnect`})}),await e}async dispose(){this.disposed||(this.disposed=!0,this.heartbeatTimer!==null&&this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),await this.closeSession(this.session))}async closeSession(e){let t=e.runtime.runPromise(He(e.clientScope,Tt)),n=!1,r=null,i=new Promise(e=>{r=setTimeout(()=>{n=!0,e()},this.timing.sessionCloseGraceMs)});try{await Promise.race([t,i])}finally{r!==null&&clearTimeout(r),n&&(console.warn(`WebSocket session close exceeded its grace period; forcing disposal`,{graceMs:this.timing.sessionCloseGraceMs}),t.catch(()=>void 0)),await e.runtime.dispose()}}createSession(){let e=this.protocol??{layer:e2e(this.url,this.lifecycleHandlers),makeClient:X0e},t=rl(De(e.layer,z0e)),n=t.runSync(ze());return{runtime:t,clientScope:n,clientPromise:t.runPromise(te(n)(e.makeClient))}}runStreamOnSession(e,t,n,r,i){let a,o,s=new Promise((e,t)=>{a=e,o=t});return{cancel:e.runtime.runCallback(gt(()=>e.clientPromise).pipe(wt(e=>Gee(t(e),e=>pt(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if(ete(e)){a();return}o(Ie(e.cause))}}),completed:s}}};function d2e(e){return new Promise(t=>{setTimeout(t,e)})}var DQ=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,f2e=/^[A-Za-z0-9_-]+$/;function p2e(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+=DQ[o>>>18&63],t+=DQ[o>>>12&63],n+1<e.byteLength&&(t+=DQ[o>>>6&63]),n+2<e.byteLength&&(t+=DQ[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function m2e(e){if(e.length===0||!f2e.test(e))throw Error(`Bulk transfer chunk is not valid base64url data.`);let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Math.floor(t.length*6/8),r=new Uint8Array(n),i=0,a=0,o=0;for(let e of t){let t=DQ.indexOf(e);if(t<0)throw Error(`Bulk transfer chunk is not valid base64url data.`);i=i<<6|t,a+=6,a>=8&&(a-=8,r[o]=i>>>a&255,o+=1)}return r}async function OQ(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=await crypto.subtle.digest(`SHA-256`,t.buffer);return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}async function h2e(e,t){let n=t?.chunkBytes??262144;if(!Number.isSafeInteger(n)||n<1||n>262144)throw Error(`Bulk transfer chunk size must be between 1 and ${Gte}.`);let r=t?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),i=[];for(let t=0;t<e.byteLength;t+=n){let a=e.slice(t,Math.min(t+n,e.byteLength));i.push({kind:`chunk`,transferId:r,offset:t,bytes:a.byteLength,data:p2e(a),sha256:await OQ(a)})}return{totalBytes:e.byteLength,sha256:await OQ(e),chunks:i}}async function g2e(e){let t=m2e(e.data);if(t.byteLength!==e.bytes)throw Error(`Bulk transfer chunk byte count mismatch at offset ${e.offset}: expected ${e.bytes}, received ${t.byteLength}.`);if(await OQ(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function _2e(e){let t=new Map,n=[],r=0;for(let i of e.chunks){let e=t.get(i.offset);if(e!==void 0){if(e.bytes!==i.bytes||e.sha256!==i.sha256||e.data!==i.data)throw Error(`Bulk transfer has a conflicting duplicate chunk at offset ${i.offset}.`);continue}if(i.offset!==r)throw Error(`Bulk transfer chunk offset mismatch: expected ${r}, received ${i.offset}.`);let a=await g2e(i);t.set(i.offset,i),n.push({chunk:i,bytes:a}),r+=a.byteLength}if(r!==e.totalBytes)throw Error(`Bulk transfer total byte count mismatch: expected ${e.totalBytes}, received ${r}.`);let i=new Uint8Array(e.totalBytes);for(let e of n)i.set(e.bytes,e.chunk.offset);if(await OQ(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var kQ=`forge`,v2e=RegExp(`^${kQ}\\/[0-9a-f]{8}$`);function y2e(){return`${kQ}/${fe(_te).replace(/-/g,``).slice(0,8).toLowerCase()}`}function b2e(e){return v2e.test(e.trim().toLowerCase())}function x2e(e){let t=e.trim().replace(/\/+$/g,``).replace(/\.git$/i,``).toLowerCase();if(/^(?:ssh|https?|git):\/\//i.test(t))try{let e=new URL(t),n=e.pathname.split(`/`).filter(e=>e.length>0).join(`/`);if(e.hostname&&n.includes(`/`))return`${e.hostname}/${n}`}catch{return t}let n=/^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(t);return n?.[1]&&n[2]?`${n[1]}/${n[2]}`:t}function S2e(e){let t=e?.trim()??``;if(t.length===0)return null;let n=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(t)?.[1]?.trim()??``;return n.length>0?n:null}function C2e(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`git@`)){let e=t.slice(4),n=e.search(/[:/]/);return n<=0?null:e.slice(0,n).toLowerCase()}try{return new URL(t).hostname.toLowerCase()}catch{return null}}function AQ(e){return`https://${e}`}function w2e(e){return e===`github.com`||e.includes(`github`)}function T2e(e){return e===`gitlab.com`||e.includes(`gitlab`)}function E2e(e){return e===`bitbucket.org`}function D2e(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function O2e(e){let t=C2e(e);if(!t)return null;let n=x2e(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?w2e(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:AQ(t)}:T2e(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:AQ(t)}:E2e(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:AQ(t)}:D2e(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:AQ(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:AQ(t)}:null}var k2e={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function jQ(e,t){return{...e,...t??k2e}}function A2e(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function j2e(e){return{isRepo:e.isRepo,...e.hostingProvider?{hostingProvider:e.hostingProvider}:{},hasOriginRemote:e.hasOriginRemote,isDefaultBranch:e.isDefaultBranch,branch:e.branch,hasWorkingTreeChanges:e.hasWorkingTreeChanges,workingTree:e.workingTree}}function M2e(e,t){switch(t._tag){case`snapshot`:return jQ(t.local,t.remote);case`localUpdated`:return jQ(t.local,e?A2e(e):null);case`remoteUpdated`:return jQ(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:j2e(e),t.remote)}}var N2e=262144,P2e=250;function F2e(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function I2e(e){return new Promise(t=>setTimeout(t,e))}function L2e(e){let t=Ace({controllerId:crypto.randomUUID(),maxPendingWriteBytes:N2e}),n=!1,r=e=>{if(!e.sessionEpoch)throw Error(`Connected Forge runtime does not support epoch-fenced terminal controls.`);t.register({threadId:e.threadId,terminalId:e.terminalId,sessionEpoch:e.sessionEpoch})},i=async e=>{for(;!n;)try{return await e()}catch(e){if(!aG(F2e(e)))throw e;await I2e(P2e)}throw Error(`Terminal control client was disposed before acknowledgement.`)};return{terminal:{open:async t=>{let n=await e.request(e=>e[M.terminalOpen]({...t,terminalId:t.terminalId??`default`}));return r(n),n},write:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,writeBytes:new TextEncoder().encode(n.data).byteLength,execute:t=>i(()=>e.request(e=>e[M.terminalWrite]({...n,terminalId:r,...t})))})},resize:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalResize]({...n,terminalId:r,...t})))})},signal:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalSignal]({...n,terminalId:r,...t})))})},clear:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalClear]({...n,terminalId:r,...t})))})},restart:async n=>{let a=n.terminalId??`default`,o=null;if(await t.enqueue({threadId:n.threadId,terminalId:a,execute:async t=>{o=(await i(()=>e.request(e=>e[M.terminalRestart]({...n,terminalId:a,...t})))).snapshot}}),o===null)throw Error(`Terminal restart completed without a snapshot.`);return r(o),o},close:async n=>{let r=n.terminalId?[n.terminalId]:t.terminalIds(n.threadId);for(let a of r)await t.enqueue({threadId:n.threadId,terminalId:a,execute:t=>i(()=>e.request(e=>e[M.terminalClose]({...n,terminalId:a,...t})))}),t.remove(n.threadId,a)},onEvent:t=>e.subscribe(e=>e[M.subscribeTerminalEvents]({}),e=>{(e.type===`started`||e.type===`restarted`)&&r(e.snapshot),t(e)})},dispose:()=>{n=!0,t.dispose()}}}function R2e(e){return{createUploadUrl:t=>e.request(e=>e[M.attachmentsCreateUploadUrl](t)),delete:t=>e.request(e=>e[M.attachmentsDelete](t))}}async function z2e(e,t){await e.request(e=>e[M.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}var B2e=2e4,V2e=12e4,H2e=3e5;function U2e(e){return e instanceof TQ||aG(e instanceof Error?e.message:String(e))}async function W2e(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?H2e:B2e,r=()=>e.request(e=>e[qn.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!U2e(t))throw t;return await e.reconnect(),await r()}}function MQ(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function NQ(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>G2e(r,e,n),n),r.protocolError!==null)throw r.protocolError;let i=r.started,a=r.completed;if(i===null||a===null)throw Error(`Bulk transfer stream completed without start and completion metadata.`);if(a.transferId!==i.transferId||a.totalBytes!==i.totalBytes||a.sha256!==i.sha256)throw Error(`Bulk transfer completion metadata mismatch.`);return await _2e({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function G2e(e,t,n){if(e.protocolError===null){if(t.kind===`started`){K2e(e,t,n);return}if(e.started===null||t.transferId!==e.started.transferId){e.protocolError=Error(`Bulk transfer event identity mismatch.`);return}if(t.kind===`chunk`){q2e(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function K2e(e,t,n){if(e.started!==null||t.totalBytes>16777216){e.protocolError=Error(`Bulk transfer started with invalid or oversized metadata.`);return}e.started=t,n?.onProgress?.({completedBytes:0,totalBytes:t.totalBytes})}function q2e(e,t,n){let r=e.started;if(r!==null){if(e.receivedBytes+=t.bytes,e.receivedBytes>r.totalBytes){e.protocolError=Error(`Bulk transfer exceeded its declared byte count.`);return}e.chunks.push(t),n?.onProgress?.({completedBytes:e.receivedBytes,totalBytes:r.totalBytes})}}async function J2e(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${Jte}-byte write limit.`);let i=await h2e(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{MQ(n?.signal);let r=await Y2e(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await X2e(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await z2e(e,a),t}}function Y2e(e,t,n,r){return e.request(e=>e[M.workspaceBeginWriteFile]({transferId:n,cwd:t.cwd,relativePath:t.relativePath,totalBytes:r.totalBytes,sha256:r.sha256}))}async function X2e(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;MQ(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[M.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}MQ(i?.signal),await e.request(e=>e[M.workspaceCommitWriteFile]({transferId:t}))}}function PQ(e){let t=L2e(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{wne(),await e.reconnect()},terminal:t.terminal,browser:{openSession:t=>e.request(e=>e[M.browserOpenSession](t)),listSessions:t=>e.request(e=>e[M.browserListSessions](t)),closeSession:t=>e.request(e=>e[M.browserCloseSession](t)),getSession:t=>e.request(e=>e[M.browserGetSession](t)),command:t=>e.request(e=>e[M.browserCommand](t)),clearBrowsingData:t=>e.request(e=>e[M.browserClearBrowsingData](t)),attachDisplay:t=>e.request(e=>e[M.browserAttachDisplay](t)),addDisplayIceCandidate:t=>e.request(e=>e[M.browserAddDisplayIceCandidate](t)),onEvent:(t,n,r)=>e.subscribe(e=>e[M.subscribeBrowserEvents](t),n,r)},computer:{input:t=>e.request(e=>e[M.computerInput](t))},threadDevRuntime:{get:t=>e.request(e=>e[M.threadDevRuntimeGet](t)),allocatePort:t=>e.request(e=>e[M.threadDevRuntimeAllocatePort](t)),release:t=>e.request(e=>e[M.threadDevRuntimeRelease](t))},devTunnel:{register:t=>e.request(e=>e[M.devTunnelRegister](t)),unregister:t=>e.request(e=>e[M.devTunnelUnregister](t)),list:t=>e.request(e=>e[M.devTunnelList](t))},attachments:R2e(e),projects:{searchContents:(t,n)=>e.request(e=>e[M.projectsSearchContents](t),n),searchEntries:t=>e.request(e=>e[M.projectsSearchEntries](t)),readFile:(t,n)=>NQ(e,e=>e[M.workspaceReadFile](t),n),writeFile:(t,n)=>J2e(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[M.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[M.projectCheckoutDeletionExecute](t))},workspace:{environmentPreflight:t=>e.request(e=>e[M.workspaceEnvironmentPreflight](t)),ensureScratch:t=>e.request(e=>e[M.workspaceEnsureScratch](t))},shell:{openInEditor:t=>e.request(e=>e[M.shellOpenInEditor](t))},git:{pull:t=>e.request(e=>e[M.gitPull](t)),refreshStatus:t=>e.request(e=>e[M.gitRefreshStatus](t)),onStatus:(t,n,r)=>{let i=null;return e.subscribe(e=>e[M.subscribeGitStatus](t),e=>{i=M2e(i,e),n(i)},r)},runStackedAction:async(t,n)=>{let r=null;if(await e.requestStream(e=>e[M.gitRunStackedAction](t),e=>{n?.onProgress?.(e),e.kind===`action_finished`&&(r=e.result)}),r)return r;throw Error(`Git action stream completed without a final result.`)},listBranches:t=>e.request(e=>e[M.gitListBranches](t)),createWorktree:t=>e.request(e=>e[M.gitCreateWorktree](t)),removeWorktree:t=>e.request(e=>e[M.gitRemoveWorktree](t)),createBranch:t=>e.request(e=>e[M.gitCreateBranch](t)),checkout:t=>e.request(e=>e[M.gitCheckout](t)),init:t=>e.request(e=>e[M.gitInit](t)),resolvePullRequest:t=>e.request(e=>e[M.gitResolvePullRequest](t)),preparePullRequestThread:t=>e.request(e=>e[M.gitPreparePullRequestThread](t))},pullRequests:{list:t=>e.request(e=>e[M.pullRequestsList](t)),listStats:t=>e.request(e=>e[M.pullRequestsListStats](t)),detail:t=>e.request(e=>e[M.pullRequestsDetail](t)),activity:t=>e.request(e=>e[M.pullRequestsActivity](t)),threadComments:t=>e.request(e=>e[M.pullRequestsThreadComments](t)),diffFileContents:t=>e.request(e=>e[M.pullRequestsDiffFileContents](t)),runAction:t=>e.request(e=>e[M.pullRequestsRunAction](t)),update:t=>e.request(e=>e[M.pullRequestsUpdate](t)),comment:t=>e.request(e=>e[M.pullRequestsComment](t)),updateComment:t=>e.request(e=>e[M.pullRequestsUpdateComment](t)),submitReview:t=>e.request(e=>e[M.pullRequestsSubmitReview](t)),replyToThread:t=>e.request(e=>e[M.pullRequestsReplyToThread](t)),setThreadResolution:t=>e.request(e=>e[M.pullRequestsSetThreadResolution](t)),setReaction:t=>e.request(e=>e[M.pullRequestsSetReaction](t)),invalidate:t=>e.request(e=>e[M.pullRequestsInvalidate](t)),reviewerCandidates:t=>e.request(e=>e[M.pullRequestsReviewerCandidates](t)),requestReviewers:t=>e.request(e=>e[M.pullRequestsRequestReviewers](t))},server:{getConfig:()=>e.request(e=>e[M.serverGetConfig]({})),refreshProviders:()=>e.request(e=>e[M.serverRefreshProviders]({})),startProviderAuth:t=>e.request(e=>e[M.serverStartProviderAuth](t)),repairProviderAuthRuntime:t=>e.request(e=>e[M.serverRepairProviderAuthRuntime](t)),disconnectProviderAuth:t=>e.request(e=>e[M.serverDisconnectProviderAuth](t)),getProviderAuthSession:t=>e.request(e=>e[M.serverGetProviderAuthSession](t)),cancelProviderAuth:t=>e.request(e=>e[M.serverCancelProviderAuth](t)),submitProviderAuthCode:t=>e.request(e=>e[M.serverSubmitProviderAuthCode](t)),syncPersonalCodexToCloud:t=>e.request(e=>e[M.serverSyncPersonalCodexToCloud](t)),syncPersonalClaudeToCloud:t=>e.request(e=>e[M.serverSyncPersonalClaudeToCloud](t)),upsertKeybinding:t=>e.request(e=>e[M.serverUpsertKeybinding](t)),removeKeybinding:t=>e.request(e=>e[M.serverRemoveKeybinding](t)),getSettings:()=>e.request(e=>e[M.serverGetSettings]({})),updateSettings:t=>e.request(e=>e[M.serverUpdateSettings]({patch:t})),updateEnvironmentDisplayName:t=>e.request(e=>e[M.serverUpdateEnvironmentDisplayName](t)),getTraceDiagnostics:t=>e.request(e=>e[M.serverGetTraceDiagnostics](t)),subscribeConfig:(t,n)=>e.subscribe(e=>e[M.subscribeServerConfig]({}),t,n),subscribeLifecycle:(t,n)=>e.subscribe(e=>e[M.subscribeServerLifecycle]({}),t,n),subscribeAuthAccess:(t,n)=>e.subscribe(e=>e[M.subscribeAuthAccess]({}),t,n),subscribeWorkspaceReadiness:(t,n)=>e.subscribe(e=>e[M.subscribeWorkspaceReadiness]({}),t,n)},usage:{getSummary:t=>e.request(e=>e[M.usageGetSummary](t),{timeout:V2e})},orchestration:{dispatchCommand:t=>W2e(e,t),getTurnDiff:(t,n)=>NQ(e,e=>e[qn.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>NQ(e,e=>e[qn.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[qn.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[qn.subscribeThread](t),n,r)}}}var Z2e=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function FQ(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!Z2e.has(t)?null:t}function IQ(e,t){return e===401||e===403||FQ(t)!==null}function Q2e(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return IQ(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}var LQ=`forge.deviceRegistry.deviceKey`,RQ=`forge.deviceRegistry.runtimeId`;function $2e(e){let t=VQ(LQ,e.desktopIdentity?.deviceKey,`device`),n=VQ(RQ,e.desktopIdentity?.runtimeId,`runtime`),r=BQ(e.desktopIdentity?.hostKey),i=r4e(),a=e.desktopAvailable?`desktop`:i4e(),o=e.desktopAvailable?n4e(e.desktopIdentity)??a4e(i):o4e(i);return{device:{...r?{hostKey:r}:{},deviceKey:t,displayName:o,platform:i,deviceType:a,metadata:{clientKind:e.desktopAvailable?`forge-desktop`:`forge-web`,userAgent:window.navigator.userAgent,origin:window.location.origin,...e.desktopIdentity?{desktopIdentity:{hostName:e.desktopIdentity.hostName,computerName:e.desktopIdentity.computerName,platform:e.desktopIdentity.platform}}:{}}},...e.desktopAvailable&&e.includeExecutableRuntime!==!1?{runtime:{runtimeId:n,runtimeKind:`desktop-local`,displayName:`Local Forge Desktop`,endpointUrl:e.desktopEndpointUrl??null,status:`online`,metadata:{origin:window.location.origin}}}:{}}}async function zQ(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return $2e({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function BQ(e){let t=e?.trim()??``;return t.length>0?t:null}function VQ(e,t,n){let r=BQ(t);return r?(FJ(e,r),r):t4e(e,n)}function e4e(){return PJ(RQ)}function HQ(){return PJ(LQ)}function t4e(e,t){let n=PJ(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return FJ(e,r),r}function n4e(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function r4e(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`iphone`)||e.includes(`ipad`)?`ios`:e.includes(`android`)?`android`:e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:`unknown`}function i4e(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`ipad`)||e.includes(`tablet`)?`tablet`:e.includes(`mobi`)||e.includes(`iphone`)||e.includes(`android`)?`mobile`:`browser`}function a4e(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function o4e(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var UQ=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function WQ(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new UQ(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new UQ(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function s4e(e){let t=e.getStoredDeviceKey(),n=t?await e.apiClient.getDeviceRegistry():await e.apiClient.registerDevice(await e.buildDeviceRegistration());return t&&!n.devices.some(e=>e.deviceKey===t)&&(n=await e.apiClient.registerDevice(await e.buildDeviceRegistration())),t??=e.getStoredDeviceKey(),{deviceKey:t,registry:n}}function c4e(e){if(!e.deviceKey)throw new UQ(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface could not establish CMMD identity.`);let t=e.registry.devices.find(t=>t.deviceKey===e.deviceKey);if(t?.trustState===`revoked`||t?.authorization?.revoked===!0)throw new UQ(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new UQ(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function l4e(e,t){let n=async()=>c4e(await s4e(t));return{acquireRoute:async()=>{let r=await n(),i=await Dce();try{return kce({route:await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Un],protocolMinVersion:4,protocolMaxVersion:4,...Oce(i)}),runtimeId:e,endpoint:i})}catch(e){if(e instanceof tl)throw new UQ(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return WQ(e)}},acquireActionGrant:async r=>{let i=await n();try{return(await t.apiClient.issueRelayActionGrant(e,{controlDeviceId:i.id,controlSessionId:t.controlSessionId,...r})).token}catch(e){return WQ(e)}}}}var GQ=`forge.relayControlJournal.v1`;function KQ(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var u4e={read:()=>KQ().getItem(GQ),write:e=>KQ().setItem(GQ,e)},qQ=null,JQ=Xt()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function d4e(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));JQ.getState().replace(Object.fromEntries([...t].map(t=>[t,Vse(e.records,t)])))})}function YQ(){return qQ===null&&(qQ=zc({storage:u4e}),d4e(qQ)),qQ}function f4e(){let e=(0,cl.c)(1),t=JQ(m4e),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,F.useEffect)(p4e,n),t}function p4e(){YQ()}function m4e(e){return e.byRuntimeId}function h4e(e){let t=YQ();for(let n of t.records())n.runtimeId===e&&(n.status===`failed`||n.status===`outcome-unknown`)&&t.acknowledge(n.runtimeId,n.actorSessionId,n.transportRequestId)}var g4e=12e4,_4e=3e4,XQ=3e4;function ZQ(e){let t=e.expiresAt?Date.parse(e.expiresAt):NaN;if(!Number.isFinite(t))throw Error(`Cloud runtime authority descriptor has no valid expiry.`);return t}function v4e(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function y4e(e){let t=e.now??Date.now,n=e.renewalSkewMs??g4e,r=!1,i=null,a=null,o=ZQ(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=ZQ(a);o=c;let l=Math.max(t(),c-n);e.onState?.({kind:`scheduled`,expiresAt:new Date(c).toISOString(),renewAt:new Date(l).toISOString()}),i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},Math.max(0,l-t()))},l=()=>{if(r)return null;let e=t()+XQ;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},XQ),new Date(e).toISOString())},u=()=>{if(r)return Promise.resolve();if(a)return a;s(),e.onState?.({kind:`renewing`,expiresAt:new Date(o).toISOString()});let n=e.renew().then(async n=>{let i=ZQ(n);if(i<=t())throw Error(`Cloud runtime authority descriptor is already expired.`);r||(e.onState?.({kind:`ready`,expiresAt:new Date(i).toISOString(),renewedAt:new Date(t()).toISOString()}),c(n))}).catch(t=>{if(r)return;let n=v4e(t);throw e.onState?.({kind:`error`,code:n?`authority_auth_rejected`:`authority_renewal_failed`,retryAt:n?null:l()}),t}).finally(()=>{a=null});return a=n,n};return c(e.initialDescriptor),{ensureLive:()=>o>t()+_4e?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}var QQ=new Map;function $Q(e,t){return e.acquire(t?{signal:t}:{})}function b4e(e,t){QQ.set(e,t)}function x4e(e){return QQ.has(e)}function e$(e,t){let n=QQ.get(e);t&&n!==t||(n?.dispose(),QQ.delete(e))}async function S4e(e){let t=QQ.get(e);if(t)return(await t.acquire()).bearerToken;let n=GK(e);return n&&GX(n)?null:XK(e)}function C4e(e){switch(e){case`running`:return`green`;case`provisioning`:case`starting`:return`amber-pulse`;case`registered`:return`idle`;case`stopped`:case`suspended`:case`draining`:return`grey`;case`destroyed`:return`idle`;case`error`:return`red-pulse`;default:return`grey`}}function t$(e){let t=e.githubRepoFullName;return t?t.split(`/`)[1]??t:w4e(e.projectName)}function w4e(e){let t=e.trim().toLowerCase().replaceAll(`'`,``).replaceAll(`"`,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:`project`}function n$(e){if(!e)return null;let t=e.trim().replace(/\/+$/,``);return t.length>0?t:null}function r$(e){let t=n$(e??void 0);return t&&i$(t).length>1?t:null}function i$(e){return e.split(`/`).flatMap(e=>e.split(`\\`)).filter(e=>e.length>0)}function a$(e){return e?i$(e).at(-1)??null:null}function T4e(e){let t=e.rows.length>0;return(e.isLoading||e.startupPhase===`auth-refreshing`)&&!t?{kind:`loading`}:e.error&&!t?{kind:`error-no-rows`,message:e.error}:e.error&&t?{kind:`stale-rows`,message:e.error}:t?{kind:`rows`}:{kind:`empty`}}function E4e(e,t){if(!t)return!1;let n=e.repositoryIdentity?.canonicalKey;return n!==void 0&&!n.toLowerCase().endsWith(`/${t.toLowerCase()}`)}function D4e(e,t){return e?e.cmmdOrganizationId===t.cmmdOrganizationId&&e.cmmdProjectId===t.cmmdProjectId:!1}function O4e(e,t){let n=e.filter(e=>!e.cmmdRegistration),r=r$(t.workspaceRoot),i=r?n.filter(e=>n$(e.cwd)===r):[];if(i.length>0)return i;let a=t$(t).toLowerCase();return n.filter(e=>a$(e.cwd)?.toLowerCase()===a)}function o$(e,t,n){let r=e[t];if(!r)return null;let i=r.projectIds.flatMap(e=>{let t=r.projectById[e];return!t||E4e(t,n.githubRepoFullName)?[]:[t]}),a=i.filter(e=>D4e(e.cmmdRegistration,n)),o=a.length>0?a:O4e(i,n),s=o.length===1?o[0]:void 0;return s?{environmentId:t,projectId:s.id}:null}function k4e(e){return{cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,githubRepoFullName:e.githubRepoFullName,projectName:e.projectName,workspaceRoot:e.workspaceRoot}}function A4e(e,t){let n=e.cmmdEnvironmentId??e.environmentId;if(e.runtimeId===null||n===null)return null;let r=o$(t,an.make(n),k4e(e));return r?Io(r.environmentId,r.projectId):null}function j4e(e,t){return e===t?!0:e===null||t===null?!1:e.environmentId===t.environmentId&&e.projectId===t.projectId}function M4e(e,t){let n=!1,r=e.map(e=>{let r=A4e(e,t);return j4e(r,e.resolvedRef)?e:(n=!0,{...e,resolvedRef:r})});return n?r:e}var s$=`registered`,N4e={destroyed:`destroyed`,superseded:`destroyed`,error:`error`,failed:`error`,draining:`draining`,recycling:`draining`,stopped:`stopped`,suspended:`suspended`,provisioning:`provisioning`,created:`provisioning`,starting:`starting`,restarting:`starting`};function c$(e,t){let n=N4e[e];if(n!==void 0)return n;if(e!==`running`)return`stopped`;if(t)switch(t){case`app_ready`:case`server_ready`:case`ready`:case`supervisor_up`:return`running`;case`starting`:case`image_pulling`:case`waiting_state`:return`starting`;case`error`:return`error`;default:return`running`}return`running`}function P4e(e){return e===`destroyed`}function F4e(e){switch(e){case`running`:case`starting`:case`provisioning`:return!0;case`suspended`:return!0;case`registered`:case`stopped`:case`draining`:case`error`:case`destroyed`:return!1;default:return!1}}function I4e(e){let t=e.shortName?.trim();if(t)return t;if(e.projectName)return e.projectName;if(e.githubRepoFullName){let t=e.githubRepoFullName.split(`/`),n=t[t.length-1];if(n)return n}return`project ${e.cmmdProjectId}`}var l$={state:`unknown`,label:`Unknown`,detail:`Current Environment availability has not been observed.`,tone:`muted`,automaticWakeAllowed:!1,shellConnected:!1,shellMayEstablishReady:!1};function u$(e,t,n,r,i,a,o=!1){return{state:e,label:t,detail:n,tone:r,automaticWakeAllowed:i,shellConnected:a,shellMayEstablishReady:o}}function L4e(e,t){return e.ownerIntent===`paused`?u$(`paused`,`Paused`,`Resume before live work can wake this Environment.`,`warning`,!1,t):e.ownerIntent===`deleting`?u$(`deleting`,`Deleting`,`This Environment is being removed.`,`muted`,!1,t):null}function R4e(e,t){return e.executionAdmission.state===`allowed`?null:u$(`unavailable`,`Unavailable`,`This Environment is not accepting live work while it drains.`,`warning`,!1,t)}function d$(e,t=!1){if(e==null)return l$;let n=L4e(e,t);if(n!==null)return n;if(e.ownerIntent!==`active`)return l$;let r=R4e(e,t);if(r!==null)return r;let{provider:i,guestReadiness:a,activeWork:o}=e;return i.observedAt===null||i.failure!==null||i.state===`absent`||i.state===`unknown`?u$(`unknown`,`Unknown`,`Current provider availability has not been observed.`,`muted`,e.automaticWakeAllowed,t):i.state===`sleeping`?u$(`sleeping`,`Sleeping`,`Live work wakes this Environment automatically.`,`muted`,e.automaticWakeAllowed,t):a.observedAt===null||a.failure!==null||a.state===`unknown`?u$(`unknown`,`Unknown`,`Current guest readiness has not been observed.`,`muted`,e.automaticWakeAllowed,t):a.state===`starting`?u$(`starting`,`Starting`,`Preparing live execution.`,`warning`,e.automaticWakeAllowed,t):a.state===`degraded`?u$(`degraded`,`Degraded`,`A required service needs attention.`,`warning`,e.automaticWakeAllowed,t):a.state===`failed`?u$(`needs-attention`,`Needs attention`,`The readiness check failed.`,`destructive`,e.automaticWakeAllowed,t):t?u$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,!0):o.state===`active`?u$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,t):u$(`unknown`,`Unknown`,`No current execution proof is available.`,`muted`,e.automaticWakeAllowed,t,!0)}function z4e(e,t){return!t||!e.shellMayEstablishReady?e:u$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,!0)}function f$(e){return e?c$(e.status,e.readinessPhase??void 0):s$}function B4e(e){return e.runtime?.githubRepoFullName??e.githubRepoFullName??null}function V4e(e,t){return{cmmdOrganizationId:e.organizationId,cmmdProjectId:e.projectId,projectName:I4e({shortName:e.shortName??null,projectName:e.projectName??null,githubRepoFullName:t,cmmdProjectId:e.projectId}),githubRepoFullName:t,iconUrl:e.iconUrl??null,icon:e.icon??null}}function H4e(e){return e?{runtimeId:e.runtimeId,workspaceRoot:e.workspaceRoot??null,status:f$(e),desiredState:p$(e.desiredState),environmentId:Tl(e.runtimeId),cmmdEnvironmentId:e.environmentId??null,...e.maintenance===void 0?{}:{maintenance:e.maintenance}}:{runtimeId:null,workspaceRoot:null,status:s$,desiredState:null,environmentId:null,cmmdEnvironmentId:null}}function p$(e){return e===`running`||e===`stopped`||e===`destroyed`?e:null}function U4e(e){return{...V4e(e,B4e(e)),registeredAt:e.registeredAt??null,...H4e(e.runtime),removal:e.removal??null,resolvedRef:null}}function W4e(e){return e.map(U4e)}function G4e(e){return e.map(e=>({runtimeId:e.runtime.runtimeId,cmmdOrganizationId:e.organizationId,cmmdUserId:e.userId,displayName:e.displayName??null,userFirstName:e.userFirstName??null,environmentId:Tl(e.runtime.runtimeId),cmmdEnvironmentId:e.runtime.environmentId??null,status:f$(e.runtime),desiredState:p$(e.runtime.desiredState),...e.runtime.maintenance===void 0?{}:{maintenance:e.runtime.maintenance},lifecycle:d$(e.lifecycle)}))}var m$=`forge:cmmd-cloud-project-catalog:v5`,K4e=nr({runtimeId:Kn(j),cmmdOrganizationId:Ln,cmmdProjectId:Ln,cmmdEnvironmentId:Kn(j),registeredAt:yn(Kn(j)),projectName:j,githubRepoFullName:Kn(j),workspaceRoot:Kn(j),iconUrl:yn(Kn(j)),icon:yn(Kn(j)),status:j,desiredState:yn(Kn(j)),environmentId:Kn(j),removal:yn(Kn(nr({operationId:j,deletePlanningProject:Xn,status:Fn([`pending`,`running`,`retryable`]),phase:Fn([`destroy_runtime`,`purge_execution_state`,`delete_planning_project`,`unregister`,`complete`]),lastErrorCode:Kn(j),lastErrorMessage:Kn(j),updatedAt:j})))}),h$=nr({rows:Jn(K4e),environments:Jn(nr({runtimeId:j,cmmdOrganizationId:Ln,cmmdUserId:Ln,displayName:yn(Kn(j)),userFirstName:yn(Kn(j)),environmentId:j,cmmdEnvironmentId:Kn(j),status:j,desiredState:Kn(j)})),fetchedAt:j});function q4e(){try{let e=yl(m$,h$);return e?{rows:e.rows.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,registeredAt:e.registeredAt??null,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl??null,icon:e.icon??null,status:e.runtimeId===null?s$:c$(e.status),desiredState:p$(e.desiredState),environmentId:e.runtimeId===null?null:Tl(e.runtimeId),cmmdEnvironmentId:e.cmmdEnvironmentId,resolvedRef:null,removal:e.removal??null})),environments:e.environments.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdUserId:e.cmmdUserId,displayName:e.displayName??null,userFirstName:e.userFirstName??null,cmmdEnvironmentId:e.cmmdEnvironmentId,status:c$(e.status),desiredState:p$(e.desiredState),environmentId:Tl(e.runtimeId)})),fetchedAt:e.fetchedAt}:null}catch{return null}}function J4e(e,t,n){try{bl(m$,{rows:e.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,environmentId:e.environmentId,removal:e.removal})),environments:t,fetchedAt:n},h$)}catch{}}var g$=1e3;function Y4e(e){return e.reconnectPhase===`idle`?`hidden`:e.reconnectPhase===`exhausted`?`actionable`:!e.hasConnected||!e.stableConnectionSeen?`startup-pending`:`actionable`}function _$(e){let t=e.maxAttempts??2,n=e.retryDelayMs??1e3;return e.failedAttempt<t?{kind:`retry`,delayMs:n,nextAttempt:e.failedAttempt+1}:{kind:`terminal`,attempt:e.failedAttempt}}var X4e=`auth-required`,Z4e=`cloud-projects`;async function Q4e(e,t,n){let r=null,i=new PK(e).listCloudProjects({signal:t.signal}).then(e=>({kind:`catalog`,catalog:e})).catch(e=>({kind:`failed`,error:e})),a=new Promise(e=>{r=setTimeout(()=>{t.abort(),e({kind:`timed-out`})},n)});try{return await Promise.race([i,a])}finally{r!==null&&clearTimeout(r)}}function $4e(e){let t=e.accessToken??e.resolveAccessToken?.(),n={Accept:`text/event-stream`};return t&&(n.Authorization=`Bearer ${t}`),n}function e3e(e,t){let n=new URL(e);return n.pathname=t,n.search=``,n.hash=``,n.toString()}async function t3e(e){return(e.status===401||e.status===403)&&(await a3e(e)||e.status===401)?`auth-required`:e.status===404||e.status===405||!e.ok||!e.body?`fallback`:e.body.getReader()}async function n3e({reader:e,signal:t,onAuthRequired:n,onCatalog:r}){let i=new TextDecoder,a=``;try{for(;!t.aborted;){let{done:o,value:s}=await e.read();if(t.aborted||o)return;let c=r3e(a,i.decode(s,{stream:!0}));if(a=c.buffer,c.messages.some(e=>i3e(e,n,r)))return}}finally{e.releaseLock()}}function r3e(e,t){let n=`${e}${t}`.split(/\n\n/);return{buffer:n.pop()??``,messages:n}}function i3e(e,t,n){let r=s3e(e);if(r.name===X4e)return t(),!0;let i=r.name===Z4e?o3e(r.data):null;return i&&n(i),!1}async function a3e(e){try{let t=await e.clone().json();return typeof t?.code==`string`&&t.code===`CMMD_AUTH_REQUIRED`}catch{return!1}}function o3e(e){try{return OK(JSON.parse(e))}catch{return null}}function s3e(e){let t=``,n=``;for(let r of e.split(`
1020
- `))r.startsWith(`event: `)&&(t=r.slice(7).trim()),r.startsWith(`data: `)&&(n=r.slice(6).trim());return{name:t,data:n}}var c3e=`/api/cmmd/forge-cloud-projects`,l3e=`/api/cmmd/forge-cloud-projects/events`,u3e=15e3,d3e=3e4,f3e=2e3,p3e=3e4,m3e=200;function h3e({config:e,onEvent:t}){let n=!1,r=!1,i=!1,a=!1,o=!1,s=0,c=null,l=0,u=null,d=null,f=0,p=null,m=null,h=null,g=null;function _(e){return e!==null&&clearTimeout(e),null}function v(){p=_(p),g=_(g)}function y(){f+=1,d?.controller.abort(),d=null}function b(e,t){return d?.controller===e&&d.generation===t&&f===t}function x(e){return u===e}function S(){y(),u?.abort(),u=null,v(),h=_(h)}function C(){return!r&&!a}function w(e){t({kind:`catalog`,catalog:e,fetchedAt:new Date().toISOString()})}function T(e){a||r||(a=!0,c=null,S(),t({kind:`auth-required`,message:e}))}function E(e,n){if(r||a)return;s+=1,c=n;let i=_$({failedAttempt:s,retryDelayMs:g$});if(i.kind===`terminal`){T(e);return}u?.abort(),u=null,g=_(g),t({kind:`auth-refreshing`}),o=!0,h=_(h),h=setTimeout(()=>{h=null,o=!1,pe()},i.delayMs)}async function D(){if(!C())return!1;let n=new AbortController,r=++f;d={controller:n,generation:r},t({kind:`loading`});try{return ee(await Q4e(e,n,u3e),n,r)}finally{b(n,r)&&(d=null)}}function ee(e,t,n){return!C()||!b(t,n)?!1:e.kind===`catalog`?te(e.catalog):e.kind===`timed-out`?ne():O(e.error)}function te(e){return c!==`sse`&&(s=0,c=null),o=!1,w(e),!0}function ne(){return t({kind:`failed`,message:`Cloud connection refresh timed out. Showing last known connections.`}),!a}function O(e){let n=e instanceof Error?e.message:`Failed to load cloud projects`;return ZG(e)||g3e(e)||/authentication required/i.test(n)?E(n,`list`):t({kind:`failed`,message:n}),!a}function k(){C()&&(p=_(p),p=setTimeout(async()=>{await D(),C()&&k()},d3e))}function re(){!C()||o||(i?k():ae(l))}function A(e){l=e+1;let t=Math.min(f3e*2**e,p3e);g=_(g),g=setTimeout(()=>{g=null,ae(l)},t)}function ie(e){s=0,c=null,l=0,w(e)}async function ae(t){if(!C()||u!==null)return;u=new AbortController;let n=u,r=e.eventsUrl??e3e(e.cmmdHttpBaseUrl,`/api/forge/context/runtimes/events`),i=e.eventsUrl?{Accept:`text/event-stream`}:$4e(e);try{await oe(await fetch(r,{headers:i,signal:n.signal,credentials:`include`}),n,t)}catch{de(n)}}async function oe(e,t,n){if(!se(t))return;let r=await t3e(e);if(se(t)){if(typeof r==`string`){ue(r);return}await n3e({reader:r,signal:t.signal,onAuthRequired:()=>ce(t),onCatalog:e=>le(t,e)}),fe(t,n)}}function se(e){return C()&&x(e)}function ce(e){se(e)&&E(`CMMD authentication required. Sign in again to continue.`,`sse`)}function le(e,t){se(e)&&ie(t)}function ue(e){if(u=null,e===`auth-required`){E(`CMMD authentication required. Sign in again to continue.`,`sse`);return}i=!0,k()}function de(e){e.signal.aborted||!se(e)||(u=null,i=!0,k())}function fe(e,t){e.signal.aborted||!se(e)||(u=null,A(t))}function pe(){return D().then(e=>{e&&C()&&re()})}return{initialize(){n||r||(n=!0,pe())},refresh(){r||(y(),m=_(m),m=setTimeout(()=>{m=null,a=!1,o=!1,s=0,c=null,S(),pe()},m3e))},teardown(){r=!0,m=_(m),S()}}}function g3e(e){return typeof e==`object`&&!!e&&`kind`in e&&e.kind===`auth`}var v$={connected:!1,isLoading:!1,error:null,rows:[],environments:[],fetchedAt:null,stale:!1,startupPhase:`idle`,capacity:null};function _3e({config:e}){let t=q4e(),n=t?{...v$,isLoading:!0,rows:t.rows,environments:t.environments,fetchedAt:t.fetchedAt,stale:!0}:v$,r=new Set;function i(e){n=e;for(let e of r)e()}function a(e){switch(e.kind){case`loading`:i({...n,isLoading:!0,error:null});return;case`catalog`:{let t=W4e(e.catalog.listRowsForDisplay()),n=G4e(e.catalog.listEnvironmentsForDisplay());J4e(t,n,e.fetchedAt),i({connected:!0,isLoading:!1,error:null,rows:t,environments:n,fetchedAt:e.fetchedAt,stale:!1,startupPhase:`idle`,capacity:e.catalog.capacity});return}case`failed`:i({...n,connected:!1,isLoading:!1,error:e.message,stale:n.rows.length>0,startupPhase:`idle`});return;case`auth-refreshing`:i({...n,connected:!1,isLoading:!0,error:null,stale:n.rows.length>0,startupPhase:`auth-refreshing`});return;case`auth-required`:i({...n,connected:!1,isLoading:!1,error:e.message,stale:n.rows.length>0,startupPhase:`idle`}),dr(`cmmd-runtimes`);return}}let o=h3e({config:e,onEvent:a});return{subscribe(e){return r.add(e),()=>r.delete(e)},read(){return n},initialize(){o.initialize()},refresh(){o.refresh()},_teardown(){o.teardown()},_setState(e){i(e)}}}var y$=null;function b$(e){return typeof window<`u`&&window.location?.href?new URL(e,window.location.href).toString():new URL(e,`http://localhost`).toString()}function x$(){return{cmmdHttpBaseUrl:`https://cmmd.ai`,resolveAccessToken:()=>null,listUrl:c3e,eventsUrl:l3e,destroyUrl:e=>b$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/destroy`),lifecycleUrl:(e,t)=>b$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/${t}`),updateCommitUrl:e=>b$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/update-commit`),updateCommitOperationUrl:(e,t)=>b$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/update-commit/${encodeURIComponent(String(t))}`),ensureUrl:b$(`/api/cmmd/forge-runtimes/ensure`)}}function S$(){return y$===null&&(y$=_3e({config:x$()})),y$}function v3e(){S$().refresh()}function y3e(e){return S$().subscribe(e)}function C$(){return S$().read()}function b3e(e){let t=(0,cl.c)(9),n=e?.enabled??!0,r,i;t[0]===n?(r=t[1],i=t[2]):(r=()=>{n&&S$().initialize()},i=[n],t[0]=n,t[1]=r,t[2]=i),(0,F.useEffect)(r,i);let a=(0,F.useSyncExternalStore)(y3e,C$,C$),o=oJ(x3e),s,c;t[3]!==o||t[4]!==a.rows?(c=M4e(a.rows,o),t[3]=o,t[4]=a.rows,t[5]=c):c=t[5],s=c;let l=s,u;return t[6]!==l||t[7]!==a?(u=l===a.rows?a:{...a,rows:l},t[6]=l,t[7]=a,t[8]=u):u=t[8],u}function x3e(e){return e.environmentStateById}var S3e=`forge:cloud-runtime-handoffs:v2`,C3e=3e5,w$=new Map,w3e={clear:()=>w$.clear(),getItem:e=>w$.get(e)??null,key:e=>Array.from(w$.keys())[e]??null,get length(){return w$.size},removeItem:e=>w$.delete(e),setItem:(e,t)=>w$.set(e,t)};function T3e(){return typeof window<`u`?window.localStorage:globalThis.localStorage??w3e}var T$=Xt()(wJ(e=>({byRuntimeId:{},record:t=>e(e=>({byRuntimeId:{...e.byRuntimeId,[t.runtimeId]:t}})),clearRuntime:t=>e(e=>t in e.byRuntimeId?{byRuntimeId:Object.fromEntries(Object.entries(e.byRuntimeId).filter(([e])=>e!==t))}:e),reconcileCatalog:(t,n=Date.now())=>e(e=>{let r=Object.entries(e.byRuntimeId).filter(([,e])=>{if(n-e.recordedAt>C3e)return!1;let r=t.find(t=>t.cmmdOrganizationId===e.cmmdOrganizationId&&t.cmmdProjectId===e.cmmdProjectId);return r?.runtimeId===e.previousCatalogRuntimeId&&r.registeredAt===e.catalogRegisteredAt});return r.length===Object.keys(e.byRuntimeId).length?e:{byRuntimeId:Object.fromEntries(r)}}),reset:()=>e({byRuntimeId:{}})}),{name:S3e,storage:SJ(T3e),partialize:e=>({byRuntimeId:e.byRuntimeId}),version:2}));function E3e(e){T$.getState().record({...e,recordedAt:Date.now()})}function D3e(e){T$.getState().clearRuntime(e)}var O3e=new Set([`filesystem`,`terminal`,`git`,`project-write`]);function k3e(e){return e===`desktop-local`}function A3e(e){return e===`cloud`||e===`cloud-vm`||e===`cmmd`||e===`github`}function E$(e){return e.actionKind===`cloud-api`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud API route`,description:`Cloud and Command work routes through authenticated Forge Cloud APIs.`}:O3e.has(e.actionKind)?A3e(e.workSource)?e.workSource===`cloud-vm`&&e.executionRuntime===`cloud`?{available:!0,route:`cloud-vm`,requiresPermissionGate:!1,title:`Cloud VM route`,description:`Filesystem, terminal, git, and project writes run inside the user's Forge Cloud VM.`}:e.executionRuntime===`cloud`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud work route`,description:`Cloud-scoped filesystem, terminal, git, and project writes run in the Forge Cloud runtime.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Open in Forge Cloud`,description:`Cloud projects must execute inside the Forge Cloud runtime. Local Desktop cannot run cloud project filesystem, terminal, git, or project-write actions.`}:k3e(e.workSource)?e.surface===`desktop-local`||e.executionRuntime===`desktop-local`?{available:!0,route:`desktop-local`,requiresPermissionGate:!1,title:`Desktop local route`,description:`Local filesystem, terminal, git, and project writes run through the Desktop local backend.`}:e.executionRuntime===`dev-local-web`?{available:!0,route:`dev-local-web`,requiresPermissionGate:!1,title:`Dev local route`,description:`Local Web is a development-only projection and routes local actions through the dev server.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Switch to Desktop Local`,description:`Local projects must execute in the Desktop Local runtime. Forge Cloud cannot run local filesystem, terminal, git, or project-write actions.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unknown work source`,description:`Forge cannot safely route local actions for this work source yet.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unsupported route`,description:`Forge does not have a runtime route for this action yet.`}}var j3e=`Ready to use. Your cloud project starts when you open the first thread.`;function M3e(e){let t=E$({actionKind:`project-write`,surface:`cloud-official`,workSource:`cloud-vm`,executionRuntime:`cloud`});return{actionAuthority:`runtime`,surface:`cloud-official`,hostKind:`user-cloud-vm`,workSource:`cloud-vm`,executionRuntime:`cloud`,modelRuntime:`cloud`,linkState:`cloud-only`,workspaceIdentity:null,hideLocalPath:!0,label:`Cloud project`,description:e?`This project runs in your Forge Cloud VM.`:j3e,actionRouteLabel:t.title,actionRouteDescription:t.description,actionRouteAvailable:t.available,requiresPermissionGate:t.requiresPermissionGate}}var N3e=3e5;function D$(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t of e){let e={cmmdOrganizationId:t.cmmdOrganizationId,cmmdProjectId:t.cmmdProjectId};r.set(k$(e),e),t.runtimeId!==null&&i.set(t.runtimeId,e)}for(let a of t){if(n-a.recordedAt>N3e)continue;let t=r.get(k$({cmmdOrganizationId:a.cmmdOrganizationId,cmmdProjectId:a.cmmdProjectId})),o=e.find(e=>e.cmmdOrganizationId===a.cmmdOrganizationId&&e.cmmdProjectId===a.cmmdProjectId);t&&o?.runtimeId===a.previousCatalogRuntimeId&&o.registeredAt===a.catalogRegisteredAt&&!i.has(a.runtimeId)&&i.set(a.runtimeId,t)}return i}function O$(e){return e.environmentId??`cmmd-cloud-project:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function P3e(e){return{environmentId:O$(e),workspaceRoot:e.workspaceRoot,resolvedRef:e.resolvedRef}}function k$(e){return`cloud:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function F3e(e){let t=/^cloud:(\d+):(\d+)$/.exec(e??``);return t?{cmmdOrganizationId:Number(t[1]),cmmdProjectId:Number(t[2])}:null}function I3e(e){return`cloud-runtime:${e}`}var L3e=`cloud-unconnected:`;function R3e(e,t,n=[]){let r=k$(e);return A$({id:tn.make(`${L3e}${r}`),environmentId:an.make(O$(e)),name:e.projectName,cwd:``,repositoryIdentity:null,availability:void 0,defaultModelSelection:null,createdAt:void 0,updatedAt:void 0,scripts:[],projectKey:r,environmentPresence:`remote-only`,source:M3e(e.runtimeId!==null),memberProjectRefs:t?[t]:[],remoteEnvironmentLabels:[],worktreeMembers:[],activeWorktreeKey:null,preConnectCloud:{runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,removal:e.removal},cloudRemoval:e.removal},n)}function A$(e,t){if(t.length===0)return e;let n=[...e.memberProjectRefs],r=new Set(n.map(e=>`${e.environmentId}:${e.projectId}`));for(let e of t){let t=`${e.environmentId}:${e.projectId}`;r.has(t)||(r.add(t),n.push(e))}return n.length===e.memberProjectRefs.length?e:{...e,memberProjectRefs:n}}function j$(e,t,n,r){if(!e)return null;let i=t.find(t=>t.cmmdEnvironmentId===String(e));if(i)return{row:i,runtimeId:i.runtimeId,matchedByHandoff:!1};let a=Dl(e).legacyRuntimeId;if(a){let e=t.find(e=>e.runtimeId===a);if(e)return{row:e,runtimeId:a,matchedByHandoff:!1};let i=D$(t,n,r).get(a);if(!i)return null;let o=t.find(e=>e.cmmdOrganizationId===i.cmmdOrganizationId&&e.cmmdProjectId===i.cmmdProjectId);return o?{row:o,runtimeId:a,matchedByHandoff:!0}:null}let o=t.find(t=>t.runtimeId===null&&O$(t)===String(e));return o?{row:o,runtimeId:null,matchedByHandoff:!1}:null}function z3e(e,t=e.runtimeId){return{runtimeId:t,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,desiredState:e.desiredState}}function B3e(e){return e.desiredState===`stopped`}var V3e=15e3;function H3e(e){return e===401||e===403}function U3e(e){return typeof e!=`object`||!e?!1:e.retryable===!0}function M$(e){return H3e(e.status)||e.attempt>=e.maxAttempts||e.status>=200&&e.status<300?!1:e.status>=500||e.status===409&&U3e(e.body)}function W3e(e,t){let n=e?.trim();if(!n)return null;if(/^-?\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:r-t}function N$(e){let t=e=>Math.min(V3e,Math.max(0,e)),n=W3e(e.retryAfter,e.nowMs??Date.now());return t(n===null?300*2**Math.max(0,e.attempt-1):n)}var G3e=6e4;function K3e(e,t){if(!e||typeof e!=`object`)return t;let n=e.error;return typeof n==`string`&&n.trim().length>0?n:t}var P$=`CMMD returned an invalid Cloud runtime connection descriptor.`;function F$(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw Error(P$);return n}function q3e(e){if(!e||typeof e!=`object`)throw Error(P$);let t=e;return{httpBaseUrl:F$(t,`httpBaseUrl`),wsBaseUrl:F$(t,`wsBaseUrl`),bearerToken:F$(t,`bearerToken`),expiresAt:F$(t,`expiresAt`)}}async function J3e(e){let t=or(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),n=ur({method:`POST`,...e.signal?{signal:e.signal}:{},headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})});for(let r=1;r<=8;r+=1){let i=await fetch(t,n),a=await i.json().catch(()=>null);if(i.ok)return q3e(a);if(!M$({status:i.status,body:a,attempt:r,maxAttempts:8})){let e=IQ(i.status,a)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${i.status}).`;throw Object.assign(Error(K3e(a,e)),{status:i.status,...FQ(a)?{code:FQ(a)}:{}})}await UX(N$({attempt:r,retryAfter:i.headers.get(`retry-after`)}),e.signal)}throw Error(`Cloud runtime connection retry budget was exhausted.`)}function Y3e(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+G3e}function I$(e){let t=e.requestDescriptor??J3e,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=new AbortController,s=e=>HX(e,o.signal),c=()=>i||(i=s(t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId},signal:o.signal})).then(async t=>(await s(Promise.resolve(e.validateDescriptor?.(t))),await s(Promise.resolve(e.persistDescriptor?.(t))),await s(Promise.resolve()),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>{if(o.signal.aborted)return s(Promise.resolve(r));let t=e?.forceRefresh||a||Y3e(r,n())?c():Promise.resolve(r);return HX(s(t),e?.signal)},invalidate:()=>{a=!0},dispose:()=>{o.abort()}}}function X3e(e){let t=e.runtimeId?.trim();if(t)return t;let n=Dl(e.environmentId).legacyRuntimeId;if(n)return n;let r=C$().rows,i=Object.values(T$.getState().byRuntimeId);return j$(e.environmentId,r,i)?.runtimeId??null}function Z3e(e,t,n,r){let i=e,a=I$({runtimeId:t,...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...n===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:n,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await IX({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(r&&!r())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...WX(i),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:un(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:new Date().toISOString()};await YK(t),await ZK(t.environmentId),VK.getState().upsert(t),i=t}});return b4e(e.environmentId,a),a}function Q3e(e){let t={wsBaseUrl:e.record.wsBaseUrl,httpBaseUrl:e.record.httpBaseUrl,bearerToken:e.bearerToken,expiresAt:e.record.runtimeTicketExpiresAt??null};return{acquire:()=>Promise.resolve(t)}}function L$(e){let t=e.toLowerCase();return t.includes(`authentication`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`credential`)||t.includes(`runtime ticket`)||t.includes(`status 401`)||t.includes(`status 403`)}var R$=new Map,z$=new Map,B$=new Map,V$=new Map,H$=new Map,U$=new Set,W$=new Map,G$=null,K$=!1;function q$(e){return V$.get(e)??0}function J$(e){V$.set(e,q$(e)+1)}function Y$(e,t){return e.environmentId===t.environmentId&&e.httpBaseUrl===t.httpBaseUrl&&e.wsBaseUrl===t.wsBaseUrl&&e.runtimeId===t.runtimeId&&e.cmmdOrganizationId===t.cmmdOrganizationId}function X$(e){if(q$(e.record.environmentId)!==e.generation)return!1;let t=GK(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||Y$(t,e.record):t!==null&&Y$(t,e.registryExpectation.record)}var $3e=9e5,Z$=32,Q$=()=>void 0;function $$(e,t){return Vo(Lo(e,t))}function e1(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function e6e(e){let t=Lo(e.environmentId,e.threadId),n=oJ.getState(),r=aJ(n,t);if(r){if(r.hasPendingApprovals||r.hasPendingUserInput||r.hasActionableProposedPlan)return!0;let e=r.session?.orchestrationStatus;if(e&&e!==`idle`&&e!==`stopped`||r.latestTurn?.state===`running`)return!0}let i=iJ(n,t);if(!i)return!1;let a=i.session?.orchestrationStatus;return!!(a&&a!==`idle`&&a!==`stopped`)||i.latestTurn?.state===`running`||i.pendingSourceProposedPlan!==void 0}function t1(e){return e.refCount===0&&!e6e(e)}function n1(e){if(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Q$)return!0;let t=j1(e.environmentId);return t?(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`event`?w6e(t.event,e.environmentId):t.kind===`snapshot`&&(oJ.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),oJ.getState().clearThreadSubscriptionError(e.environmentId,e.threadId))},{onError:t=>hXe(e.environmentId,e.threadId,t)}),!0):!1}function r1(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=A1(()=>{n1(e)&&(e.lastAccessedAt=Date.now())}),n1(e))}function i1(e){let t=W$.get(e);return t?(e1(t),t.unsubscribeConnectionListener?.(),t.unsubscribeConnectionListener=null,W$.delete(e),t.unsubscribe(),t.unsubscribe=Q$,o6e(),!0):!1}var a1=null;function t6e(e){let t=Lo(e.environmentId,e.threadId),n=oJ.getState(),r=aJ(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=iJ(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function n6e(e){e.unsubscribe!==Q$&&(e.unsubscribe(),e.unsubscribe=Q$),n1(e)||r1(e)}function r6e(e,t,n){if(e.recoveryAttempts+=1,e.lastEventAt=Date.now(),console.warn(`[forge] thread-detail liveness watchdog recovering`,{action:t,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:Math.round(n),recoveryAttempts:e.recoveryAttempts}),t===`resubscribe`){n6e(e);return}j1(e.environmentId)?.reconnect().catch(t=>{gG(t,{route:`thread-detail-liveness-watchdog-reconnect-failed`,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:String(Math.round(n)),recoveryAttempts:String(e.recoveryAttempts)})})}function i6e(){let e=Date.now();for(let t of W$.values()){let n=G$e({isWorking:t6e(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:K$e,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&r6e(t,n,e-t.lastEventAt)}}function a6e(){a1===null&&(a1=setInterval(i6e,q$e))}function o6e(){W$.size>0||a1!==null&&(clearInterval(a1),a1=null)}function s6e(e){for(let[t,n]of W$)n.environmentId===e&&i1(t)}function c6e(e){let t=Lo(e.environmentId,e.threadId),n=oJ.getState(),r=iJ(n,t);if(!r)return null;let i=aJ(n,t),a=i?.latestUserMessageAt??null;if(a===null)for(let e=r.messages.length-1;e>=0;--e){let t=r.messages[e];if(t?.role===`user`){a=t.createdAt;break}}return{id:r.id,projectId:r.projectId,title:r.title,modelSelection:r.modelSelection,runtimeMode:r.runtimeMode,interactionMode:r.interactionMode,branch:r.branch,worktreePath:r.worktreePath,latestTurn:r.latestTurn,createdAt:r.createdAt,updatedAt:r.updatedAt??r.createdAt,archivedAt:r.archivedAt,session:r.session?{threadId:r.id,updatedAt:r.session.updatedAt,providerName:r.session.provider,runtimeMode:r.runtimeMode,activeTurnId:r.session.activeTurnId??null,lastError:r.session.lastError??null,status:r.session.orchestrationStatus}:null,latestUserMessageAt:a,hasPendingApprovals:i?.hasPendingApprovals??!1,hasPendingUserInput:i?.hasPendingUserInput??!1,hasActionableProposedPlan:i?.hasActionableProposedPlan??!1,anchorKind:r.anchorKind,anchorCmmdId:r.anchorCmmdId,kind:r.kind,parentThreadId:r.parentThreadId,status:r.status,workerRole:r.workerRole,goal:r.goal,titleRegeneration:r.titleRegeneration??null}}function l6e(e,t){if(W$.size===0)return e;let n=new Set(e.threads.map(e=>e.id)),r=[];for(let e of W$.values()){if(e.environmentId!==t||e.refCount<=0||n.has(e.threadId))continue;let i=c6e(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function u6e(e,t){let n=new Set(t);for(let[t,r]of W$)r.environmentId===e&&!n.has(r.threadId)&&t1(r)&&i1(t)}function d6e(e){e1(e),t1(e)&&(e.evictionTimeoutId=setTimeout(()=>{let t=W$.get($$(e.environmentId,e.threadId));t&&(t.evictionTimeoutId=null,t1(t)&&i1($$(e.environmentId,e.threadId)))},$3e))}function o1(){if(W$.size<=Z$)return;let e=[...W$.entries()].filter(([,e])=>t1(e)).toSorted(([,e],[,t])=>e.lastAccessedAt-t.lastAccessedAt);for(let[t]of e){if(W$.size<=Z$)return;i1(t)}}function s1(e){e1(e),t1(e)&&d6e(e)}function f6e(e,t){let n=W$.get($$(e,t));n&&s1(n)}function c1(e){for(let t of W$.values())t.environmentId===e&&s1(t);o1()}function p6e(e,t){let n=$$(e,t),r=W$.get(n);if(r){e1(r),r.refCount+=1,r.lastAccessedAt=Date.now(),n1(r)||r1(r);let e=!1;return()=>{e||(e=!0,r.refCount=Math.max(0,r.refCount-1),r.lastAccessedAt=Date.now(),r.refCount===0&&(s1(r),o1()))}}let i={environmentId:e,threadId:t,unsubscribe:Q$,unsubscribeConnectionListener:null,refCount:1,lastAccessedAt:Date.now(),evictionTimeoutId:null,lastEventAt:Date.now(),recoveryAttempts:0};W$.set(n,i),n1(i)||r1(i),a6e(),o1();let a=!1;return()=>{a||(a=!0,i.refCount=Math.max(0,i.refCount-1),i.lastAccessedAt=Date.now(),i.refCount===0&&(s1(i),o1()))}}function l1(){for(let e of U$)e()}function m6e(e){return{lastError:e instanceof Error?e.message:String(e),lastErrorAt:new Date().toISOString()}}function u1(){return new Date().toISOString()}var d1=8,f1=[1e3,2e3,4e3,8e3,12e3,16e3,2e4],h6e=9e4;function g6e(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function _6e(e){if(Q2e(e))return!1;let t=g6e(e);if(t===502||t===503||t===504||e._tag===`OrchestrationGetSnapshotError`)return!0;let n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return r.includes(`all fibers interrupted without error`)||r.includes(`timed out while waiting for forge cloud runtime metadata`)||r.includes(`timed out while waiting for`)||r.includes(`to stream its shell snapshot`)||r.includes(`forge runtime route not found`)||r.includes(`fly-replay`)||r.includes(`could not find a good candidate`)||r.includes(`instance refused connection`)||n.includes(`Unknown socket error`)||n.includes(`Failed to fetch remote auth endpoint`)||n.includes(`Forge runtime replay target is unavailable`)||n.includes(`Remote auth request failed (502)`)||n.includes(`Remote auth request failed (503)`)||n.includes(`Remote auth request failed (504)`)||n.includes(`Unable to connect to the Forge server WebSocket`)}function v6e(e){return f1[e]??f1[f1.length-1]}function y6e(){return h6e}function b6e(e,t){if(!GX(e))return t;let n=null,r=new Promise((t,r)=>{n=globalThis.setTimeout(()=>{r(Error(`Timed out while waiting for Forge Cloud runtime metadata for ${e.environmentId}. The VM may still be starting.`))},y6e())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function p1(e){zX.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function m1(e){let t=u1();zX.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),VK.getState().markConnected(e,t)}function h1(e,t){zX.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function g1(e,t){zX.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:u1(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:u1()}:{}})}function _1(e,t){zX.getState().patch(e,{connectionState:`error`,...m6e(t)})}function x6e(e){if(e.length<2)return[...e];let t=[];for(let n of e){let e=t.at(-1);if(e?.type===`thread.message-sent`&&n.type===`thread.message-sent`&&e.payload.threadId===n.payload.threadId&&e.payload.messageId===n.payload.messageId){t[t.length-1]={...n,payload:{...n.payload,attachments:n.payload.attachments??e.payload.attachments,createdAt:e.payload.createdAt,text:!n.payload.streaming&&n.payload.text.length>0?n.payload.text:e.payload.text+n.payload.text}};continue}t.push(n)}return t}function v1(){let e=$q(oJ.getState());eQ.getState().syncProjects(e.map(e=>({key:Bo(Io(e.environmentId,e.id)),cwd:e.cwd})))}function y1(){let e=eJ(oJ.getState());eQ.getState().syncThreads(e.map(e=>({key:Vo(Lo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),x$e(e.map(e=>Lo(e.environmentId,e.id)))}function S6e(){v1(),y1();let e=C$e({snapshotThreads:eJ(oJ.getState()).map(e=>({key:Vo(Lo(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:AX.getState().listDraftThreadKeys()});MZ.getState().removeOrphanedTerminalStates(e)}function b1(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function C6e(e,t){if(e.length===0)return;let n=w$e(e),r=x6e(e),i=e.some(e=>e.type===`project.created`||e.type===`project.meta-updated`||e.type===`project.deleted`);if(n.needsProviderInvalidation&&(K$=!0,G$?.queryInvalidationThrottler.maybeExecute()),oJ.getState().applyOrchestrationEvents(r,t),i){let e=$q(oJ.getState());eQ.getState().syncProjects(e.map(e=>({key:Bo(Io(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=eJ(oJ.getState());eQ.getState().syncThreads(e.map(e=>({key:Vo(Lo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=AX.getState();for(let e of n.promoteDraftThreadIds)jX(Lo(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(Lo(t,e)),eQ.getState().clearThreadUi(Vo(Lo(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=Lo(t,e);MZ.getState().removeTerminalState(n),zZ.getState().clearBrowserState(n)}c1(t)}function w6e(e,t){C6e([e],t)}function T6e(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?Lo(t,n):null,i=r?iJ(oJ.getState(),r):void 0;switch(oJ.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:v1();return;case`thread-upserted`:y1(),!i&&r&&jX(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(MZ.getState().removeTerminalState(r),zZ.getState().clearBrowserState(r)),f6e(t,e.thread.id),o1();return;case`thread-removed`:r&&(i1(Vo(r)),AX.getState().clearDraftThread(r),eQ.getState().clearThreadUi(Vo(r)),MZ.getState().removeTerminalState(r),zZ.getState().clearBrowserState(r)),y1();return}}function E6e(e,t){return e.invalidateQueries({queryKey:PX.all(t)})}function x1(e){return{onWelcome:(t,n)=>{e?.(t),G$&&E6e(G$.queryClient,n)},applyShellEvent:T6e,syncShellSnapshot:(e,t)=>{let n=l6e(e,t);oJ.getState().syncServerShellSnapshot(n,t),u6e(t,n.threads.map(e=>e.id)),c1(t),S6e()},applyTerminalEvent:(e,t)=>{let n=Lo(t,Vn.make(e.threadId)),r=iJ(oJ.getState(),n),i=AX.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&MZ.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=Lo(t,Vn.make(e.threadId)),r=iJ(oJ.getState(),n),i=AX.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&zZ.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{_1(t,e)}}}function S1(){if(typeof window>`u`)return;let e=pr();if(e?.primaryMode===`cloud`&&e.bearerToken)return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function D6e(){if(typeof window>`u`)return;let e=pr(),t=e?.primaryMode===`cloud`?e.desktopLocal??null:e??null;if(!(!t?.httpBaseUrl||!t.wsBaseUrl||!t.bearerToken))return{bearerToken:t.bearerToken,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,label:t.label}}function O6e(e){let t=Xie(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return PQ(new EQ(async()=>{await lr().catch(()=>null);let e=S1();if(e)try{return await LX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})}catch(e){throw ZG(e)&&dr(`ws-token`),e}return mJe(t)}))}function k6e(e){return PQ(new EQ(()=>LX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken}),{trackGlobalConnection:!1,onAttempt:()=>{p1(e.environmentId)},onOpen:()=>{m1(e.environmentId)},onError:t=>{zX.getState().patch(e.environmentId,{connectionState:`error`,lastError:t,lastErrorAt:u1()})},onClose:t=>{g1(e.environmentId,t.reason)}}))}function A6e(e,t,n,r){return n()&&zX.getState().ensure(e.environmentId),PQ(new EQ(async()=>{let e=await t.acquire(),n=e=>LX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken,...r?{runtimeTicket:e.bearerToken}:{}});try{return await n(e)}catch(e){if(!r||!ZG(e))throw e;return n(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&p1(e.environmentId)},onOpen:()=>{n()&&m1(e.environmentId)},onError:i=>{r&&L$(i)&&t.invalidate?.(),n()&&zX.getState().patch(e.environmentId,{connectionState:`error`,lastError:i,lastErrorAt:u1()})},onClose:i=>{r&&(i.code===1008||L$(i.reason))&&t.invalidate?.(),n()&&g1(e.environmentId,i.reason)}}))}async function C1(e,t,n,r,i,a,o){let s=await $Q(t,o),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),IX({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);if(!r())return!1;zX.getState().patch(e.environmentId,{authState:l.authenticated?`authenticated`:`requires-auth`,descriptor:c.environment,serverConfig:c,role:l.authenticated?l.role??i??null:null});let u=GK(e.environmentId);return r()&&l.authenticated&&u&&VK.getState().upsert({...u,lastAuthenticatedPullRequestCapability:c.environment.capabilities?.pullRequests===!0}),!0}function w1(e){let t=R$.get(e.environmentId);if(t&&t!==e)throw Error(`Environment ${e.environmentId} already has an active connection.`);return R$.set(e.environmentId,e),l1(),e}async function T1(e){let t=R$.get(e);return t?(R$.delete(e),e$(e),s6e(e),l1(),await t.dispose(),!0):!1}function E1(){let e=wK();if(!e?.environmentId)throw Error(`Unable to resolve the primary environment.`);let t=R$.get(e.environmentId);if(t)return t;let n=S1(),r=e.source===`paired-bearer`||!0;return w1(qX({kind:`primary`,knownEnvironment:e,client:O6e(e),resolveEnvironmentId:()=>wK()?.environmentId??e.environmentId,...r?{readiness:n?{bearerToken:n.bearerToken}:{}}:{},...x1()}))}async function j6e(e,t,n){let r=R$.get(e.environmentId);if(r)return r;let i=GX(e)?X3e(e):null,a=i!==null,o=()=>X$({record:e,generation:t,registryExpectation:n?.registryExpectation??{kind:`existing-record`,record:e}}),s=a?n?.bearerToken:n?.bearerToken??await XK(e.environmentId);if(!a&&!s)throw o()&&zX.getState().patch(e.environmentId,{authState:`requires-auth`,role:null,connectionState:`disconnected`,lastError:`Saved environment is missing its saved credential. Pair it again.`,lastErrorAt:u1()}),Error(`Saved environment is missing its saved credential.`);let c=a?Z3e(e,i,s??void 0,o):Q3e({record:e,bearerToken:s}),l=await $Q(c,n?.signal);if(!o())throw Error(`Saved environment changed while its connection was being acquired.`);let u=n?.client??A6e(e,c,o,a),d=Po({id:e.environmentId,label:e.label,source:`manual`,target:{httpBaseUrl:l.httpBaseUrl,wsBaseUrl:l.wsBaseUrl}}),f=a&&l.expiresAt?y4e({initialDescriptor:{httpBaseUrl:l.httpBaseUrl,wsBaseUrl:l.wsBaseUrl,bearerToken:l.bearerToken,expiresAt:l.expiresAt},renew:async()=>{let e=await c.acquire({forceRefresh:!0});return{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken,expiresAt:e.expiresAt??null}},onState:t=>{o()&&zX.getState().patch(e.environmentId,{providerAuthority:t})}}):null,p=qX({kind:`saved`,knownEnvironment:{...d,environmentId:e.environmentId},client:u,readiness:{bearerToken:l.bearerToken},tolerateReportedEnvironmentIdentity:a,refreshMetadata:async()=>{await C1(e,c,u,o)},...f?{ensureProviderAuthority:f.ensureLive,onDispose:f.dispose}:{},onConfigSnapshot:t=>{o()&&zX.getState().patch(e.environmentId,{descriptor:t.environment,serverConfig:t})},...x1(t=>{o()&&zX.getState().patch(e.environmentId,{descriptor:t.environment})})});try{if(!await b6e(e,C1(e,c,u,o,n?.role??null,n?.serverConfig??null,n?.signal))||!o())throw Error(`Saved environment changed while its connection was being acquired.`);return w1(p)}catch(t){throw a&&e$(e.environmentId,c),o()&&_1(e.environmentId,t),await p.dispose().catch(()=>void 0),t}}async function D1(e,t){let n=R$.get(e.environmentId);if(n)return n;let r=q$(e.environmentId),i=H$.get(e.environmentId);if(i&&i.generation===r&&Y$(i.record,e))return i.promise;let a=j6e(e,r,t).finally(()=>{H$.get(e.environmentId)?.promise===a&&H$.delete(e.environmentId)});return H$.set(e.environmentId,{generation:r,record:e,promise:a}),a}async function O1(e){await zl(e);let t=new Map(e.map(e=>[e.environmentId,e]));for(let[e,n]of H$){let r=t.get(e);(!r||!Y$(r,n.record))&&J$(e)}let n=new Set(e.map(e=>e.environmentId)),r=[...R$.values()].filter(e=>e.kind===`saved`).map(e=>e.environmentId).filter(e=>!n.has(e));await Promise.all(r.map(async e=>{J$(e),await N1(e)}))}function k1(){G$?.stop(),G$=null}function A1(e){return U$.add(e),()=>{U$.delete(e)}}function j1(e){return R$.get(e)??null}function M6e(e){let t=j1(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function M1(){return E1()}async function N6e(){let e=D6e();if(!e)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let t=await A$e({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return R$.get(t.environmentId)||w1(qX({kind:`desktop-local`,knownEnvironment:{...Po({id:t.environmentId,label:e.label,source:`desktop-managed`,target:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}),environmentId:t.environmentId,label:t.label},client:k6e({environmentId:t.environmentId,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken}),...x1()}))}async function P6e(e){let t=an.make(e.runtimeId),n=R$.get(t);if(n)return n;p1(t);let r=YQ(),i=l4e(e.runtimeId,{apiClient:JG,getStoredDeviceKey:HQ,buildDeviceRegistration:zQ,controlSessionId:r.controlSessionId}),a=await i.acquireRoute(),o=a,s=Ece({acquireRoute:async()=>{let e=o;return o=null,e??i.acquireRoute()},acquireActionGrant:i.acquireActionGrant,journal:r,lifecycle:{onConnecting:()=>{p1(t)},onAuthenticated:()=>{m1(t)},onDisconnected:e=>{g1(t,e.reason)},onError:e=>{_1(t,Object.assign(Error(e.message),e))}}}),c=PQ(new EQ(a.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:s,makeClient:Tce(Un)})),l=qX({kind:`saved`,knownEnvironment:{...Po({id:t,label:e.label,source:`manual`,target:{httpBaseUrl:mr()?.target.httpBaseUrl??a.relayWebSocketUrl,wsBaseUrl:a.relayWebSocketUrl}}),environmentId:t},client:c,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>{h1(t,e)},...x1(e=>{zX.getState().patch(t,{descriptor:e.environment})})});try{let[,e]=await Promise.all([l.ensureBootstrapped(),c.server.getConfig()]);return h1(t,e),m1(t),w1(l)}catch(e){throw _1(t,e),await l.dispose().catch(()=>void 0),e}}function F6e(e){let t=an.make(e.runtimeId),n=R$.get(t);if(n)return Promise.resolve(n);let r=z$.get(t);if(r)return r;let i=P6e(e).finally(()=>{z$.delete(t)});return z$.set(t,i),i}async function N1(e){R$.get(e)?.kind===`saved`&&(zX.getState().clear(e),await T1(e).catch(()=>!1))}async function I6e(e){let t=GK(e);if(!t)throw Error(`Saved environment not found.`);let n=R$.get(e);if(!n){try{await F1(t)}catch(t){throw _1(e,t),t}return}p1(e);try{await n.reconnect()}catch(t){throw _1(e,t),t}}function P1(e){for(let t of e){let e=B$.get(t);e===void 0||e<=1?B$.delete(t):B$.set(t,e-1)}}async function L6e(e){let t=e.environmentId;B$.set(t,(B$.get(t)??0)+1);try{return j1(t)||await F1(e),!0}catch{return P1([t]),!1}}async function R6e(){await UK();let e=(await Promise.all(tYe().map(async e=>await L6e(e)?e.environmentId:null))).flatMap(e=>e===null?[]:[e]),t=!1;return()=>{t||(t=!0,P1(e))}}async function z6e(e){J$(e),VK.getState().remove(e),await ZK(e),await N1(e)}async function B6e(e){let t=an.make(e.environment.environmentId),{existing:n,replacedRecord:r}=P$e({environmentId:t,replacesEnvironmentId:e.environment.replacesEnvironmentId}),{kind:i,cmmdOrganizationId:a,cmmdProjectId:o,runtimeId:s,runtimeTicketExpiresAt:c}=e.environment,l={environmentId:t,label:e.environment.label,wsBaseUrl:un(e.environment.wsBaseUrl),httpBaseUrl:e.environment.httpBaseUrl,createdAt:n?.createdAt??u1(),lastConnectedAt:u1(),...i===void 0?{}:{kind:i},...a===void 0?{}:{cmmdOrganizationId:a},...o===void 0?{}:{cmmdProjectId:o},...s===void 0?{}:{runtimeId:s},...c===void 0?{}:{runtimeTicketExpiresAt:c}};VX(e.signal);let u=await F$e(n);J$(l.environmentId),await T1(l.environmentId).catch(()=>!1),r&&(J$(r.environmentId),await T1(r.environmentId).catch(()=>!1)),await F1(l,{bearerToken:e.bearerToken,registryExpectation:n&&!r?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}});let d=!1;try{return VX(e.signal),await I$e({record:l,replacedRecord:r,rollback:u,...e.signal?{signal:e.signal}:{}}),d=!0,VX(e.signal),VK.getState().upsert(WX(l)),l}catch(t){throw await T1(l.environmentId).catch(()=>!1),d&&await KX({record:l,replacedRecord:r,rollback:u}),VX(e.signal),t}}async function F1(e,t){if(!GX(e))return D1(e,t);let n=q$(e.environmentId),r=()=>X$({record:e,generation:n,registryExpectation:t?.registryExpectation??{kind:`existing-record`,record:e}}),i=null;for(let n=0;n<d1;n+=1){VX(t?.signal);try{let n=await D1(e,t);return await HX(n.ensureBootstrapped(),t?.signal),n}catch(a){if(i=a,!r())throw a;if(await T1(e.environmentId).catch(()=>!1),VX(t?.signal),n>=7||!_6e(a))throw r()&&_1(e.environmentId,a),a;let o=v6e(n);t?.onBootstrapRetry?.({attempt:n+2,maxAttempts:d1,retryDelayMs:o,error:a}),r()&&zX.getState().patch(e.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await UX(o,t?.signal)}}let a=i instanceof Error?i:Error(String(i));throw r()&&_1(e.environmentId,a),a}async function V6e(e){await R$.get(e)?.ensureBootstrapped()}async function H6e(e){let t=R$.get(e);if(t?.ensureProviderAuthority){await t.ensureProviderAuthority();return}if(x4e(e))throw Error(`Cloud runtime provider authority is not available.`)}function U6e(e){if(G$?.queryClient===e)return G$.refCount+=1,()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&k1())};k1(),K$=!1;let t=new _Xe(()=>{K$&&(K$=!1,e.invalidateQueries({queryKey:NX.all}),e.invalidateQueries({queryKey:MX.all}))},{wait:100,leading:!1,trailing:!0});E1(),lr().catch(()=>void 0);let n=VK.subscribe(()=>{HK()&&O1(WK())});return UK().then(()=>O1(WK())).catch(()=>void 0),G$={queryClient:e,queryInvalidationThrottler:t,refCount:1,stop:()=>{n(),t.cancel()}},()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&k1())}}var W6e=wte(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]);function G6e(e){return{environmentId:e.environmentId,threadId:e.threadId}}function K6e(e){return{draftId:e}}function q6e(e){return!e.environmentId||!e.threadId?null:Lo(e.environmentId,e.threadId)}function J6e(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:Lo(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}var Y6e=F.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return vte(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function I1(e){let t=(0,cl.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Zt(`relative overflow-hidden rounded-sm bg-muted [--skeleton-highlight:--alpha(var(--color-white)/64%)] after:absolute after:inset-0 after:animate-skeleton after:bg-[linear-gradient(120deg,transparent_40%,var(--skeleton-highlight),transparent_60%)] motion-reduce:after:content-none dark:[--skeleton-highlight:--alpha(var(--color-white)/4%)]`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Nr.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function X6e(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=Kt(i),[,o]=F.useState(!1),s=Gt(Q6e).current,c=Gt(Z6e).current,l=F.useRef(0),u=F.useRef(!0),d=F.useRef([]),f=F.useRef(null),p=Kt(()=>{u.current||(u.current=!0,o(e=>!e))}),m=Kt((e,t)=>{c.set(e,t),p()}),h=Kt(e=>{c.delete(e),p()}),g=Kt(e=>{let t=new Map;return n.current.length=0,r&&(r.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),n.current[e.index]=e.element,r&&(r.current[e.index]=e.registration.label===void 0?e.registration.textRef?.current?.textContent??e.element.textContent:e.registration.label)}),l.current=n.current.length,t});function _(e){if(f.current?.disconnect(),f.current=null,typeof MutationObserver!=`function`||e.length<2)return;let t=new MutationObserver(n=>{if(!t8e(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&L1(r,n)>0){t.disconnect(),p();return}r=n}});f.current=t;let n=new Set;for(let t=1;t<e.length;t+=1){let r=e8e(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=Kt(()=>{let[e,t]=$6e(c),n=g(e);_(t),d.current=e,u.current=!1,s.forEach(e=>e(n)),a(n)});Jt(()=>(u.current||g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),Jt(()=>{u.current&&v()}),Jt(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=Kt(e=>(s.add(e),()=>{s.delete(e)})),b=F.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,Nr.jsx)(Ste.Provider,{value:b,children:t})}function Z6e(){return new Map}function Q6e(){return new Set}function $6e(e){let t=new Set,n=[],r=[];e.forEach((e,i)=>{if(!i.isConnected)return;let a=e.index,o={index:a??-1,element:i,registration:e};a===null?r.push(o):a>=0&&(t.add(a),n.push(o))});let i=0;return r.sort((e,t)=>L1(e.element,t.element)),r.forEach(e=>{for(;t.has(i);)i+=1;e.index=i,n.push(e),i+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}function e8e(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function t8e(e){for(let t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}function L1(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function R1(e){let t=e.browser,n=t?{openSession:t.openSession,listSessions:t.listSessions,closeSession:t.closeSession,getSession:t.getSession,command:t.command,clearBrowsingData:t.clearBrowsingData,attachDisplay:t.attachDisplay,addDisplayIceCandidate:async e=>{await t.addDisplayIceCandidate(e)},onEvent:(e,n)=>t.onEvent(e,n)}:void 0;return{...n?{browser:n}:{},attachments:{createUploadUrl:t=>e.attachments.createUploadUrl(t),delete:t=>e.attachments.delete(t)},computer:{input:t=>e.computer.input(t)},threadDevRuntime:{get:t=>e.threadDevRuntime.get(t),allocatePort:t=>e.threadDevRuntime.allocatePort(t),release:t=>e.threadDevRuntime.release(t)},devTunnel:{register:t=>e.devTunnel.register(t),unregister:t=>e.devTunnel.unregister(t),list:t=>e.devTunnel.list(t)},terminal:{open:t=>e.terminal.open(t),write:t=>e.terminal.write(t),resize:t=>e.terminal.resize(t),signal:t=>e.terminal.signal(t),clear:t=>e.terminal.clear(t),restart:t=>e.terminal.restart(t),close:t=>e.terminal.close(t),onEvent:t=>e.terminal.onEvent(t)},projects:{searchContents:e.projects.searchContents,searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},workspace:{environmentPreflight:e.workspace.environmentPreflight,ensureScratch:e.workspace.ensureScratch},shell:{openInEditor:t=>e.shell.openInEditor(t)},git:{pull:e.git.pull,refreshStatus:e.git.refreshStatus,onStatus:(t,n,r)=>e.git.onStatus(t,n,r),listBranches:e.git.listBranches,createWorktree:e.git.createWorktree,removeWorktree:e.git.removeWorktree,createBranch:e.git.createBranch,checkout:e.git.checkout,init:e.git.init,resolvePullRequest:e.git.resolvePullRequest,preparePullRequestThread:e.git.preparePullRequestThread},pullRequests:{list:t=>e.pullRequests.list(t),listStats:t=>e.pullRequests.listStats(t),detail:t=>e.pullRequests.detail(t),activity:t=>e.pullRequests.activity(t),threadComments:t=>e.pullRequests.threadComments(t),diffFileContents:t=>e.pullRequests.diffFileContents(t),runAction:t=>e.pullRequests.runAction(t),update:t=>e.pullRequests.update(t),comment:t=>e.pullRequests.comment(t),updateComment:t=>e.pullRequests.updateComment(t),submitReview:t=>e.pullRequests.submitReview(t),replyToThread:t=>e.pullRequests.replyToThread(t),setThreadResolution:t=>e.pullRequests.setThreadResolution(t),setReaction:t=>e.pullRequests.setReaction(t),invalidate:t=>e.pullRequests.invalidate(t),reviewerCandidates:t=>e.pullRequests.reviewerCandidates(t),requestReviewers:t=>e.pullRequests.requestReviewers(t)},orchestration:{dispatchCommand:e.orchestration.dispatchCommand,getTurnDiff:e.orchestration.getTurnDiff,getFullThreadDiff:e.orchestration.getFullThreadDiff,subscribeShell:(t,n)=>e.orchestration.subscribeShell(t,n),subscribeThread:(t,n,r)=>e.orchestration.subscribeThread(t,n,r)}}}function z1(e){if(typeof window>`u`||!e)return;let t=j1(e);return t?R1(t.client):void 0}function n8e(e){let t=(0,cl.c)(4),n;t[0]===e?n=t[1]:(n=()=>j1(e),t[0]=e,t[1]=n);let r=(0,F.useSyncExternalStore)(A1,n,r8e),i,a;return t[2]===r?a=t[3]:(a=r?R1(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function r8e(){return null}function i8e(e){let t=z1(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}var B1=`forge:last-editor`;function a8e(e){let t=(0,cl.c)(5),[n,r]=Cl(B1,null,zn),i;bb0:{if(n&&e.includes(n)){i=n;break bb0}let r;t[0]===e?r=t[1]:(r=en.find(t=>e.includes(t.id))?.id??null,t[0]=e,t[1]=r),i=r}let a=i,o;return t[2]!==a||t[3]!==r?(o=[a,r],t[2]=a,t[3]=r,t[4]=o):o=t[4],o}function V1(e){let t=new Set(e),n=yl(B1,zn);if(n&&t.has(n))return n;let r=en.find(e=>t.has(e.id))?.id??null;return r&&bl(B1,r,zn),r??null}async function o8e(e,t){let{availableEditors:n}=await e.server.getConfig(),r=V1(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}function H1(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var U1=Object.freeze({data:null,error:null,cause:null,isPending:!1}),W1=Object.freeze({...U1,isPending:!0}),s8e=Wt(U1).pipe(Ut,Vt(`git-status:null`)),G1=()=>void 0,K1=new Map,c8e=new Set,q1=new Map,J1=new Map,l8e=1e3,Y1=gte(e=>(c8e.add(e),Wt(W1).pipe(Ut,Vt(`git-status:${e}`))));function X1(e){return e.environmentId===null||H1(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function Z1(e){if(e.environmentId===null)return null;let t=j1(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function Q1(e){let t=X1(e);return t===null?U1:Ht.get(Y1(t))}function u8e(e,t){let n=X1(e);if(n===null)return G1;let r=K1.get(n);return r?(r.refCount+=1,()=>$1(n)):(K1.set(n,{refCount:1,unsubscribe:p8e(n,e,t)}),()=>$1(n))}function d8e(e,t){let n=X1(e),r=H1(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??Z1(e)?.client;if(!i)return Promise.resolve(Q1(e).data);let a=q1.get(n);if(a)return a;let o=J1.get(n)??0;if(Date.now()-o<l8e)return Promise.resolve(Q1(e).data);J1.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{q1.delete(n)});return q1.set(n,s),s}function f8e(e){let t=(0,cl.c)(4),n=X1(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>u8e({environmentId:e.environmentId,cwd:e.cwd}),i=[e.environmentId,e.cwd],t[0]=e.cwd,t[1]=e.environmentId,t[2]=r,t[3]=i):(r=t[2],i=t[3]),(0,F.useEffect)(r,i);let a=cr(n===null?s8e:Y1(n));return n===null?U1:a}function $1(e){let t=K1.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),K1.delete(e)))}function p8e(e,t,n){let r=H1(t.cwd);if(r===null)return G1;let i=null,a=G1,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:Z1(t);if(!o){i!==null&&(a(),a=G1,i=null),e0(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=m8e(e,r,o.client))},s=n?G1:A1(o);return o(),()=>{s(),a()}}function m8e(e,t,n){return e0(e),n.onStatus({cwd:t},t=>{Ht.set(Y1(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{e0(e)}})}function e0(e){let t=Y1(e),n=Ht.get(t),r=n.data===null?W1:{...n,error:null,cause:null,isPending:!0};(n.data!==r.data||n.error!==r.error||n.cause!==r.cause||n.isPending!==r.isPending)&&Ht.set(t,r)}function t0(e,t){return Wt(t).pipe(Ut,Vt(e))}function n0(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var h8e=[],g8e=[],_8e=[],v8e=e=>e?.availableEditors??h8e,y8e=e=>e?.keybindings??g8e,b8e=e=>e?.keybindingsConfigPath??null,x8e=e=>e?.observability??null,S8e=e=>e?.providers??_8e,C8e=e=>e?.settings??bne,r0=t0(`server-welcome`,null),i0=t0(`server-config`,null),a0=t0(`server-config-updated`,null),w8e=t0(`server-providers-updated`,null);function o0(){return Ht.get(i0)}function T8e(){return Ht.get(a0)}function s0(e){d0(e),f0({providers:e.providers}),p0(n0(e),`snapshot`)}function E8e(e){switch(e.type){case`snapshot`:s0(e.config);return;case`keybindingsUpdated`:{let t=o0();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};d0(n),p0(n0(n),e.type);return}case`providerStatuses`:c0(e.payload);return;case`settingsUpdated`:l0(e.payload.settings);return;case`environmentUpdated`:u0(e.payload.environment);return}}function c0(e){let t=o0();if(f0(e),!t)return;let n={...t,providers:e.providers};d0(n),p0(n0(n),`providerStatuses`)}function l0(e){let t=o0();if(!t)return;let n={...t,settings:e};d0(n),p0(n0(n),`settingsUpdated`)}function u0(e){let t=o0();if(SK()?.environmentId===e.environmentId&&CK(e),!t)return;let n={...t,environment:e};d0(n),p0(n0(n),`environmentUpdated`)}function D8e(e){Ht.set(r0,e)}function O8e(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&D8e(e.payload)}),e.subscribeConfig(e=>{E8e(e)})];return o0()===null&&e.getConfig().then(e=>{t||o0()!==null||s0(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var k8e=1;function d0(e){Ht.set(i0,e)}function f0(e){Ht.set(w8e,e)}function p0(e,t){Ht.set(a0,{id:k8e++,payload:e,source:t})}function m0(e,t){let n=(0,F.useRef)(t);n.current=t;let r=(0,F.useCallback)(e=>{e!==null&&n.current(e)},[]);Ene(e,r,{immediate:!0})}function A8e(){return cr(i0)}function h0(){return cr(i0,C8e)}function j8e(){return cr(i0,S8e)}function M8e(){return cr(i0,y8e)}function N8e(){return cr(i0,v8e)}function P8e(){return cr(i0,b8e)}function F8e(){return cr(i0,x8e)}function I8e(e){m0(r0,e)}function L8e(e){m0(a0,e)}function R8e(e){let t=[];for(let n of e){let e=n.children??[];if(e.length>0){t.push({item:n,isGroupLabel:!0});for(let n of e)t.push({item:n,isGroupLabel:!1});continue}Array.isArray(n.children)||t.push({item:n,isGroupLabel:!1})}return t}function z8e(e){let t=document.createElement(`div`);return t.textContent=e,t.className=`px-2 pt-1.5 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,t}function B8e(e){let t=document.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled,t.className=e.disabled?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-muted-foreground/50 cursor-not-allowed`:e.destructive?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-destructive transition-colors hover:bg-accent`:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-popover-foreground transition-colors hover:bg-accent`,t}function V8e(e,t){return new Promise(n=>{let r=document.createElement(`div`);r.style.cssText=`position:fixed;inset:0;z-index:9999`;let i=document.createElement(`div`);i.className=`fixed z-[10000] min-w-[160px] rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg/5 outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]`;let a=t?.x??0,o=t?.y??0;i.style.top=`${o}px`,i.style.left=`${a}px`;function s(e){document.removeEventListener(`keydown`,c),r.remove(),i.remove(),n(e)}function c(e){e.key===`Escape`&&(e.preventDefault(),s(null))}r.addEventListener(`mousedown`,()=>s(null)),document.addEventListener(`keydown`,c);let l=!1;for(let{item:t,isGroupLabel:n}of R8e(e)){if(n){i.appendChild(z8e(t.label));continue}let e=t.destructive===!0||t.id===`delete`,r=t.disabled===!0;if(e&&!l){let e=document.createElement(`div`);e.className=`-mx-1 my-1 h-px bg-border`,i.appendChild(e),l=!0}let a=B8e({label:t.label,disabled:r,destructive:e});r||a.addEventListener(`click`,()=>s(t.id)),i.appendChild(a)}document.body.appendChild(r),document.body.appendChild(i),requestAnimationFrame(()=>{let e=i.getBoundingClientRect();e.right>window.innerWidth&&(i.style.left=`${window.innerWidth-e.width-4}px`),e.bottom>window.innerHeight&&(i.style.top=`${window.innerHeight-e.height-4}px`)})})}var g0;function H8e(){return _0(M1().client)}function _0(e){return{getConfig:e.server.getConfig,refreshProviders:e.server.refreshProviders,startProviderAuth:e.server.startProviderAuth,repairProviderAuthRuntime:e.server.repairProviderAuthRuntime,disconnectProviderAuth:e.server.disconnectProviderAuth,getProviderAuthSession:e.server.getProviderAuthSession,cancelProviderAuth:e.server.cancelProviderAuth,submitProviderAuthCode:e.server.submitProviderAuthCode,syncPersonalCodexToCloud:e.server.syncPersonalCodexToCloud,syncPersonalClaudeToCloud:e.server.syncPersonalClaudeToCloud,upsertKeybinding:e.server.upsertKeybinding,removeKeybinding:e.server.removeKeybinding,getSettings:e.server.getSettings,updateSettings:e.server.updateSettings,updateEnvironmentDisplayName:async t=>{let n=await e.server.updateEnvironmentDisplayName({displayName:t});return u0(n.environment),n}}}function U8e(e,t){return{...e,...t,dialogs:{...e.dialogs,...t.dialogs},shell:{...e.shell,...t.shell},contextMenu:{...e.contextMenu,...t.contextMenu},persistence:{...e.persistence,...t.persistence},server:{...e.server,...t.server}}}function W8e(e){return{dialogs:{pickFolder:async()=>window.desktopBridge?window.desktopBridge.pickFolder():null,confirm:async e=>window.desktopBridge?window.desktopBridge.confirm(e):window.confirm(e)},shell:{openInEditor:(t,n)=>e.shell.openInEditor({cwd:t,editor:n}),openExternal:async e=>{if(window.desktopBridge){if(!await window.desktopBridge.openExternal(e))throw Error(`Unable to open link.`);return}window.open(e,`_blank`,`noopener,noreferrer`)}},contextMenu:{show:async(e,t)=>window.desktopBridge?window.desktopBridge.showContextMenu(e,t):V8e(e,t)},persistence:{getClientSettings:Il,setClientSettings:Ll,getSavedEnvironmentRegistry:Rl,setSavedEnvironmentRegistry:zl,getSavedEnvironmentSecret:Bl,setSavedEnvironmentSecret:Vl,removeSavedEnvironmentSecret:Hl},server:_0(e)}}function v0(){if(typeof window>`u`)return;if(g0)return g0;let e=W8e(M1().client);return window.nativeApi?(g0=U8e(e,window.nativeApi),g0):(g0=e,g0)}function G8e(){let e=v0();if(!e)throw Error(`Local API not found`);return e}var K8e=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,q8e=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function J8e(e){let t=e.trim();return t.length===0?``:/^(['"]).*\1$/u.test(t)||/^[a-zA-Z][a-zA-Z0-9-]*$/u.test(t)?t:`"${t.replaceAll(`"`,``)}"`}function Y8e(e){let t=e.split(`,`).map(J8e).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var y0={fontSans:`--font-sans`,fontMono:`--font-mono`,fontComposer:`--font-composer`,fontTerminal:`--font-terminal`,promptFontSize:`--forge-prompt-font-size`,terminalFontSize:`--forge-terminal-font-size`,glassOpacity:`--glass-opacity`};function X8e(e,t){let n=[[y0.fontSans,t.fontFamilySans,K8e],[y0.fontMono,t.fontFamilyCode,q8e],[y0.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[y0.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=Y8e(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(y0.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(y0.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(y0.glassOpacity,`${String(t.glassOpacity)}%`),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}var b0=`themeId`,x0=`forge:theme-boot:v1`;function Z8e(e,t){try{window.localStorage.setItem(x0,JSON.stringify({appearance:t,background:e}))}catch{}}function Q8e(){try{window.localStorage.removeItem(x0)}catch{}}function S0(){return typeof document>`u`?null:document.documentElement}function C0(){let e=S0();if(e!==null){for(let t of nn)e.style.removeProperty(_n[t]);delete e.dataset[b0],Q8e()}}function $8e(e,t){let n=S0();if(n===null)return;let r=t===`dark`?e.dark:e.light;for(let e of nn){let t=r[e];if(t===void 0){n.style.removeProperty(_n[e]);continue}n.style.setProperty(_n[e],t)}n.dataset[b0]=e.id,r.background!==void 0&&Z8e(r.background,t)}function e5e(e,t){if(e===`forge`){C0();return}let n=lne(e);if(n===void 0){C0();return}$8e(n,t)}function w0(e,t){if(!Fe(e)||!Fe(t))return t;let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=Fe(t)&&Fe(r)?w0(t,r):r}return n}var T0=`[CLIENT_SETTINGS]`,E0=new Set,D0=An,O0=!1,k0=null;function t5e(){for(let e of E0)e()}function A0(){return D0}function j0(e){D0=e,t5e()}function n5e(e){return E0.add(e),r5e(),()=>{E0.delete(e)}}async function r5e(){if(O0)return;if(k0)return k0;let e=(async()=>{try{let e=await Il();e&&j0(e)}catch(e){console.error(`${T0} hydrate failed`,e)}finally{O0=!0}})().finally(()=>{k0===e&&(k0=null)});return k0=e,k0}function i5e(e){j0(e),Ll(e).catch(e=>{console.error(`${T0} persist failed`,e)})}var a5e=new Set(Kte(yne.fields));function o5e(e){let t={},n={};for(let[r,i]of Object.entries(e))a5e.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function M0(e){let t=h0(),n=(0,F.useSyncExternalStore)(n5e,A0,()=>An),r=(0,F.useMemo)(()=>({...t,...n}),[n,t]);return(0,F.useMemo)(()=>e?e(r):r,[r,e])}function N0(){let e=(0,cl.c)(2),t=s5e,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(Ate)},e[0]=n):n=e[0];let r=n,i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={updateSettings:t,resetSettings:r},e[1]=i):i=e[1],i}function s5e(e){let{serverPatch:t,clientPatch:n}=o5e(e);if(Object.keys(t).length>0){let e=o0();e&&l0(w0(e.settings,t)),M1().client.server.updateSettings(t)}Object.keys(n).length>0&&i5e({...A0(),...n})}var c5e=`forge:theme`,P0=`theme-color`,l5e=`meta[name="${P0}"][data-dynamic-theme-color="true"]`,F0=`(prefers-color-scheme: dark)`,u5e={dark:`#0a0a0a`,light:`#ffffff`};function d5e(){return typeof window<`u`&&typeof localStorage<`u`}function I0(e){return e===`system`||e===`light`||e===`dark`}function L0(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function f5e(){if(!d5e())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(Ol);if(e){let t=jl(JSON.parse(e));return{theme:I0(t.theme)?t.theme:`system`,uiFontSize:L0(t.uiFontSize,16),codeFontSize:L0(t.codeFontSize,13)}}let t=window.localStorage.getItem(c5e);return{theme:I0(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function p5e(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(F0).matches?`dark`:`light`}function R0(e){return e===`system`?p5e():e}function m5e(){let e=document.querySelector(l5e);return e||(e=document.createElement(`meta`),e.name=P0,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function z0(e){let t=e?.trim().toLowerCase();return!t||t===`transparent`||t===`rgba(0, 0, 0, 0)`||t===`rgba(0 0 0 / 0)`?null:e?.trim()??null}function h5e(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function g5e(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function B0(e=g5e()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=z0(getComputedStyle(h5e()).backgroundColor),n=z0(getComputedStyle(document.body).backgroundColor),r=t??n??u5e[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,m5e().setAttribute(`content`,r)}function _5e(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function V0(e,t=!1){let n=R0(e);return typeof document>`u`||typeof window>`u`?n:(t&&document.documentElement.classList.add(`no-transitions`),document.documentElement.classList.toggle(`dark`,n===`dark`),document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=n,B0(n),_5e(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function H0(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${L0(e,16)}px`)}function U0(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${L0(e,13)}px`)}function W0(e){H0(e.uiFontSize),U0(e.codeFontSize)}if(typeof document<`u`){let e=f5e();V0(e.theme),W0(e)}function v5e(){let e=(0,cl.c)(34),t=M0(S5e),n=M0(x5e),r=M0(b5e),i=M0(y5e),{updateSettings:a}=N0(),o;e[0]===t?o=e[1]:(o=()=>R0(t),e[0]=t,e[1]=o);let[s,c]=(0,F.useState)(o),l;e[2]===a?l=e[3]:(l=e=>{a({theme:e}),c(V0(e,!0))},e[2]=a,e[3]=l);let u=l,d;e[4]===a?d=e[5]:(d=e=>{a({themeId:e})},e[4]=a,e[5]=d);let f=d,p;e[6]===a?p=e[7]:(p=e=>{let t=L0(e,16);a({uiFontSize:t}),H0(t)},e[6]=a,e[7]=p);let m=p,h;e[8]===a?h=e[9]:(h=e=>{let t=L0(e,13);a({codeFontSize:t}),U0(t)},e[8]=a,e[9]=h);let g=h,_,v;e[10]===t?(_=e[11],v=e[12]):(_=()=>{c(V0(t))},v=[t],e[10]=t,e[11]=_,e[12]=v),(0,F.useEffect)(_,v);let y,b;e[13]!==i||e[14]!==r?(y=()=>{W0({uiFontSize:r,codeFontSize:i})},b=[r,i],e[13]=i,e[14]=r,e[15]=y,e[16]=b):(y=e[15],b=e[16]),(0,F.useEffect)(y,b);let x,S;e[17]!==s||e[18]!==n?(S=()=>{e5e(n,s===`dark`?`dark`:`light`)},x=[n,s],e[17]=s,e[18]=n,e[19]=x,e[20]=S):(x=e[19],S=e[20]),(0,F.useEffect)(S,x);let C,w;e[21]===t?(C=e[22],w=e[23]):(C=()=>{if(t!==`system`||typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(F0),n=()=>{c(V0(`system`,!0))};return e.addEventListener(`change`,n),()=>{e.removeEventListener(`change`,n)}},w=[t],e[21]=t,e[22]=C,e[23]=w),(0,F.useEffect)(C,w);let T;return e[24]!==i||e[25]!==s||e[26]!==g||e[27]!==u||e[28]!==f||e[29]!==m||e[30]!==t||e[31]!==n||e[32]!==r?(T={theme:t,setTheme:u,themeId:n,setThemeId:f,resolvedTheme:s,uiFontSize:r,codeFontSize:i,setUiFontSize:m,setCodeFontSize:g},e[24]=i,e[25]=s,e[26]=g,e[27]=u,e[28]=f,e[29]=m,e[30]=t,e[31]=n,e[32]=r,e[33]=T):T=e[33],T}function y5e(e){return e.codeFontSize}function b5e(e){return e.uiFontSize}function x5e(e){return e.themeId}function S5e(e){return e.theme}function C5e(){let e=(0,cl.c)(10),t=M0(j5e),n=M0(A5e),r=M0(k5e),i=M0(O5e),a=M0(D5e),o=M0(E5e),s=M0(T5e),c=M0(w5e),l,u;e[0]!==n||e[1]!==r||e[2]!==t||e[3]!==i||e[4]!==s||e[5]!==c||e[6]!==a||e[7]!==o?(l=()=>{typeof document>`u`||X8e(document.documentElement,{fontFamilyCode:n,fontFamilyComposer:r,fontFamilySans:t,fontFamilyTerminal:i,fontSmoothing:s,glassOpacity:c,promptFontSize:a,terminalFontSize:o})},u=[n,r,t,i,s,c,a,o],e[0]=n,e[1]=r,e[2]=t,e[3]=i,e[4]=s,e[5]=c,e[6]=a,e[7]=o,e[8]=l,e[9]=u):(l=e[8],u=e[9]),(0,F.useEffect)(l,u)}function w5e(e){return e.glassOpacity}function T5e(e){return e.fontSmoothing}function E5e(e){return e.terminalFontSize}function D5e(e){return e.promptFontSize}function O5e(e){return e.fontFamilyTerminal}function k5e(e){return e.fontFamilyComposer}function A5e(e){return e.fontFamilyCode}function j5e(e){return e.fontFamilySans}function M5e(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var G0=new Map;function K0(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=G0.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,M5e(e,t));return G0.set(n,i),i}function N5e(e,t){return K0(t,!0).format(new Date(e))}function P5e(e,t){return K0(t,!1).format(new Date(e))}function q0(e){let t=Date.now()-new Date(e).getTime();if(t<0)return{value:`just now`,suffix:null};let n=Math.floor(t/1e3);if(n<60)return{value:`just now`,suffix:null};let r=Math.floor(n/60);if(r<60)return{value:`${r}m`,suffix:`ago`};let i=Math.floor(r/60);return i<24?{value:`${i}h`,suffix:`ago`}:{value:`${Math.floor(i/24)}d`,suffix:`ago`}}function F5e(e){let t=q0(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}var I5e=new Set([`tool.started`,`task.started`,`context-window.updated`,`text-generation.usage`,`worktree.stage`,`launch.agent-starting`]);function J0(e){return I5e.has(e.kind)||e.summary===`Checkpoint captured`}function L5e(e,t){return!t.latestTurnId||e.turnId===t.latestTurnId||R5e(e)?!0:z5e(e,t.latestTurnStartedAt)}function R5e(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function z5e(e,t){return e.turnId!==null||e.tone!==`error`||t===null?!1:e.createdAt>=t}var B5e=[{value:`codex`,label:`Codex`,available:!0},{value:`claudeAgent`,label:`Claude`,available:!0},{value:`cmmd`,label:`CMMD`,available:!0},{value:`ollama`,label:`Ollama`,available:!1},{value:`cursor`,label:`Cursor`,available:!1}];function V5e(e){if(!Number.isFinite(e)||e<0)return`0ms`;if(e<1e3)return`${Math.max(1,Math.round(e))}ms`;if(e<1e4)return`${(e/1e3).toFixed(1)}s`;if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n===0?`${t}m`:n===60?`${t+1}m`:`${t}m ${n}s`}function H5e(e,t){if(!t)return null;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)||r<n?null:V5e(r-n)}function Y0(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function U5e(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?Y0(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function X0(e){switch(e){case`command_execution_approval`:case`exec_command_approval`:return`command`;case`file_read_approval`:return`file-read`;case`file_change_approval`:case`apply_patch_approval`:return`file-change`;default:return null}}function Z0(e){let t=e?.toLowerCase();return t?t.includes(`stale pending approval request`)||t.includes(`stale pending user-input request`)||t.includes(`unknown pending approval request`)||t.includes(`unknown pending permission request`)||t.includes(`unknown pending user-input request`):!1}function W5e(e){let t=new Map,n=[...e].toSorted(h2);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?Sn.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?X0(n.requestType):null,a=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`approval.requested`&&r&&i){t.set(r,{requestId:r,requestKind:i,createdAt:e.createdAt,...a?{detail:a}:{}});continue}if(e.kind===`approval.resolved`&&r){t.delete(r);continue}if(e.kind===`provider.approval.respond.failed`&&r&&Z0(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function G5e(e){let t=e?.questions;if(!Array.isArray(t))return null;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||typeof t.header!=`string`||typeof t.question!=`string`||!Array.isArray(t.options))return null;let n=t.options.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.description!=`string`?null:{label:t.label,description:t.description}}).filter(e=>e!==null);return n.length===0?null:{id:t.id,header:t.header,question:t.question,options:n,multiSelect:t.multiSelect===!0}}).filter(e=>e!==null);return n.length>0?n:null}function K5e(e){let t=new Map,n=[...e].toSorted(h2);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?Sn.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=G5e(n);if(!i)continue;t.set(r,{requestId:r,createdAt:e.createdAt,questions:i});continue}if(e.kind===`user-input.resolved`&&r){t.delete(r);continue}e.kind===`provider.user-input.respond.failed`&&r&&Z0(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function q5e(e,t){if(!t)return null;let n=[...e].toSorted(h2),r=null;for(let e of n){let t=$0(e.payload&&typeof e.payload==`object`?e.payload:null);t&&(r={request:t,turnId:e.turnId})}return!r||r.turnId!==t?null:r.request}function J5e(e,t){let n=[...e].toSorted(h2),r=n.filter(e=>e.kind===`turn.plan.updated`),i=(t?r.findLast(e=>e.turnId===t):void 0)??r.at(-1)??null;if(!i)return null;let a=i.payload&&typeof i.payload==`object`?i.payload:null,o=a?.plan;if(!Array.isArray(o))return null;let s=o.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.step!=`string`)return null;let n=t.status===`completed`||t.status===`inProgress`?t.status:`pending`;return{step:t.step,status:n}}).filter(e=>e!==null);if(s.length===0)return null;let c=i.turnId!==null&&n.some(e=>e.kind===`turn.completed`&&e.turnId===i.turnId&&h2(i,e)<0)?s.map(e=>e.status===`inProgress`?{...e,status:`completed`}:e):s;return{createdAt:i.createdAt,turnId:i.turnId,...a&&`explanation`in a?{explanation:a.explanation}:{},steps:c}}function Q0(e,t){if(t){let n=[...e].filter(e=>e.turnId===t).toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);if(n)return o2(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?o2(n):null}function Y5e(e){let t=e.threads.find(t=>t.id===e.threadId)?.proposedPlans??[];if(!e.latestTurnSettled){let t=e.latestTurn?.sourceProposedPlan;if(t){let n=e.threads.find(e=>e.id===t.threadId)?.proposedPlans.find(e=>e.id===t.planId);if(n)return o2(n)}}return Q0(t,e.latestTurn?.turnId??null)}function X5e(e){return e!==null&&e.implementedAt===null}function Z5e(e,t,n){let r=Q5e(),i={latestTurnId:t,latestTurnStartedAt:n??null};return o7e([...e].toSorted(h2).filter(e=>L5e(e,i)).filter(e=>!J0(e)).filter(e=>r||e.kind!==`runtime.warning`).filter(e=>!$5e(e)).map(e7e)).map(({activityKind:e,collapseKey:t,...n})=>n)}function Q5e(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function $5e(e){if(e.kind!==`tool.updated`&&e.kind!==`tool.completed`)return!1;let t=e.payload&&typeof e.payload==`object`?e.payload:null;return typeof t?.detail==`string`&&t.detail.startsWith(`ExitPlanMode:`)}function e7e(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=x7e(t),r=D7e(t),i=S7e(t),a=e.kind===`task.progress`||e.kind===`task.completed`,o=a&&typeof t?.summary==`string`&&t.summary.length>0?t.summary:null,s=a&&!o&&typeof t?.detail==`string`&&t.detail.length>0?t.detail:null,c=o||s,l={id:e.id,createdAt:e.createdAt,label:c||e.summary,tone:e.kind===`task.progress`?`thinking`:e.tone,activityKind:e.kind},u=T7e(t),d=E7e(t);if(!s&&t&&typeof t.detail==`string`&&t.detail.length>0){let e=f2(t.detail).output;e&&(l.detail=e)}n.command&&(l.command=n.command),n.rawCommand&&(l.rawCommand=n.rawCommand),r.length>0&&(l.changedFiles=r),i&&(l.toolTitle=i),u&&(l.itemType=u),d&&(l.requestKind=d);let f=t7e(t);if(f)l.githubConfirmation=f,l.tone=`approval`,l.label=`GitHub action needs approval`,l.toolTitle=t2(f.operation),l.detail=n2(f);else{let e=$0(t);e&&(l.githubActionRequired=e,l.tone=`approval`,l.label=r2(e.action),l.toolTitle=`GitHub setup required`,l.detail=a2(e))}let p=u7e(l);return p&&(l.collapseKey=p),l}function t7e(e){for(let t of e2(e)){if(t.userActionRequired!==`confirm_github_tool`)continue;let e=s2(t.confirmation),n=s2(e?.request),r=c2(e?.confirmationId),i=c2(e?.toolName),a=c2(e?.operation);if(!(!r||!i||!a||!n))return{confirmationId:r,toolName:i,operation:a,request:n}}return null}function $0(e){let t=e2(e)[0];if(!t)return null;let n=c2(t.userActionRequired);return!n||n===`confirm_github_tool`?null:{action:n,toolName:c2(t.toolName),message:c2(t.error)??c2(t.message)}}function e2(e){if(!e)return[];let t=[],n=new Set,r=(e,i)=>{if(i>8||e==null)return;if(typeof e==`string`){let n=c2(e);if(!n)return;let r=n7e(n);r&&c2(r.userActionRequired)&&t.push(r);return}if(typeof e!=`object`||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let t of e)r(t,i+1);return}let a=e;if(c2(a.userActionRequired)){t.push(a);return}for(let e of Object.values(a))r(e,i+1)};return r(e,0),t}function n7e(e){try{return s2(JSON.parse(e))}catch{return null}}function t2(e){switch(e){case`create_repository`:return`Create GitHub repository`;case`link_project_repository`:return`Link project repository`;case`push_branch`:return`Push Git branch`;case`create_pull_request`:return`Create pull request`;case`rerun_workflow`:return`Rerun GitHub Actions workflow`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function n2(e){return[c2(e.request.repoFullName)??(c2(e.request.owner)&&c2(e.request.name)?`${c2(e.request.owner)}/${c2(e.request.name)}`:null),c2(e.request.cwd),c2(e.request.branch),c2(e.request.title)].filter(Boolean).join(` - `)}function r2(e){switch(e){case`connect_github`:return`Connect GitHub to continue`;case`connect_cmmd`:return`Forge couldn't authorize this action`;case`start_from_authenticated_forge_session`:return`Open this thread in Forge`;case`link_project_repository`:return`Link this project to GitHub`;case`create_branch`:return`Create a branch before pushing`;case`retry_in_user_vm`:return`Retry in the project VM`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function i2(e){switch(e){case`connect_github`:return`Connect GitHub so agents can create repos, push branches, and open PRs.`;case`connect_cmmd`:return`Reconnect Forge, then retry. Your conversation is preserved.`;case`start_from_authenticated_forge_session`:return`Open it in Forge so this action uses your signed-in account.`;case`link_project_repository`:return`Link a GitHub repo to this project before pushing or opening PRs.`;case`create_branch`:return`Forge needs a branch before it can push to GitHub.`;case`retry_in_user_vm`:return`This has to run from the project's cloud VM.`;default:return`Finish the required setup, then retry.`}}function a2(e){return e.action===`connect_cmmd`?i2(e.action):e.message??i2(e.action)}function r7e(e,t){return e.action===t.action&&e.toolName===t.toolName&&e.message===t.message}function i7e(e){switch(e){case`connect_cmmd`:return`Reconnect Forge`;case`connect_github`:return`Connect GitHub`;default:return`Open Git settings`}}function a7e(e){return[`The required Forge GitHub setup has been completed by the user.`,e.toolName?`Retry the previous GitHub tool request for \`${e.toolName}\`.`:`Retry the previous GitHub tool request.`,`Continue the previous GitHub lifecycle request using Forge brokered GitHub tools only.`,"Do not use shell `gh` or direct GitHub CLI commands."].join(`
1021
- `)}function o7e(e){let t=[];for(let n of e){let e=t.at(-1);if(e&&s7e(e,n)){t[t.length-1]=c7e(e,n);continue}t.push(n)}return t}function s7e(e,t){return e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`||t.activityKind!==`tool.updated`&&t.activityKind!==`tool.completed`||e.activityKind===`tool.completed`?!1:e.collapseKey!==void 0&&e.collapseKey===t.collapseKey}function c7e(e,t){let n=l7e(e.changedFiles,t.changedFiles),r=t.detail??e.detail,i=t.command??e.command,a=t.rawCommand??e.rawCommand,o=t.toolTitle??e.toolTitle,s=t.itemType??e.itemType,c=t.requestKind??e.requestKind,l=t.collapseKey??e.collapseKey;return{...e,...t,...r?{detail:r}:{},...i?{command:i}:{},...a?{rawCommand:a}:{},...n.length>0?{changedFiles:n}:{},...o?{toolTitle:o}:{},...s?{itemType:s}:{},...c?{requestKind:c}:{},...l?{collapseKey:l}:{}}}function l7e(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function u7e(e){if(e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`)return;let t=d7e(e.toolTitle??e.label),n=e.detail?.trim()??``,r=e.itemType??``;if(t.length!==0||n.length!==0||r.length!==0)return[r,t,n].join(``)}function d7e(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}function o2(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function s2(e){return e&&typeof e==`object`?e:null}function c2(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function l2(e){let t=e.trim();if(t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)){let e=t.slice(1,-1).trim();return e.length>0?e:t}return t}function f7e(e){let t=l2(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function p7e(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`"`)||t.startsWith(`'`)){let e=t.charAt(0),n=t.indexOf(e,1);return n<=0?null:{executable:t.slice(0,n+1),rest:t.slice(n+1).trim()}}let n=t.search(/\s/);return n<0?{executable:t,rest:``}:{executable:t.slice(0,n),rest:t.slice(n).trim()}}var m7e=[{executables:[`pwsh`,`pwsh.exe`,`powershell`,`powershell.exe`],wrapperFlagPattern:/(?:^|\s)-command\s+/i},{executables:[`cmd`,`cmd.exe`],wrapperFlagPattern:/(?:^|\s)\/c\s+/i},{executables:[`bash`,`sh`,`zsh`],wrapperFlagPattern:/(?:^|\s)-(?:l)?c\s+/i}];function h7e(e){return m7e.find(t=>t.executables.includes(e))}function g7e(e,t){let n=t.exec(e);if(!n)return null;let r=e.slice(n.index+n[0].length).trim();if(r.length===0)return null;let i=l2(r);return i.length>0?i:null}function _7e(e){let t=p7e(e);if(!t||t.rest.length===0)return e;let n=f7e(t.executable);if(!n)return e;let r=h7e(n);return r?g7e(t.rest,r.wrapperFlagPattern)??e:e}function v7e(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function u2(e){let t=c2(e);if(t)return t;if(!Array.isArray(e))return null;let n=e.map(e=>c2(e)).filter(e=>e!==null);return n.length===0?null:n.map(e=>v7e(e)).join(` `)}function y7e(e){let t=u2(e);return t?_7e(t):null}function b7e(e,t){let n=u2(e);return!n||t===null||n===t?null:n}function x7e(e){let t=s2(e?.data),n=s2(t?.item),r=s2(n?.result),i=s2(n?.input),a=c2(e?.itemType),o=c2(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?f2(o).output:null];for(let e of s){let t=y7e(e);if(t)return{command:t,rawCommand:b7e(e,t)}}return{command:null,rawCommand:null}}function S7e(e){return C7e(e)??c2(e?.title)}function C7e(e){if(!e)return null;let t=s2(e.data),n=s2(t?.item),r=s2(n?.input)??s2(t?.input),i=c2(e.title),a=c2(e.itemType),o=c2(n?.name)??c2(n?.toolName)??c2(t?.name)??c2(e.toolName)??i,s=c2(e.detail),c=[o,i,a,s].filter(Boolean).join(` `).toLowerCase();if(!c.includes(`browser`)&&!c.includes(`forge-browser`))return null;switch(w7e(o,r,s)){case`open-session`:return`Opened browser session`;case`name-session`:return`Named browser session`;case`new-tab`:return d2(r)??`Opened browser tab`;case`navigate`:return d2(r)??`Navigated browser`;case`reload`:return`Reloaded page`;case`back`:return`Went back`;case`forward`:return`Went forward`;case`screenshot`:return`Captured screenshot`;case`snapshot`:return`Read DOM snapshot`;case`logs`:return`Read console logs`;case`click`:return`Clicked page`;case`type`:return`Typed text`;case`scroll`:return`Scrolled page`;case`viewport`:return`Updated viewport`;case`visibility`:return`Updated browser visibility`;default:return null}}function w7e(e,t,n){let r=[c2(t?.type)??c2(t?.command),e,n].filter(Boolean).join(` `).toLowerCase();return/\b(open[-_.\s]?session|create[-_.\s]?session|session[-_.\s]?open)\b/.test(r)?`open-session`:/\b(name[-_.\s]?session|session[-_.\s]?name)\b/.test(r)?`name-session`:/\b(new[-_.\s]?tab|create[-_.\s]?tab|open[-_.\s]?tab)\b/.test(r)?`new-tab`:/\b(navigate|goto|go[-_.\s]?to)\b/.test(r)?`navigate`:/\breload\b/.test(r)?`reload`:/\b(go[-_.\s]?back|back)\b/.test(r)?`back`:/\b(go[-_.\s]?forward|forward)\b/.test(r)?`forward`:/\b(screenshot|capture)\b/.test(r)?`screenshot`:/\b(snapshot|dom[-_.\s]?snapshot|read[-_.\s]?dom)\b/.test(r)?`snapshot`:/\b(console[-_.\s]?logs?|logs?)\b/.test(r)?`logs`:/\bclick\b/.test(r)?`click`:/\btype|fill\b/.test(r)?`type`:/\bscroll\b/.test(r)?`scroll`:/\bviewport\b/.test(r)?`viewport`:/\bvisibility|visible|hidden\b/.test(r)?`visibility`:null}function d2(e){let t=c2(e?.url)??c2(e?.initialUrl);if(!t)return null;try{let e=new URL(t);return e.hostname.length===0?null:`Navigated to ${e.hostname}`}catch{return null}}function f2(e){let t=e.trim(),n=/^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(t);if(!n?.groups)return{output:t.length>0?t:null};let r=Number.parseInt(n.groups.code??``,10),i=n.groups.output?.trim()??``;return{output:i.length>0?i:null,...Number.isInteger(r)?{exitCode:r}:{}}}function T7e(e){if(typeof e?.itemType==`string`&&Lte(e.itemType))return e.itemType}function E7e(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:X0(e?.requestType)??void 0}function p2(e,t,n){let r=c2(n);!r||t.has(r)||(t.add(r),e.push(r))}function m2(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(m2(i,t,n,r+1),t.length>=12)return;return}let i=s2(e);if(i){p2(t,n,i.path),p2(t,n,i.filePath),p2(t,n,i.relativePath),p2(t,n,i.filename),p2(t,n,i.newPath),p2(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(m2(i[e],t,n,r+1),t.length>=12))return}}function D7e(e){let t=[],n=new Set;return m2(s2(e?.data),t,n,0),t}function h2(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;let n=e.createdAt.localeCompare(t.createdAt);if(n!==0)return n;let r=g2(e.kind)-g2(t.kind);return r===0?e.id.localeCompare(t.id):r}function g2(e){return e.endsWith(`.started`)||e===`tool.started`?0:e.endsWith(`.progress`)||e.endsWith(`.updated`)?1:e.endsWith(`.completed`)||e.endsWith(`.resolved`)?2:1}function O7e(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}function k7e(e,t,n){let r=e.map(e=>({id:e.id,kind:`message`,createdAt:e.createdAt,message:e})),i=t.map(e=>({id:e.id,kind:`proposed-plan`,createdAt:e.createdAt,proposedPlan:e})),a=n.map(e=>({id:e.id,kind:`work`,createdAt:e.createdAt,entry:e})),o=e.flatMap(e=>{if(e.role!==`assistant`)return[];let t=A7e(e.text,{workEntries:n,createdAt:e.createdAt});return t?[{id:`${e.id}:github-confirmation:${t.confirmationId}`,kind:`work`,createdAt:e.createdAt,entry:{id:`${e.id}:github-confirmation:${t.confirmationId}`,createdAt:e.createdAt,label:`GitHub action needs approval`,detail:n2(t),tone:`approval`,toolTitle:t2(t.operation),githubConfirmation:t}}]:[]});return[...r,...i,...a,...o].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function A7e(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=P7e(e,/\b(?:New confirmation id|Confirmation id):\s*`?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})`?/i)??null,r=/\bRepo(?: to create)?:\s*(private|public|internal)\s+`?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)`?/i.exec(e);if(!n)return null;let i=j7e(e,n,t);if(i)return i;if(!r)return null;let a=r[1]?.toLowerCase(),o=r[2],s=r[3];return!o||!s?null:{confirmationId:n,toolName:`forge_github_create_repository`,operation:`create_repository`,request:{owner:o,name:s,visibility:a}}}function j7e(e,t,n){if(!M7e(e))return null;let r=N7e(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?c2(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function M7e(e){return/\bforge_github_refresh_credentials\b/i.test(e)||/\bcredential refresh\b/i.test(e)||/\brefresh(?:ing)? GitHub credentials\b/i.test(e)}function N7e(e,t,n){for(let r of e.toReversed()){if(t!==void 0&&r.createdAt>t)continue;let e=r.githubConfirmation;if(e?.toolName===n)return e}return null}function P7e(e,t){return t.exec(e)?.[1]??null}function F7e(e,t){if(!t?.startedAt||!t.completedAt)return null;if(t.assistantMessageId){let n=e.find(e=>e.kind===`message`&&e.message.role===`assistant`&&e.message.id===t.assistantMessageId);if(n)return n.id}let n=Date.parse(t.startedAt),r=Date.parse(t.completedAt);if(Number.isNaN(n)||Number.isNaN(r))return null;let i=null,a=null;for(let t of e){if(t.kind!==`message`||t.message.role!==`assistant`)continue;let e=Date.parse(t.message.createdAt);Number.isNaN(e)||e<n||(a=t.id,e<=r&&(i=t.id))}return i??a}function I7e(e){let t=[...e].toSorted((e,t)=>e.completedAt.localeCompare(t.completedAt)),n={};for(let e=0;e<t.length;e+=1){let r=t[e];r&&(n[r.turnId]=e+1)}return n}function L7e(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function R7e(e,t){if(t===`disconnected`||t===`connecting`)return null;for(let t of e.toReversed())if(t.kind===`work`&&t.entry.githubConfirmation)return t.entry.githubConfirmation;return null}var _2=[`preview`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`pull-request`],v2={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function y2(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function z7e(e,t,n,r=`execution-intent`){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n,readPolicy:r}}function b2(e){let t=[e.provider,e.environmentId,e.repositoryLinkId??``,e.projectId,e.host.toLowerCase(),e.repository,String(e.number)].map(e=>encodeURIComponent(e)).join(`:`);return{...e,id:`pull-request:${t}`,kind:`pull-request`}}function x2(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var B7e=`workspace:pull-requests`;function S2(e){return typeof e==`object`&&!!e}function V7e(e){return typeof e==`string`&&_2.includes(e)}function C2(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function H7e(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function U7e(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:C2(e.revealLine),revealRequestId:H7e(e.revealRequestId),readPolicy:e.readPolicy===`connected-only`?`connected-only`:`execution-intent`}}function W7e(e){let t=e.resourceId;return t==null?{id:`browser:new`,kind:`preview`,resourceId:null}:typeof t!=`string`||t.length===0?null:{id:`browser:${t}`,kind:`preview`,resourceId:t}}function G7e(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?gn.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var K7e=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function w2(e){return typeof e==`string`&&e.length>0}function T2(e){return e===null||typeof e==`string`}function q7e(e){return e===void 0||T2(e)}function J7e(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=C2(e.number),c=e.title;return![w2(t)&&K7e.has(t),w2(n),T2(r),w2(i),w2(a),w2(o),s!==null,q7e(c)].every(Boolean)||!w2(t)||!w2(n)?null:b2({provider:t,environmentId:an.make(n),repositoryLinkId:r,projectId:tn.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function Y7e(e){if(!S2(e)||!V7e(e.kind))return null;let t=e.kind;return t===`file`?U7e(e):t===`preview`?W7e(e):t===`diff`?G7e(e):t===`pull-request`?J7e(e):{id:t,kind:t}}function X7e(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=Y7e(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function Z7e(e){if(!S2(e))return null;let t=X7e(e.surfaces);if(t.length===0)return null;let n=e.activeSurfaceId,r=t.some(e=>e.id===n),i=typeof n==`string`&&r?n:t[0]?.id??null;return{isOpen:e.isOpen===!0,activeSurfaceId:i,surfaces:t}}function Q7e(e){if(!S2(e)||!S2(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===B7e)continue;let e=Z7e(r);e&&(t[n]=e)}return{byThreadKey:t}}var $7e=`forge:right-panel-state`,e9e=3,t9e=e=>e===`workspace:pull-requests`;function n9e(e){return`draft:${e}`}function r9e(e){return e.startsWith(`draft:`)}function i9e(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var E2=(e,t,n=!0)=>({...e,isOpen:!0,surfaces:e.surfaces.some(e=>e.id===t.id)?e.surfaces:[...e.surfaces,t],activeSurfaceId:n?t.id:e.activeSurfaceId}),D2=(e,t,n)=>{let r=e[t]??v2,i=n(r);if(!i.isOpen&&i.activeSurfaceId===null&&i.surfaces.length===0){if(!(t in e))return e;let{[t]:n,...r}=e;return r}return i===r?e:{...e,[t]:i}},a9e=Xt()(wJ(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>E2(e,e.surfaces.find(e=>e.kind===n)??x2(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return E2({...e,surfaces:t},y2(n))})})),revealBrowser:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>E2(e,e.surfaces.find(e=>e.kind===`preview`)??y2(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t={id:`diff`,kind:`diff`,turnId:n??null,filePath:n?r??null:null};return{...e,isOpen:!0,activeSurfaceId:t.id,surfaces:e.surfaces.some(e=>e.id===`diff`)?e.surfaces.map(e=>e.id===`diff`?t:e):[...e.surfaces,t]}})})),openFile:(t,n,r,i=`execution-intent`)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t=`file:${n}`,a=e.surfaces.find(e=>e.id===t&&e.kind===`file`),o=z7e(n,i9e(r),(a?.revealRequestId??0)+1,i);return{...e,isOpen:!0,activeSurfaceId:o.id,surfaces:a?e.surfaces.map(e=>e.id===o.id?o:e):[...e.surfaces,o]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>E2(e,b2(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0)return e;let r=e.surfaces.filter(e=>e.id!==n);if(e.activeSurfaceId!==n)return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r};let i=r[Math.min(t,r.length-1)]??null;return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r,activeSurfaceId:i?.id??null}})})),closeOtherSurfaces:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t=e.surfaces.find(e=>e.id===n);return!t||e.surfaces.length===1?e:{...e,isOpen:!0,surfaces:[t],activeSurfaceId:t.id}})})),closeSurfacesToRight:(t,n)=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0||t===e.surfaces.length-1)return e;let r=e.surfaces.slice(0,t+1),i=r.some(t=>t.id===e.activeSurfaceId);return{...e,surfaces:r,activeSurfaceId:i?e.activeSurfaceId:n}})})),closeAllSurfaces:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,()=>v2)})),show:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:D2(e.byThreadKey,t,e=>e.isOpen?{...e,isMaximized:!(e.isMaximized??!1)}:e)})),removeThread:t=>e(e=>{if(!(t in e.byThreadKey))return e;let{[t]:n,...r}=e.byThreadKey;return{byThreadKey:r}})}),{name:$7e,version:e9e,storage:SJ(()=>NJ),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!r9e(e)&&!t9e(e)))}),migrate:e=>Q7e(e)}));function o9e(e){return t=>e?Qq(t,e.environmentId).projectById[e.projectId]:void 0}function O2(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=Qq(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=yq(o,a.threadId),r)}}function s9e(e){return O2(()=>e)}function c9e(e){return t=>{if(e)return Qq(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function l9e(e){let t,n,r,i;return a=>{if(!e){i=void 0,t=void 0,n=void 0,r=void 0;return}let o=Qq(a,e.environmentId).threadShellById,s=o[e.threadId];if(!s){i=void 0,t=void 0,n=void 0,r=void 0;return}let c=s.kind===`master`?s.id:s.parentThreadId,l=c==null?void 0:o[c];if(i&&t===o&&n===s&&r===l)return i;let u=[];if(c!=null){for(let e of Object.values(o))e.kind===`worker`&&e.parentThreadId===c&&u.push(e);u.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}return t=o,n=s,r=l,i={you:s,master:l,workers:u},i}}function u9e(e){return O2(t=>{if(!e)return;let n,r,i;for(let[a,o]of Object.entries(t.environmentStateById))if(o.threadShellById[e]){let s={environmentId:a,threadId:e};if(n??=s,t.activeEnvironmentId===a&&(r=s),o.bootstrapComplete&&(i=s,t.activeEnvironmentId===a))break}return i??r??n})}var d9e=/https?:\/\/[^\s"'`<>]+/g,f9e=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,p9e=/[.,;!?]+$/;function m9e(e){let t=e.replace(p9e,``);if(t.length===0)return t;let n=(e,n)=>{for(;t.endsWith(n);){if(t.split(e).length-1>=t.split(n).length-1)return;t=t.slice(0,-1)}};return n(`(`,`)`),n(`[`,`]`),n(`{`,`}`),t}function h9e(e,t){return e.start<t.end&&t.start<e.end}function k2(e,t,n,r){let i=[];n.lastIndex=0;for(let a of e.matchAll(n)){let e=a[0],n=a.index??-1;if(n<0||e.length===0)continue;let o=m9e(e);if(o.length===0||t===`path`&&/^https?:\/\//i.test(o))continue;let s={kind:t,text:o,start:n,end:n+o.length};[...r,...i].some(e=>h9e(s,e))||i.push(s)}return i}function A2(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function g9e(e){return e.startsWith(`/`)||A2(e)}function j2(e){return A2(e)||/[A-Za-z]:\\/.test(e)}function M2(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function _9e(e){let t=e.match(/^\/Users\/([^/]+)/);if(t?.[1])return`/Users/${t[1]}`;let n=e.match(/^\/home\/([^/]+)/);if(n?.[1])return`/home/${n[1]}`;let r=e.match(/^([A-Za-z]:\\Users\\[^\\]+)/);if(r?.[1])return r[1]}function N2(e){let t=e,n,r,i=t.match(/:(\d+)$/);if(!i?.[1])return{path:t,line:void 0,column:void 0};n=i[1],t=t.slice(0,-i[0].length);let a=t.match(/:(\d+)$/);return a?.[1]?(r=a[1],t=t.slice(0,-a[0].length)):(r=n,n=void 0),{path:t,line:r,column:n}}function v9e(e){let t=k2(e,`url`,d9e,[]),n=k2(e,`path`,f9e,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function y9e(e,t){let n=t(e-1);if(!n)return null;let r=e,i=n;for(;r>1&&i.isWrapped;){let e=t(r-2);if(!e)return null;--r,i=e}let a=[],o=0,s=r;for(;;){let e=t(s-1);if(!e)break;let n=t(s)?.isWrapped===!0,r=e.translateToString(!n);if(a.push({bufferLineNumber:s,text:r,startIndex:o,endIndex:o+r.length}),o+=r.length,!n)break;s+=1}return{text:a.map(e=>e.text).join(``),segments:a}}function P2(e,t){for(let n of e)if(t<n.endIndex)return{x:t-n.startIndex+1,y:n.bufferLineNumber};let n=e[e.length-1];return{x:Math.max(n?.text.length??0,1),y:n?.bufferLineNumber??1}}function b9e(e,t){return{start:P2(e.segments,t.start),end:P2(e.segments,t.end-1)}}function x9e(e,t){return e.start.y<=t&&t<=e.end.y}function S9e(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:xte(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function C9e(e,t){let{path:n,line:r,column:i}=N2(e),a=n;if(n.startsWith(`~/`)){let e=_9e(t);if(e){let t=j2(e)?`\\`:`/`;a=M2(e,n.slice(2),t)}}else g9e(n)||(a=M2(t,n,j2(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var F2=`diffs-container`,w9e=(()=>{try{return!1}catch{return!1}})(),T9e=/(?=^From [a-f0-9]+ .+$)/m,E9e=/(?=^diff --git)/gm,D9e=/(?<=\n)/,O9e=/^(---|\+\+\+)\s+([^\t\r\n]+)/,k9e=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,A9e=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,j9e=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,I2=`header-prefix`,L2=`header-filename-suffix`,R2=`header-metadata`,z2=`header-custom`,B2={dark:`pierre-dark`,light:`pierre-light`},M9e=`data-theme-css`,N9e=`data-unsafe-css`,P9e=`data-diffs-scrollbar-measure`,F9e=`data-diffs-code-view-header`,I9e=`data-diffs-code-view-footer`,V2=`--diffs-scrollbar-gutter-measured`,L9e=1e5,H2={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},R9e={...H2,hunkLineCount:1},z9e={paddingTop:8,paddingBottom:8,gap:8},B9e={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},V9e=Object.freeze({fromStart:0,fromEnd:0}),H9e={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},U9e={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},U2=new Set,W2=null;function G2(e){U2.add(e),W2??=requestAnimationFrame(q2)}function K2(e){U2.delete(e)&&U2.size===0&&W2!=null&&(cancelAnimationFrame(W2),W2=null)}function q2(e){let t=new Set(U2);U2.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}W2=U2.size>0?requestAnimationFrame(q2):null}function J2(e,t,n){if(e===t||e==null||t==null)return e===t;let r=new Set(n),i=Object.keys(e),a=new Set(Object.keys(t));for(let n of i)if(a.delete(n),!r.has(n)&&(!(n in t)||e[n]!==t[n]))return!1;for(let e of Array.from(a))if(!r.has(e))return!1;return!0}function Y2(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function W9e(e,t){let n=e?.theme??B2,r=t?.theme??B2,i=X2(e),a=X2(t);return Y2(n,r)&&J2(e,t,[`theme`,`parseDiffOptions`])&&J2(i,a)}function X2(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function Z2(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function G9e({scrollTop:e,scrollHeight:t,height:n,fitPerfectly:r=!1,fitPerfectlyOverscroll:i=0,overscrollSize:a}){let o=n+a*2,s=r?n+i*2:o;if(t=Math.max(t,s),o>=t||r){let n=Math.max(e-i,0),r=Math.min(e+s,t);return{top:n,bottom:Math.max(r,n)}}let c=e+n/2-o/2,l=c+o;return c<0&&(c=0),l>t&&(l=t),c=Math.floor(Math.max(c,0)),{top:c,bottom:Math.ceil(Math.max(Math.min(l,t),c))}}function Q2(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function $2(e,t){return e-(t===0?0:1)}function e4(e,t){return $2(e,t)+t}var t4=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},K9e=new class extends t4{};function q9e(e,t,n){return K9e.diff(e,t,n)}function n4(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function r4(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function i4(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function a4(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function o4(e,t){return i4(e,t,``)}function s4(e,t){return a4(e,t,``)}function c4(e,t){return t.slice(0,J9e(e,t))}function J9e(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function l4(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function u4(e,t){if(t)return f4(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function d4(e,t){if(t)return f4(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function f4(e,t){if(!t)return[d4(e),u4(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=l4(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var p4=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Y9e=RegExp(`[${p4}]+|\\s+|[^${p4}]`,`ug`);new class extends t4{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=l4(e,r)}else n=e.match(Y9e)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&m4(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&m4(n,i,r,null,t.intlSegmenter),e}};function m4(e,t,n,r,i){if(t&&n){let[a,o]=f4(t.value,i),[s,c]=f4(n.value,i);if(e){let r=n4(a,s);e.value=a4(e.value,s,r),t.value=o4(t.value,r),n.value=o4(n.value,r)}if(r){let e=r4(o,c);r.value=i4(r.value,c,e),t.value=s4(t.value,e),n.value=s4(n.value,e)}}else if(n){if(e){let e=d4(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=d4(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=d4(r.value,i),[a,o]=f4(t.value,i),s=n4(n,a);t.value=o4(t.value,s);let c=r4(o4(n,s),o);t.value=s4(t.value,c),r.value=i4(r.value,n,c),e.value=a4(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=d4(r.value,i),n=c4(u4(t.value,i),e);t.value=s4(t.value,n)}else if(e){let n=c4(u4(e.value,i),d4(t.value,i));t.value=o4(t.value,n)}}var X9e=new class extends t4{tokenize(e){let t=RegExp(`(\\r?\\n)|[${p4}]+|[^\\S\\n\\r]+|[^${p4}]`,`ug`);return e.match(t)||[]}};function Z9e(e,t,n){return X9e.diff(e,t,n)}var Q9e=new class extends t4{constructor(){super(...arguments),this.tokenize=g4}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
1019
+ `)}}}var B$e=(e=`/api/workspace/readiness`)=>{if(typeof fetch>`u`)return{close:()=>{}};let t=typeof e==`string`?{url:e}:e,n=!1,r=new AbortController;return fetch(t.url,{credentials:t.bearerToken?`omit`:`include`,signal:r.signal,...t.bearerToken?{headers:{Authorization:`Bearer ${t.bearerToken}`}}:{}}).then(e=>{if(e.ok)return z$e(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},V$e=6e4;function H$e(e){let t=new URL(e.target.httpBaseUrl);return t.pathname=`${t.pathname.endsWith(`/`)?t.pathname.slice(0,-1):t.pathname}/api/workspace/readiness`,t.search=``,t.hash=``,t.toString()}function U$e(e){let t=new Set,n=null,r=!1,i=!1;return{hasWaiters:()=>t.size>0,wait:()=>{if(r)return Promise.reject(n);if(i)return Promise.resolve();let a=null,o=null,s=new Promise((e,n)=>{o={resolve:e,reject:n},t.add(o)}),c=new Promise((t,n)=>{a=globalThis.setTimeout(()=>{n(Error(`Timed out while waiting for ${e.label} (${e.environmentId}) to stream its shell snapshot.`))},e.timeoutMs)});return Promise.race([s,c]).finally(()=>{a!==null&&globalThis.clearTimeout(a),o!==null&&t.delete(o)})},resolve:()=>{r=!1,n=null,i=!0;let e=[...t];t.clear();for(let t of e)t.resolve()},reject:e=>{r=!0,n=e,i=!1;let a=[...t];t.clear();for(let t of a)t.reject(e)},reset:()=>{r=!1,n=null,i=!1}}}function KX(e){let t=e.knownEnvironment.environmentId;if(!t)throw Error(`Known environment ${e.knownEnvironment.label} is missing its environmentId.`);let n=!1,r=!1,i=null,a=null,o=U$e({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??V$e}),s=e.readiness?(e.readiness.openStream??B$e)({url:H$e(e.knownEnvironment),environmentId:t,...e.readiness.bearerToken?{bearerToken:e.readiness.bearerToken}:{}}):null,c=t=>{if(!r){r=!0;let n=Error(t);_(),e.client.dispose(),e.onIdentityMismatch?.(n)}return!1},l=(n,r)=>{if(e.tolerateReportedEnvironmentIdentity)return a===null?(a=n,!0):a===n||c(`Environment connection ${t} reported a changed runtime identity (${a} -> ${n}) via ${r}.`);let i=e.resolveEnvironmentId?.()??t;return i===n||c(`Environment connection ${i} changed identity to ${n} via ${r}.`)},u=()=>e.resolveEnvironmentId?.()??t,d=e.client.server.subscribeLifecycle(t=>{t.type===`welcome`&&l(t.payload.environment.environmentId,`server lifecycle welcome`)&&e.onWelcome?.(t.payload,u())}),f=e.client.server.subscribeConfig(t=>{if(t.type===`snapshot`){if(!l(t.config.environment.environmentId,`server config snapshot`))return;i=t.config,e.onConfigSnapshot?.(t.config);return}if(t.type!==`providerStatuses`||!i)return;let n={...i,providers:t.payload.providers};i=n,e.onConfigSnapshot?.(n)}),p=e.client.orchestration.subscribeShell(t=>{if(t.kind===`snapshot`){e.syncShellSnapshot(t.snapshot,u()),o.resolve();return}e.applyShellEvent(t,u())},{onResubscribe:()=>{n||o.reset()},onError:t=>{if(!n){if(o.hasWaiters()){o.reject(t);return}e.onShellSubscriptionError?.(t,u())}}}),m=e.client.terminal.onEvent(t=>{e.applyTerminalEvent(t,u())}),h=e.client.browser?.onEvent({},t=>{e.applyBrowserEvent(t,u())}),g=e.client.server.subscribeWorkspaceReadiness(e=>{n||N(async()=>{let{setWorkspaceReadinessPhaseForEnvironment:e}=await import(`./workspaceReadinessAtom-D6bgTvKb.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([3,1,4,5])).then(({setWorkspaceReadinessPhaseForEnvironment:t})=>{n||t(u(),e)})}),_=()=>{n||(n=!0,e.onDispose?.(),s?.close(),p(),m(),h?.(),d(),f(),g())};return{kind:e.kind,environmentId:t,knownEnvironment:e.knownEnvironment,client:e.client,ensureBootstrapped:()=>o.wait(),reconnect:async()=>{o.reset();try{await e.client.reconnect(),await e.refreshMetadata?.(),await o.wait()}catch(e){throw o.reject(e),e}},...e.ensureProviderAuthority?{ensureProviderAuthority:e.ensureProviderAuthority}:{},dispose:async()=>{_(),await e.client.dispose()}}}function W$e(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var G$e=3e4,K$e=1e4,q$e=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,qX=/https?:\/\/[^\s"'`<>]+/gu,J$e=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),Y$e=/(https?:\/\/(?:localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|192\.168(?:\.\d{1,3}){2}):)\s+(\d{1,5})(?=[/?#\s]|$)/giu;function JX(e){let t=e.trim();if(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t))return null;let n=t.split(/[/:?#]/,1)[0]??``,r=q$e.test(t)||XX(n)?`http`:`https`,i=/^https?:\/\//i.test(t)?t:`${r}://${t}`;try{let e=new URL(i);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function X$e(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function YX(e){try{let t=new URL(e);return Dne(t.hostname)}catch{return!1}}function XX(e){return Tne(e)}function ZX(e){try{let t=new URL(e);if(t.protocol!==`http:`||!YX(t.toString())&&!XX(t.hostname)||!t.port)return null;let n=Number(t.port);return Number.isInteger(n)&&n>0&&n<=65535?n:null}catch{return null}}function Z$e(e){let t=e.replace(/[.,;!?]+$/u,``);for(;t.endsWith(`)`)||t.endsWith(`]`)||t.endsWith(`}`);){let e=t.at(-1);if(!e)break;let n=e===`)`?`(`:e===`]`?`[`:`{`;if(t.split(n).length-1>=t.split(e).length-1)break;t=t.slice(0,-1)}return t}function Q$e(e){return e.replace(J$e,``).replaceAll(/./gsu,e=>$$e(e)?``:e).replace(Y$e,`$1$2`)}function $$e(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function QX(e){let t=null,n=null,r=Q$e(e);qX.lastIndex=0;for(let e of r.matchAll(qX)){let r=JX(Z$e(e[0]));!r||!ZX(r)||(t=r,YX(r)&&(n=r))}return n??t}function e1e(e){let t=null;for(let n of e){let e=n.event,r=QX(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function t1e(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var n1e=`forge:terminal-state:v1`,$X=[],r1e=200,eZ=8;function i1e(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:uZ(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!Wo(e)&&typeof t?.url==`string`&&!!ZX(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function a1e(){return kJ(typeof window<`u`?window.localStorage:void 0)}function o1e(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[mJ]}function s1e(e,t){if(e.length===0)return[];let n=new Set(t);return[...new Set(e)].map(e=>e.trim()).filter(e=>e.length>0&&n.has(e))}function tZ(e){return`group-${e}`}function nZ(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}-${r}`,r+=1;return t.add(n),n}function rZ(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function c1e(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function l1e(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=c1e(t.terminalIds).filter(e=>!(!n.has(e)||r.has(e)));if(e.length===0)continue;for(let t of e)r.add(t);let o=t.id.trim().length>0?t.id.trim():tZ(e[0]??`default`);i.push({id:nZ(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:nZ(tZ(e),a),terminalIds:[e]});return i.length===0?[{id:tZ(mJ),terminalIds:[mJ]}]:i}function iZ(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function u1e(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||!iZ(r.terminalIds,i.terminalIds))return!1}return!0}function aZ(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&iZ(e.terminalIds,t.terminalIds)&&iZ(e.runningTerminalIds,t.runningTerminalIds)&&u1e(e.terminalGroups,t.terminalGroups)}var oZ=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[mJ],runningTerminalIds:[],activeTerminalId:mJ,terminalGroups:[{id:tZ(mJ),terminalIds:[mJ]}],activeTerminalGroupId:tZ(mJ)});function sZ(){return{...oZ,terminalIds:[...oZ.terminalIds],runningTerminalIds:[...oZ.runningTerminalIds],terminalGroups:vZ(oZ.terminalGroups)}}function cZ(){return oZ}function lZ(e){let t=o1e(e.terminalIds),n=t.length>0?t:[mJ],r=s1e(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=l1e(e.terminalGroups,n),o=a.some(t=>t.id===e.activeTerminalGroupId)?e.activeTerminalGroupId:null,s=a.find(e=>e.terminalIds.includes(i))?.id??null,c={terminalOpen:e.terminalOpen,terminalHeight:Number.isFinite(e.terminalHeight)&&e.terminalHeight>0?e.terminalHeight:280,terminalIds:n,runningTerminalIds:r,activeTerminalId:i,terminalGroups:a,activeTerminalGroupId:o??s??a[0]?.id??tZ(`default`)};return aZ(e,c)?e:c}function d1e(e){let t=lZ(e);if(t.terminalIds.length<=eZ)return t;let n=new Set,r=e=>{!e||n.size>=eZ||t.terminalIds.includes(e)&&n.add(e)};r(mJ),r(t.activeTerminalId);for(let e of t.runningTerminalIds)r(e);for(let e of t.terminalIds.toReversed())r(e);let i=t.terminalIds.filter(e=>n.has(e)),a=i[i.length-1]??i[0]??`default`,o=i.includes(t.activeTerminalId)?t.activeTerminalId:a;return lZ({...t,terminalIds:i.length>0?i:[mJ],runningTerminalIds:t.runningTerminalIds.filter(e=>n.has(e)),activeTerminalId:o,terminalGroups:t.terminalGroups.map(e=>({id:e.id,terminalIds:e.terminalIds.filter(e=>n.has(e))})).filter(e=>e.terminalIds.length>0)})}function uZ(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>Wo(e)?[[e,d1e(t)]]:[]))}function f1e(e){return aZ(lZ(e),oZ)}function p1e(e){return e.trim().length>0}function dZ(e){return Vo(e)}function fZ(e,t){return`${dZ(e)}\u0000${t}`}function pZ(e,t){return fZ(e,t)}function mZ(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function hZ(e,t){let n=QX(e);return n?{url:n,observedAt:t}:null}function m1e(e){return hZ(e.history,e.updatedAt)}function gZ(e){return e.type===`output`?hZ(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?hZ(e.snapshot.history,e.snapshot.updatedAt):null}function _Z(e,t,n){if(!n)return e;let r=dZ(t),i=e[r];return i&&mZ(i.observedAt)>mZ(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function vZ(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function yZ(e,t,n,r){let i=fZ(n,r.terminalId),a=e[i]??$X,o={id:t,event:r},s=a.length>=r1e?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function bZ(e,t,n,r){let i=fZ(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function xZ(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function SZ(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function CZ(e,t){let n={...e},r=!1;for(let e of Object.keys(n))e.startsWith(`${t}\u0000`)&&(delete n[e],r=!0);return r?n:e}function h1e(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function g1e(e,t){let n=h1e(t);return e?.runtimeEnv&&e.cwd===n.cwd&&e.worktreePath===n.worktreePath&&(e.terminalId===void 0||e.terminalId===t.terminalId)?{...n,runtimeEnv:e.runtimeEnv}:n}function wZ(e,t,n){let r=lZ(e);if(!p1e(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=vZ(r.terminalGroups),s=rZ(o,t);if(s>=0&&(o[s].terminalIds=o[s].terminalIds.filter(e=>e!==t),o[s].terminalIds.length===0&&o.splice(s,1)),n===`new`){let e=new Set(o.map(e=>e.id)),n=nZ(tZ(t),e);return o.push({id:n,terminalIds:[t]}),lZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=rZ(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=nZ(tZ(r.activeTerminalId),e);o.push({id:t,terminalIds:[r.activeTerminalId]}),c=o.length-1}let l=o[c];if(!l||i&&!l.terminalIds.includes(t)&&l.terminalIds.length>=4)return r;if(!l.terminalIds.includes(t)){let e=l.terminalIds.indexOf(r.activeTerminalId);e>=0?l.terminalIds.splice(e+1,0,t):l.terminalIds.push(t)}return lZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function TZ(e,t){let n=lZ(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function _1e(e,t){let n=lZ(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function v1e(e,t){return wZ(e,t,`split`)}function EZ(e,t,n){let r=wZ(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function DZ(e,t){let n=lZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalGroups.find(e=>e.terminalIds.includes(t))?.id??n.activeTerminalGroupId;return n.activeTerminalId===t&&n.activeTerminalGroupId===r?n:{...n,activeTerminalId:t,activeTerminalGroupId:r}}function y1e(e,t){let n=lZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return sZ();let i=n.terminalIds.indexOf(t),a=n.activeTerminalId===t?r[Math.min(i,r.length-1)]??r[0]??`default`:n.activeTerminalId,o=n.terminalGroups.map(e=>({...e,terminalIds:e.terminalIds.filter(e=>e!==t)})).filter(e=>e.terminalIds.length>0),s=o.find(e=>e.terminalIds.includes(a))?.id??o[0]?.id??tZ(a);return lZ({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function OZ(e,t,n){let r=lZ(e);if(!r.terminalIds.includes(t)||n===r.runningTerminalIds.includes(t))return r;let i=new Set(r.runningTerminalIds);return n?i.add(t):i.delete(t),{...r,runningTerminalIds:[...i]}}function kZ(e,t){return!t||t.threadId.length===0?cZ():e[dZ(t)]??cZ()}function AZ(e,t,n){if(t.threadId.length===0)return e;let r=dZ(t),i=kZ(e,t),a=n(i);if(a===i)return e;if(f1e(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function b1e(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?$X:e[fZ(t,n)]??$X}function x1e(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[pZ(t,n)]??null}function S1e(e,t){if(!t||t.threadId.length===0)return[];let n=`${dZ(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function C1e(e,t){return!t||t.threadId.length===0?null:e[dZ(t)]??null}var jZ=Xt()(CJ(e=>{let t=(t,n)=>{e(e=>{let r=AZ(e.terminalStateByThreadKey,t,n);return r===e.terminalStateByThreadKey?e:{terminalStateByThreadKey:r}})};return{terminalStateByThreadKey:{},terminalLaunchContextByThreadKey:{},terminalEventEntriesByKey:{},terminalSessionSnapshotByKey:{},terminalStreamCursorByKey:{},terminalPreviewUrlByThreadKey:{},nextTerminalEventId:1,setTerminalOpen:(e,n)=>t(e,e=>TZ(e,n)),setTerminalHeight:(e,n)=>t(e,e=>_1e(e,n)),splitTerminal:(e,n)=>t(e,e=>v1e(e,n)),newTerminal:(e,n,r)=>t(e,e=>EZ(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=EZ(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=DZ(t,n)),r?.open&&(t=TZ(t,!0)),lZ(t)}),setActiveTerminal:(e,n)=>t(e,e=>DZ(e,n)),closeTerminal:(e,n)=>t(e,e=>y1e(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[dZ(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=dZ(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>OZ(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=pZ(t,n.terminalId),i=xZ(n),a=n.type===`started`||n.type===`restarted`;if(SZ(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?bZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):yZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=_Z(e.terminalPreviewUrlByThreadKey,t,gZ(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[pZ(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=dZ(t),i=pZ(t,n.terminalId),a=xZ(n),o=n.type===`started`||n.type===`restarted`;if(SZ(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=_Z(e.terminalPreviewUrlByThreadKey,t,gZ(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[pZ(t,n.terminalId)]:n.snapshot},s=AZ(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=EZ(r,n.terminalId)),t?(r=DZ(r,n.terminalId),r=TZ(r,!0)):(r=DZ(r,e.activeTerminalId),r=TZ(r,e.terminalOpen)),lZ(r)}),c={...c,[r]:g1e(c[r],n)});let d=t1e(n);d!==null&&(s=AZ(s,t,e=>OZ(e,n.terminalId,d)));let f=o&&a?bZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):yZ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),p=a?{...e.terminalStreamCursorByKey,[i]:a}:e.terminalStreamCursorByKey;return{terminalStateByThreadKey:s,terminalLaunchContextByThreadKey:c,terminalSessionSnapshotByKey:l,terminalStreamCursorByKey:p,terminalPreviewUrlByThreadKey:u,...f}}),setTerminalSessionSnapshot:(t,n)=>e(e=>({terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[pZ(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:_Z(e.terminalPreviewUrlByThreadKey,t,m1e(n))})),clearTerminalState:t=>e(e=>{let n=dZ(t),r=AZ(e.terminalStateByThreadKey,t,()=>sZ()),i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,{[n]:o,...s}=e.terminalLaunchContextByThreadKey,{[n]:c,...l}=e.terminalPreviewUrlByThreadKey,u={...e.terminalEventEntriesByKey},d=!1;for(let e of Object.keys(u))e.startsWith(`${n}\u0000`)&&(delete u[e],d=!0);let f={...e.terminalSessionSnapshotByKey},p=!1;for(let e of Object.keys(f))e.startsWith(`${n}\u0000`)&&(delete f[e],p=!0);let m=CZ(e.terminalStreamCursorByKey,n);return r===e.terminalStateByThreadKey&&!i&&!a&&!d&&!p&&m===e.terminalStreamCursorByKey?e:{terminalStateByThreadKey:r,terminalLaunchContextByThreadKey:s,terminalPreviewUrlByThreadKey:l,terminalEventEntriesByKey:u,terminalSessionSnapshotByKey:f,terminalStreamCursorByKey:m}}),removeTerminalState:t=>e(e=>{let n=dZ(t),r=e.terminalStateByThreadKey[n]!==void 0,i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,o={...e.terminalEventEntriesByKey},s=!1;for(let e of Object.keys(o))e.startsWith(`${n}\u0000`)&&(delete o[e],s=!0);let c={...e.terminalSessionSnapshotByKey},l=!1;for(let e of Object.keys(c))e.startsWith(`${n}\u0000`)&&(delete c[e],l=!0);let u=CZ(e.terminalStreamCursorByKey,n);if(!r&&!i&&!a&&!s&&!l&&u===e.terminalStreamCursorByKey)return e;let d={...e.terminalStateByThreadKey};delete d[n];let f={...e.terminalLaunchContextByThreadKey};delete f[n];let p={...e.terminalPreviewUrlByThreadKey};return delete p[n],{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:o,terminalSessionSnapshotByKey:c,terminalStreamCursorByKey:u}}),removeOrphanedTerminalStates:t=>e(e=>{let n=Object.keys(e.terminalStateByThreadKey).filter(e=>!t.has(e)),r=Object.keys(e.terminalLaunchContextByThreadKey).filter(e=>!t.has(e)),i=Object.keys(e.terminalPreviewUrlByThreadKey).filter(e=>!t.has(e)),a={...e.terminalEventEntriesByKey},o=!1;for(let e of Object.keys(a)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete a[e],o=!0)}let s={...e.terminalSessionSnapshotByKey},c=!1;for(let e of Object.keys(s)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete s[e],c=!0)}let l={...e.terminalStreamCursorByKey},u=!1;for(let e of Object.keys(l)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete l[e],u=!0)}if(n.length===0&&r.length===0&&i.length===0&&!o&&!c&&!u)return e;let d={...e.terminalStateByThreadKey};for(let e of n)delete d[e];let f={...e.terminalLaunchContextByThreadKey};for(let e of r)delete f[e];let p={...e.terminalPreviewUrlByThreadKey};for(let e of i)delete p[e];return{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:a,terminalSessionSnapshotByKey:s,terminalStreamCursorByKey:l}})}},{name:n1e,version:4,storage:xJ(a1e),migrate:i1e,partialize:e=>({terminalStateByThreadKey:uZ(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function w1e(e){return typeof e==`string`?e:typeof e==`object`&&e&&`detail`in e&&typeof e.detail==`string`?e.detail:e instanceof Error?e.message:String(e)}function T1e(e){return e.match(/blocked by policy for\s+([^.\s]+(?:\.[^.\s]+)*)\.?/i)?.[1]||(e.match(/navigation to\s+([^.\s]+(?:\.[^.\s]+)*)\s+is restricted/i)?.[1]??null)}function MZ(e){let t=w1e(e).trim()||`Unknown browser error.`,n=T1e(t);return/blocked by policy|restricted to allowed domains/i.test(t)?{title:`Browser navigation blocked`,cause:`${n??`This URL`} is not allowed by the current browser policy.`,nextAction:`Use an allowed URL or update the browser allowed-domain setting.`,technicalDetail:t}:/does not match thread|session .*not found|no active browser tab|tab .*not found/i.test(t)?{title:`Browser session is stale`,cause:`Forge no longer has a matching live browser session for this thread.`,nextAction:`Restart the browser session from the Browser options menu.`,technicalDetail:t}:/screenshot|capture|Page\.capture/i.test(t)?{title:`Browser screenshot failed`,cause:`The browser could not capture the current page frame.`,nextAction:`Reload the page, then try the screenshot again.`,technicalDetail:t}:/timed out|timeout/i.test(t)?{title:`Browser action timed out`,cause:`Forge did not receive a response from the browser runtime in time.`,nextAction:`Retry the action. If it keeps failing, restart the browser session.`,technicalDetail:t}:/runtime is not available|browser.*unavailable|not supported|disabled/i.test(t)?{title:`Browser session unavailable`,cause:`This environment does not currently expose the in-app browser runtime.`,nextAction:`Use a workspace with browser support or restart Forge after browser support is enabled.`,technicalDetail:t}:/navigate|navigation|net::|ERR_/i.test(t)?{title:`Browser navigation failed`,cause:`The browser could not load the requested page.`,nextAction:`Check the URL and network access, then try again.`,technicalDetail:t}:{title:`Browser action failed`,cause:`Forge could not complete the browser action.`,nextAction:`Retry the action. If it keeps failing, restart the browser session from the Browser options menu.`,technicalDetail:t}}function E1e(e){let t=MZ(e);return`${t.cause} ${t.nextAction}`}function D1e(e){let t=MZ(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var NZ={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function PZ(e){return Vo(e)}function O1e(e){let t=e.status===`reconnecting`&&e.reason===`network_unreachable`;return e.transport===`remote-webrtc`&&(e.status===`connected`||e.status===`connecting`||e.status===`reconnecting`)&&(e.reason!==`network_unreachable`||t)&&e.reason!==`unsupported_host`}function k1e(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function FZ(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!O1e(t.display)||!k1e(n.display)?n:{...n,display:{...t.display,viewport:n.display.viewport??n.viewport??t.display.viewport,devicePixelRatio:n.display.devicePixelRatio??t.display.devicePixelRatio,iceServers:n.display.iceServers??t.display.iceServers,reconnect:t.display.reconnect??n.display.reconnect}}}function A1e(e){let{storedSession:t,nextSession:n}=e;if(!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId)return!1;let r=n.tabs.some(e=>e.navigationStatus===`pending`),i=t.tabs.some(e=>e.navigationStatus===`complete`||e.navigationStatus===`failed`);if(!r||!i)return!1;let a=Date.parse(t.updatedAt),o=Date.parse(n.updatedAt);return Number.isNaN(a)||Number.isNaN(o)?!1:o<a}function IZ(e,t,n){return e[t]===n?e:{...e,[t]:n}}function j1e(e){switch(e.type){case`tab.updated`:return e.payload.tab.tabId;case`tab.closed`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`console.logs.ready`:case`display.iceCandidate`:case`display.metrics`:return e.payload.tabId;case`action.failed`:return e.payload.tabId??null;case`display.updated`:case`session.started`:case`session.updated`:case`session.closed`:return null}}function M1e(e,t){let n=j1e(t);return n?{...e,lastActivityByTabId:{...e.lastActivityByTabId,[n]:{actor:t.agentId?`agent`:`human`,agentId:t.agentId,browserId:t.browserId,eventType:t.type,...t.type===`action.failed`?{commandType:t.payload.commandType}:{},...t.type===`action.failed`?{message:t.payload.message}:{},createdAt:t.createdAt}}}:e}function N1e(e){switch(e.type){case`session.started`:case`session.updated`:case`tab.updated`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`display.updated`:return!0;case`session.closed`:case`tab.closed`:case`console.logs.ready`:case`action.failed`:case`display.iceCandidate`:case`display.metrics`:return!1}}function LZ(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function P1e(e,t){let n=LZ(t);return e.some(e=>LZ(e)===n)?e:[...e,t]}function F1e(e){if(e.type!==`session.closed`)return null;switch(e.payload.reason){case`idle_timeout`:return`The browser was closed after being idle. Reopen the preview to restore this thread's browser.`;case`runtime_shutdown`:return`The browser runtime shut down. Reopen the preview to restore this thread's browser.`;case`thread_archived`:case`clear_browsing_data`:case`user_closed`:case void 0:return null}}function I1e(e){let t=e.event.payload.display;return t.status===`failed`||t.status===`unsupported`?t.detail??`Browser display is unavailable.`:e.currentLastError&&/browser display/i.test(e.currentLastError)?null:e.currentLastError}function L1e(e,t){let n=e.sessionsByBrowserId[t.browserId]??(e.session?.browserId===t.browserId?e.session:null);if(!n)return!0;let r=n.sessionId===t.payload.sessionId,i=!t.sessionEpoch||!n.sessionEpoch||t.sessionEpoch===n.sessionEpoch;return r&&i}function R1e(e,t){let n=e.lastFrameSequenceByTabId[t]??0;return{acceptedSequence:n,observedSequence:e.lastObservedFrameSequenceByTabId[t]??n,...e.lastFrameStreamIdByTabId[t]?{streamId:e.lastFrameStreamIdByTabId[t]}:{},...e.lastFrameStreamGenerationByTabId[t]===void 0?{}:{streamGeneration:e.lastFrameStreamGenerationByTabId[t]},...e.lastFrameMetaByTabId[t]?.capturedAt?{acceptedCapturedAt:e.lastFrameMetaByTabId[t].capturedAt}:{},gapCount:e.frameGapCountByTabId[t]??0}}function z1e(e,t){let n=t.payload.tabId,r=Ice(R1e(e,n),{sequence:t.payload.sequence,capturedAt:t.payload.capturedAt,...t.payload.streamId?{streamId:t.payload.streamId}:{},...t.payload.streamGeneration===void 0?{}:{streamGeneration:t.payload.streamGeneration},...t.payload.keyframe===void 0?{}:{keyframe:t.payload.keyframe}});return{decision:r,observedSequence:r.state.observedSequence,frameGapCount:r.state.gapCount}}function B1e(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function V1e(e,t){let n=t.payload.tabId;return{...e,lastFrameByTabId:{...e.lastFrameByTabId,[n]:t.payload.imageDataUrl},lastFrameSequenceByTabId:{...e.lastFrameSequenceByTabId,[n]:t.payload.sequence},lastFrameStreamIdByTabId:t.payload.streamId?{...e.lastFrameStreamIdByTabId,[n]:t.payload.streamId}:e.lastFrameStreamIdByTabId,lastFrameStreamGenerationByTabId:t.payload.streamGeneration===void 0?e.lastFrameStreamGenerationByTabId:{...e.lastFrameStreamGenerationByTabId,[n]:t.payload.streamGeneration},lastFrameMetaByTabId:{...e.lastFrameMetaByTabId,[n]:{capturedAt:t.payload.capturedAt,url:t.payload.url,viewport:t.payload.viewport}},lastError:null}}function H1e(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!L1e(t,n))return i;let o=z1e(t,n);if(!o.decision.observe)return i;let s=B1e(t,n,o),c=o.decision.accept?V1e(s,n):s;return{browserStateByThreadKey:IZ(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var RZ=Xt(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=PZ(t),i=e.browserStateByThreadKey[r]??NZ,a=n?FZ({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...i,session:a,selectedBrowserId:a?.browserId??i.selectedBrowserId,sessionsByBrowserId:a?{...i.sessionsByBrowserId,[a.browserId]:a}:i.sessionsByBrowserId,lastError:a?null:i.lastError})}}),selectBrowserSession:(t,n)=>e(e=>{let r=PZ(t),i=e.browserStateByThreadKey[r]??NZ,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=PZ(t),i=N1e(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=M1e(e.browserStateByThreadKey[r]??NZ,n);switch(n.type){case`session.started`:{if(A1e({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=FZ({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:t,selectedBrowserId:a.selectedBrowserId??t.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.updated`:{let t=FZ({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:a.selectedBrowserId&&a.selectedBrowserId!==n.payload.snapshot.browserId?a.session:t,selectedBrowserId:a.selectedBrowserId??n.payload.snapshot.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.closed`:let t=a.selectedBrowserId===n.browserId||a.session?.browserId===n.browserId;return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:t?null:a.session,selectedBrowserId:t?null:a.selectedBrowserId,sessionsByBrowserId:Object.fromEntries(Object.entries(a.sessionsByBrowserId).filter(([e])=>e!==n.browserId)),lastError:F1e(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:I1e({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o=t.tabs.map(e=>e.tabId===n.payload.tab.tabId?{...n.payload.tab,isActive:e.tabId===t.activeTabId}:{...e,isActive:e.tabId===t.activeTabId}).concat(t.tabs.some(e=>e.tabId===n.payload.tab.tabId)?[]:[{...n.payload.tab,isActive:n.payload.tab.tabId===t.activeTabId}]);return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:o},lastError:null}),pendingAutoRevealKeys:i}}case`tab.closed`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return e;let i=t.tabs.filter(e=>e.tabId!==n.payload.tabId);return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:i,activeTabId:t.activeTabId===n.payload.tabId?i[0]?.tabId??null:t.activeTabId}})}}case`snapshot.ready`:return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,lastScreenshotDataUrlByTabId:{...a.lastScreenshotDataUrlByTabId,[n.payload.tabId]:n.payload.imageDataUrl},lastScreenshotMetaByTabId:{...a.lastScreenshotMetaByTabId,[n.payload.tabId]:{captureId:n.payload.captureId,capturedAt:n.payload.capturedAt,url:n.payload.url,viewport:n.payload.viewport}},lastError:null}),pendingAutoRevealKeys:i};case`frame.ready`:return H1e({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,lastConsoleLogsByTabId:{...a.lastConsoleLogsByTabId,[n.payload.tabId]:n.payload.logs},lastConsoleLogsMetaByTabId:{...a.lastConsoleLogsMetaByTabId,[n.payload.tabId]:{capturedAt:n.createdAt,tabId:n.payload.tabId,count:n.payload.logs.length}},lastError:null})};case`display.iceCandidate`:{let t=a.displayIceCandidatesByClientId[n.payload.clientId]??[];return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:P1e(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:IZ(e.browserStateByThreadKey,r,{...a,lastError:D1e(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=PZ(t);if(!(n in e.browserStateByThreadKey))return e;let{[n]:r,...i}=e.browserStateByThreadKey;return{browserStateByThreadKey:i}}),consumeAutoReveal:t=>e(e=>{if(!e.pendingAutoRevealKeys.has(t))return e;let n=new Set(e.pendingAutoRevealKeys);return n.delete(t),{pendingAutoRevealKeys:n}})}));function U1e(e,t){return t?e[PZ(t)]??null:null}var W1e={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function G1e(e){return{x:Math.max(12,Math.min(e.position.x,e.viewportWidth-e.width-12)),y:Math.max(12,Math.min(e.position.y,e.viewportHeight-e.height-12))}}function K1e(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function q1e(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}var zZ=`forge:ui-state:v1`,BZ=[`t3code:ui-state:v1`,`t3code:renderer-state:v8`,`t3code:renderer-state:v7`,`t3code:renderer-state:v6`,`t3code:renderer-state:v5`,`t3code:renderer-state:v4`,`t3code:renderer-state:v3`,`codething:renderer-state:v4`,`codething:renderer-state:v3`,`codething:renderer-state:v2`,`codething:renderer-state:v1`],VZ=`months`,J1e=new Set([`weeks`,`months`,`quarters`]);function Y1e(e){return typeof e==`string`&&J1e.has(e)?e:VZ}function HZ(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var UZ={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:VZ,projectLeadCompanion:W1e},WZ=new Set,GZ=[],KZ=new Map,qZ=!1;function X1e(){if(typeof window>`u`)return UZ;try{let e=window.localStorage.getItem(zZ);if(!e){for(let e of BZ){let t=window.localStorage.getItem(e);if(t)return JZ(JSON.parse(t)),UZ}return UZ}let t=JSON.parse(e);return JZ(t),{...UZ,projectGroupOrder:Z1e(t.projectGroupOrderKeys),threadChangedFilesExpandedById:e0e(t.threadChangedFilesExpandedById),pinnedThreadById:Q1e(t.pinnedThreadKeys),threadLinkedPrById:$1e(t.threadLinkedPrById),timelineWorkColumnWidth:HZ(t.timelineWorkColumnWidth??360),timelineScale:Y1e(t.timelineScale)}}catch{return UZ}}function Z1e(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function Q1e(e){if(!Array.isArray(e))return{};let t={};for(let n of e)typeof n==`string`&&n.length>0&&(t[n]=!0);return t}function $1e(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length!==0&&typeof r==`string`&&r.trim().length!==0&&(t[n]=r);return t}function e0e(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!r||typeof r!=`object`)continue;let e={};for(let[t,n]of Object.entries(r))t&&typeof n==`boolean`&&n===!1&&(e[t]=!1);Object.keys(e).length>0&&(t[n]=e)}return t}function JZ(e){WZ.clear(),GZ.length=0;for(let t of e.expandedProjectCwds??[])typeof t==`string`&&t.length>0&&WZ.add(t);for(let t of e.projectOrderCwds??[])typeof t==`string`&&t.length>0&&!GZ.includes(t)&&GZ.push(t)}function t0e(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=KZ.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=KZ.get(e);return t?[t]:[]}),r=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).flatMap(([e,t])=>{let n=Object.fromEntries(Object.entries(t).filter(([,e])=>e===!1));return Object.keys(n).length>0?[[e,n]]:[]}));if(window.localStorage.setItem(zZ,JSON.stringify({expandedProjectCwds:t,projectOrderCwds:n,projectGroupOrderKeys:e.projectGroupOrder,threadChangedFilesExpandedById:r,pinnedThreadKeys:Object.keys(e.pinnedThreadById).filter(t=>e.pinnedThreadById[t]),threadLinkedPrById:e.threadLinkedPrById,timelineWorkColumnWidth:e.timelineWorkColumnWidth,timelineScale:e.timelineScale})),!qZ){qZ=!0;for(let e of BZ)window.localStorage.removeItem(e)}}catch{}}var YZ=new Qt(t0e,{wait:500});function XZ(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(t[e]!==r)return!1;return!0}function ZZ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function n0e(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(!(e in t)||!XZ(r,t[e]))return!1;return!0}function r0e(e,t){let n=new Map(KZ),r=new Map([...n.entries()].map(([e,t])=>[t,e]));KZ.clear();for(let e of t)KZ.set(e.key,e.cwd);let i=n.size!==KZ.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(GZ.map((e,t)=>[e,t])),c=t.map((e,t)=>{let n=r.get(e.cwd),i=o[e.key]??(n?o[n]:void 0)??(WZ.size>0?WZ.has(e.cwd):!0);return a[e.key]=i,{id:e.key,cwd:e.cwd,incomingIndex:t}}),l=e.projectOrder.length>0?(()=>{let t=new Map(c.map(e=>[e.cwd,e.id])),r=new Set,i=[];for(let o of e.projectOrder){let e=(o in a?o:void 0)??(()=>{let e=n.get(o);return e?t.get(e):void 0})();!e||r.has(e)||(r.add(e),i.push(e))}for(let e of c)r.has(e.id)||i.push(e.id);return i})():c.map(e=>({id:e.id,incomingIndex:e.incomingIndex,orderIndex:s.get(e.cwd)??GZ.length+e.incomingIndex})).toSorted((e,t)=>{let n=e.orderIndex-t.orderIndex;return n===0?e.incomingIndex-t.incomingIndex:n}).map(e=>e.id);return XZ(e.projectExpandedById,a)&&ZZ(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function i0e(e,t){let n=new Set(t.map(e=>e.key)),r=Object.fromEntries(Object.entries(e.threadLastVisitedAtById).filter(([e])=>n.has(e)));for(let e of t)r[e.key]===void 0&&e.seedVisitedAt!==void 0&&e.seedVisitedAt.length>0&&(r[e.key]=e.seedVisitedAt);let i=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).filter(([e])=>n.has(e))),a=Object.fromEntries(Object.entries(e.pinnedThreadById).filter(([e,t])=>n.has(e)&&t)),o=Object.fromEntries(Object.entries(e.threadLinkedPrById).filter(([e])=>n.has(e)));return XZ(e.threadLastVisitedAtById,r)&&n0e(e.threadChangedFilesExpandedById,i)&&XZ(e.pinnedThreadById,a)&&XZ(e.threadLinkedPrById,o)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o}}function a0e(e,t,n){let r=n??new Date().toISOString(),i=Date.parse(r),a=e.threadLastVisitedAtById[t],o=a?Date.parse(a):NaN;return Number.isFinite(o)&&Number.isFinite(i)&&o>=i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:r}}}function o0e(e,t,n){if(!n)return e;let r=Date.parse(n);if(Number.isNaN(r))return e;let i=new Date(r-1).toISOString();return e.threadLastVisitedAtById[t]===i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:i}}}function s0e(e,t){let n=t in e.threadLastVisitedAtById,r=t in e.threadChangedFilesExpandedById,i=t in e.pinnedThreadById,a=t in e.threadLinkedPrById;if(!n&&!r&&!i&&!a)return e;let o={...e.threadLastVisitedAtById},s={...e.threadChangedFilesExpandedById},c={...e.pinnedThreadById},l={...e.threadLinkedPrById};return delete o[t],delete s[t],delete c[t],delete l[t],{...e,threadLastVisitedAtById:o,threadChangedFilesExpandedById:s,pinnedThreadById:c,threadLinkedPrById:l}}function QZ(e,t,n){if(e.pinnedThreadById[t]===!0===n)return e;if(n)return{...e,pinnedThreadById:{...e.pinnedThreadById,[t]:!0}};let r={...e.pinnedThreadById};return delete r[t],{...e,pinnedThreadById:r}}function c0e(e,t){return QZ(e,t,e.pinnedThreadById[t]!==!0)}function l0e(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function u0e(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function d0e(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}function f0e(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function p0e(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function m0e(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function h0e(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function g0e(e,t,n){if(t.length===0)return e;let r=new Set(t),i=new Set(n);if(t.every(e=>i.has(e)))return e;let a=e.projectOrder.findIndex(e=>i.has(e));if(a<0)return e;let o=[...e.projectOrder],s=[],c=0;for(let e=o.length-1;e>=0;e--)r.has(o[e])&&(s.unshift(o.splice(e,1)[0]),e<a&&c++);if(s.length===0)return e;let l=a-Math.max(0,c-1);return o.splice(l,0,...s),{...e,projectOrder:o}}function _0e(e,t){let n=[...new Set(t)],r=new Set(n),i=e.projectGroupOrder.filter(e=>r.has(e)),a=new Set(i);for(let e of n)a.has(e)||i.push(e);return ZZ(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function v0e(e,t,n){if(t===n)return e;let r=e.projectGroupOrder.indexOf(t),i=e.projectGroupOrder.indexOf(n);if(r<0||i<0)return e;let a=[...e.projectGroupOrder],[o]=a.splice(r,1);return o===void 0?e:(a.splice(i,0,o),{...e,projectGroupOrder:a})}var $Z=Xt(e=>({...X1e(),syncProjects:t=>e(e=>r0e(e,t)),syncProjectGroups:t=>e(e=>_0e(e,t)),syncThreads:t=>e(e=>i0e(e,t)),markThreadVisited:(t,n)=>e(e=>a0e(e,t,n)),markThreadUnread:(t,n)=>e(e=>o0e(e,t,n)),clearThreadUi:t=>e(e=>s0e(e,t)),setThreadPinned:(t,n)=>e(e=>QZ(e,t,n)),toggleThreadPinned:t=>e(e=>c0e(e,t)),setThreadLinkedPr:(t,n)=>e(e=>l0e(e,t,n)),clearThreadLinkedPr:t=>e(e=>u0e(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>d0e(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>p0e(e,t,n)),toggleProject:t=>e(e=>m0e(e,t)),setProjectExpanded:(t,n)=>e(e=>h0e(e,t,n)),reorderProjects:(t,n)=>e(e=>g0e(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>v0e(e,t,n)),setLastActiveProject:t=>e(e=>f0e(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:HZ(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:K1e(e.projectLeadCompanion,t)})),closeProjectLeadCompanion:()=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,open:!1}})),setProjectLeadCompanionMinimized:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,minimized:t}})),setProjectLeadCompanionDock:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,dock:t}})),setProjectLeadCompanionPosition:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,position:t}}))}));function y0e(e){$Z.getState().openProjectLeadCompanion(e)}$Z.subscribe(e=>YZ.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{YZ.flush()});var b0e=$e(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),x0e=class extends yt()(`effect/http/FetchHttpClient/RequestInit`){},S0e=Zre(rt(Jre((e,t,n,r)=>{let i=r.getRef(b0e),a=r.context.mapUnsafe.get(x0e.key)??{},o=a.headers?En(dn(a.headers),e.headers):e.headers,s=r=>Ze(Fee({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new Zn({reason:new cne({request:e,cause:t})})}),t=>Wte(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return wt(fte(e.body.stream),s)}return s(void 0)}))),C0e=cte.pipe(b,Lt(e=>{if(kn(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=lee(e.reason.response.headers[`retry-after`]).pipe(pte(Nre),m(()=>5));return rt(re(t))}return rt(re(1))})),w0e=Xe(function*(e){let t=yield*Ot(),n=at(t,Mre),r=at(t,Me),a=We(t),o=d(Ne(e.exportInterval),_ee),s,c=Kre(at(t,Bi)).pipe(Vi(Oe(Wi,!1)),Yre({schedule:C0e,times:3})),u=Cn({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(u=En(dn(e.headers),u));let f=Lre(e.url,{headers:u}),p=[],m=At(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return ct;s!==void 0&&(s=void 0);let t=p;if(e.maxBatchSize!==`disabled`){if(p.length===0)return ct;p=[]}return c.execute(Ri(f,e.body(t))).pipe(mee,jee(!1))}).pipe(Ge(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,p=[],kee(`Disabling exporter for 60 seconds`,e)):ct),l({package:`@effect/opentelemetry`,module:e.label}));return yield*Bt(r,m.pipe(Dt,ft,Wee(e.shutdownTimeout))),yield*i(o).pipe(zt(m),et,Nt(r)),{push(t){s===void 0&&(p.push(t),e.maxBatchSize!==`disabled`&&p.length>=e.maxBatchSize&&pe(a(m),r))}}}),T0e=e=>{let t=e.attributes?eQ(Object.entries(e.attributes)):[];return t.push({key:`service.name`,value:{stringValue:e.serviceName}}),e.serviceVersion&&t.push({key:`service.version`,value:{stringValue:e.serviceVersion}}),{attributes:t,droppedAttributesCount:0}},E0e=Xe(function*(e){let t={...yield*Xl(jn(jle(j,j)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*Xl(j,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*Xl(jn(j),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],T0e({serviceName:n,serviceVersion:r,attributes:t})},c),D0e=e=>{let t=e.attributes.find(e=>e.key===`service.name`);if(!t||!t.value.stringValue)throw Error(`Resource does not contain a service name`);return t.value.stringValue},eQ=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:tQ(r)});return t},tQ=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(tQ)}};switch(typeof e){case`string`:return{stringValue:e};case`bigint`:return{intValue:Number(e)};case`number`:return Number.isInteger(e)?{intValue:e}:{doubleValue:e};case`boolean`:return{boolValue:e};default:return{stringValue:Kee(e)}}},nQ=class extends yt()(`effect/observability/OtlpSerialization`){},O0e=he(nQ,{traces:e=>Dn(e),metrics:e=>Dn(e),logs:e=>Dn(e)}),k0e=Xe(function*(e){let t=yield*E0e(e.resource),n=yield*nQ,r={name:D0e(t)},i=yield*w0e({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??re(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??re(3)});function a(e){e.sampled&&i.push(M0e(e))}return xe({span(e){return j0e({...e,status:{_tag:`Started`,startTime:e.startTime},attributes:new Map,export:a})},context:e.context?function(t,n){return n.currentSpan===void 0?t[`~effect/Effect/evaluate`](n):e.context(t,n.currentSpan)}:void 0})}),A0e={_tag:`Span`,end(e,t){this.status={_tag:`Ended`,startTime:this.status.startTime,endTime:e,exit:t},this.export(this)},attribute(e,t){this.attributes.set(e,t)},event(e,t,n){this.events.push([e,t,n])},addLinks(e){this.links.push(...e)}},j0e=e=>{let t=Object.assign(Object.create(A0e),e);return t.traceId=_t(t.parent)?t.parent.value.traceId:rQ(32),t.spanId=rQ(16),t.events=[],t},rQ=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},M0e=e=>{let t=e.status,n=eQ(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?eQ(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=P0e;else if(dt(t.exit.cause))i={code:iQ.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=lte(t.exit.cause);if(i={code:iQ.Error},e.length>0){i.message=e[0].message;for(let n of e)r.push({name:`exception`,timeUnixNano:String(t.endTime),droppedAttributesCount:0,attributes:[{key:`exception.type`,value:{stringValue:n.name}},{key:`exception.message`,value:{stringValue:n.message}},{key:`exception.stacktrace`,value:{stringValue:n.stack??`No stack trace available`}}]})}}return{traceId:e.traceId,spanId:e.spanId,parentSpanId:we(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:N0e[e.kind],startTimeUnixNano:String(t.startTime),endTimeUnixNano:String(t.endTime),attributes:n,droppedAttributesCount:0,events:r,droppedEventsCount:0,status:i,links:e.links.map(e=>({traceId:e.span.traceId,spanId:e.span.spanId,attributes:eQ(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},iQ={Unset:0,Ok:1,Error:2},N0e={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},P0e={code:iQ.Ok},F0e=1e4,I0e={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":Pr?`electron`:`browser`,"service.version":dl}},L0e=De(S0e,O0e,he(Ui,()=>!0)),aQ=null,oQ=null,sQ=null,cQ=null,lQ=0,uQ=Promise.resolve(),R0e=he(Hee,xe({span(e){return aQ?.span(e)??new s(e)}}));function z0e(e={}){return e.exportIntervalMs===void 0&&cQ!==null||(uQ=uQ.finally(()=>B0e(e))),uQ}async function B0e(e){let t=or(`/api/observability/v1/traces`),n=mr()?.bearerToken,r=Math.max(10,e.exportIntervalMs??F0e),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(cQ===i&&aQ!==null)return;cQ=i;let a=++lQ,o=oQ,s=sQ;aQ=null,oQ=null,sQ=null,await dQ(o,s);let c=rl(L0e),l=c.runSync(ze());try{let e=await c.runPromise(te(l)(k0e({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:I0e})));if(a!==lQ){await dQ(c,l);return}aQ=e,oQ=c,sQ=l}catch(e){await dQ(c,l),a===lQ&&console.warn(`Failed to configure client tracing exporter`,{error:V0e(e),otlpTracesUrl:t})}}async function dQ(e,t){e!==null&&t!==null&&await e.runPromise(He(t,Tt)).catch(()=>void 0).finally(()=>{e.dispose()})}function V0e(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var fQ=15e3,pQ=new Map,mQ=Wt([]).pipe(Ut,Vt(`slow-rpc-ack-requests`));function hQ(e){Ht.set(mQ,[...e])}function gQ(){return Ht.get(mQ)}var _Q=`global`;function H0e(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)}function U0e(e,t,n=_Q){if(!H0e(t))return;bQ(e,n),q0e();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:fQ},a=yQ(n,e),o=setTimeout(()=>{pQ.delete(a),K0e(i)},fQ);pQ.set(a,{request:i,timeoutId:o})}function W0e(e,t=_Q){bQ(e,t);let n=gQ();n.some(n=>n.clientId===t&&n.requestId===e)&&hQ(n.filter(n=>n.clientId!==t||n.requestId!==e))}function vQ(e){for(let[t,n]of pQ)n.request.clientId===e&&(clearTimeout(n.timeoutId),pQ.delete(t));hQ(gQ().filter(t=>t.clientId!==e))}function G0e(){for(let e of pQ.values())clearTimeout(e.timeoutId);pQ.clear(),hQ([])}function yQ(e,t){return`${e}:${t}`}function bQ(e,t){let n=yQ(t,e),r=pQ.get(n);r&&(clearTimeout(r.timeoutId),pQ.delete(n))}function K0e(e){let t=[...gQ(),e];if(t.length<=256){hQ(t);return}hQ(t.slice(-256))}function q0e(){for(;pQ.size>=256;){let e=pQ.keys().next().value;if(e===void 0)return;let t=pQ.get(e);if(!t)return;bQ(t.request.requestId,t.request.clientId)}}function J0e(){return cr(mQ)}var Y0e=ko(Mn),xQ=1;function X0e(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function SQ(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)throw Error(`Unsupported websocket transport URL protocol: ${t.protocol}`);return t.pathname=`/ws`,t.toString()}function Z0e(){return{onAttempt:Lne,onOpen:One,onError:e=>{Ine(e)},onClose:e=>{kne(e)},trackGlobalConnection:!0}}function Q0e(e){let t=Z0e(),n=e?.trackGlobalConnection??!0;return{onAttempt:r=>{n&&t.onAttempt(r),e?.onAttempt?.(r)},onOpen:()=>{n&&t.onOpen(),e?.onOpen?.()},onError:r=>{n&&t.onError(r),e?.onError?.(r)},onClose:r=>{n&&t.onClose(r),e?.onClose?.(r)},trackGlobalConnection:n}}function $0e(e,t){let n=xQ;xQ+=1;let r=Q0e(t),i=typeof e==`function`?gt(()=>e()).pipe(Ze(e=>SQ(e)),ite(e=>pt(()=>{r.onError(X0e(e))})),c):SQ(e),a=he(oa,(e,t)=>{r.onAttempt(e);let n=new globalThis.WebSocket(e,t);return n.addEventListener(`open`,()=>{r.onOpen()},{once:!0}),n.addEventListener(`error`,()=>{r.onError(`Unable to connect to the Forge server WebSocket.`)},{once:!0}),n.addEventListener(`close`,e=>{r.onClose({code:e.code,reason:e.reason})},{once:!0}),n}),o=sa(i).pipe(E(a)),s=Lt(_(10),e=>rt(Ue(Fne(e)??0)));return ht(Mo,Ze(No({retryPolicy:s,retryTransientErrors:!0}),e=>({...e,run:(t,r)=>{let i=`${n}:${String(t)}`;return e.run(t,e=>(e._tag===`Chunk`||e._tag===`Exit`?W0e(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&vQ(i),r(e))).pipe(Je(pt(()=>{vQ(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&U0e(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(E(De(o,Oo)))}var e2e=/^all fibers interrupted without error$/i;function t2e(e){return aG(e)||e2e.test(e.trim())}var n2e=Ue(250),CQ=()=>void 0,wQ=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=Be(Ne(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},r2e=new Set([`OrchestrationGetSnapshotError`]);function i2e(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&r2e.has(t)}function a2e(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?o2e(e):String(e)}function o2e(e){try{return JSON.stringify(e)}catch{let t=e;return[typeof t._tag==`string`?t._tag:void 0,typeof t.message==`string`?t.message:void 0].filter(Boolean).join(`: `)||Object.prototype.toString.call(e)}}var s2e=4e3,c2e=1e4,l2e=500,TQ=class{url;lifecycleHandlers;disposed=!1;hasReportedTransportDisconnect=!1;reconnectChain=Promise.resolve();session;heartbeatTimer=null;heartbeatInFlight=!1;protocol;timing;constructor(e,t,n,r){this.url=e,this.lifecycleHandlers=t,this.protocol=n??null,this.timing={heartbeatIntervalMs:r?.heartbeatIntervalMs??s2e,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??c2e,sessionCloseGraceMs:r?.sessionCloseGraceMs??l2e},this.session=this.createSession(),this.startHeartbeat()}startHeartbeat(){this.heartbeatTimer===null&&(this.heartbeatTimer=setInterval(()=>{if(this.disposed||this.heartbeatInFlight)return;this.heartbeatInFlight=!0;let e=this.session;this.request(e=>e[M.serverHeartbeat]({}),{timeout:this.timing.heartbeatTimeoutMs}).catch(async()=>{this.disposed||e!==this.session||await this.reconnect()}).finally(()=>{this.heartbeatInFlight=!1})},this.timing.heartbeatIntervalMs))}async request(e,t){if(this.disposed)throw Error(`Transport disposed`);let n=this.session,i=await n.clientPromise,a=At(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(Mt({duration:o,orElse:()=>r(new wQ(o))}));return await n.runtime.runPromise(s,{signal:t?.signal})}async requestStream(e,t,n){if(this.disposed)throw Error(`Transport disposed`);let r=this.session,i=this.runStreamOnSession(r,e,t,()=>!0,()=>void 0),a=()=>i.cancel();n?.signal?.aborted&&a(),n?.signal?.addEventListener(`abort`,a,{once:!0});try{await i.completed}catch(e){if(n?.signal?.aborted){let e=Error(`RPC stream request was cancelled.`);throw e.name=`AbortError`,e}throw e}finally{n?.signal?.removeEventListener(`abort`,a)}}subscribe(e,t,n){if(this.disposed)return()=>void 0;let r={active:!0,hasReceivedValue:!1,cancelCurrentStream:CQ},i=Be(Ne(n?.retryDelay??n2e));return this.runSubscriptionLoop(e,t,n,r,i),()=>{r.active=!1,r.cancelCurrentStream()}}async runSubscriptionLoop(e,t,n,r,i){for(;r.active&&!this.disposed;){let a=this.session;try{this.notifyResubscribe(r,n);let i=this.startSubscriptionStream(a,e,t,r);r.cancelCurrentStream=i.cancel,await i.completed,r.cancelCurrentStream=CQ}catch(e){if(r.cancelCurrentStream=CQ,!await this.handleSubscriptionFailure(e,a,r,n,i))return}}}notifyResubscribe(e,t){if(e.hasReceivedValue)try{t?.onResubscribe?.()}catch{}}startSubscriptionStream(e,t,n,r){return this.runStreamOnSession(e,t,n,()=>r.active,()=>{this.hasReportedTransportDisconnect=!1,r.hasReceivedValue=!0})}async handleSubscriptionFailure(e,t,n,r,i){if(!n.active||this.disposed)return!1;if(t!==this.session)return!0;let a=a2e(e);return t2e(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await u2e(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){i2e(e)||gG(e,{route:`ws-subscribe`,reason:`non-transport-error`}),t?.onError?.(e)}async reconnect(){if(this.disposed)throw Error(`Transport disposed`);let e=this.reconnectChain.then(async()=>{if(this.disposed)throw Error(`Transport disposed`);let e=this.session;this.session=this.createSession(),await this.closeSession(e)});this.reconnectChain=e.catch(e=>{gG(e,{route:`ws-reconnect`})}),await e}async dispose(){this.disposed||(this.disposed=!0,this.heartbeatTimer!==null&&this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),await this.closeSession(this.session))}async closeSession(e){let t=e.runtime.runPromise(He(e.clientScope,Tt)),n=!1,r=null,i=new Promise(e=>{r=setTimeout(()=>{n=!0,e()},this.timing.sessionCloseGraceMs)});try{await Promise.race([t,i])}finally{r!==null&&clearTimeout(r),n&&(console.warn(`WebSocket session close exceeded its grace period; forcing disposal`,{graceMs:this.timing.sessionCloseGraceMs}),t.catch(()=>void 0)),await e.runtime.dispose()}}createSession(){let e=this.protocol??{layer:$0e(this.url,this.lifecycleHandlers),makeClient:Y0e},t=rl(De(e.layer,R0e)),n=t.runSync(ze());return{runtime:t,clientScope:n,clientPromise:t.runPromise(te(n)(e.makeClient))}}runStreamOnSession(e,t,n,r,i){let a,o,s=new Promise((e,t)=>{a=e,o=t});return{cancel:e.runtime.runCallback(gt(()=>e.clientPromise).pipe(wt(e=>Gee(t(e),e=>pt(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if(ete(e)){a();return}o(Ie(e.cause))}}),completed:s}}};function u2e(e){return new Promise(t=>{setTimeout(t,e)})}var EQ=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,d2e=/^[A-Za-z0-9_-]+$/;function f2e(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+=EQ[o>>>18&63],t+=EQ[o>>>12&63],n+1<e.byteLength&&(t+=EQ[o>>>6&63]),n+2<e.byteLength&&(t+=EQ[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function p2e(e){if(e.length===0||!d2e.test(e))throw Error(`Bulk transfer chunk is not valid base64url data.`);let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Math.floor(t.length*6/8),r=new Uint8Array(n),i=0,a=0,o=0;for(let e of t){let t=EQ.indexOf(e);if(t<0)throw Error(`Bulk transfer chunk is not valid base64url data.`);i=i<<6|t,a+=6,a>=8&&(a-=8,r[o]=i>>>a&255,o+=1)}return r}async function DQ(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=await crypto.subtle.digest(`SHA-256`,t.buffer);return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}async function m2e(e,t){let n=t?.chunkBytes??262144;if(!Number.isSafeInteger(n)||n<1||n>262144)throw Error(`Bulk transfer chunk size must be between 1 and ${Gte}.`);let r=t?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),i=[];for(let t=0;t<e.byteLength;t+=n){let a=e.slice(t,Math.min(t+n,e.byteLength));i.push({kind:`chunk`,transferId:r,offset:t,bytes:a.byteLength,data:f2e(a),sha256:await DQ(a)})}return{totalBytes:e.byteLength,sha256:await DQ(e),chunks:i}}async function h2e(e){let t=p2e(e.data);if(t.byteLength!==e.bytes)throw Error(`Bulk transfer chunk byte count mismatch at offset ${e.offset}: expected ${e.bytes}, received ${t.byteLength}.`);if(await DQ(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function g2e(e){let t=new Map,n=[],r=0;for(let i of e.chunks){let e=t.get(i.offset);if(e!==void 0){if(e.bytes!==i.bytes||e.sha256!==i.sha256||e.data!==i.data)throw Error(`Bulk transfer has a conflicting duplicate chunk at offset ${i.offset}.`);continue}if(i.offset!==r)throw Error(`Bulk transfer chunk offset mismatch: expected ${r}, received ${i.offset}.`);let a=await h2e(i);t.set(i.offset,i),n.push({chunk:i,bytes:a}),r+=a.byteLength}if(r!==e.totalBytes)throw Error(`Bulk transfer total byte count mismatch: expected ${e.totalBytes}, received ${r}.`);let i=new Uint8Array(e.totalBytes);for(let e of n)i.set(e.bytes,e.chunk.offset);if(await DQ(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var OQ=`forge`,_2e=RegExp(`^${OQ}\\/[0-9a-f]{8}$`);function v2e(){return`${OQ}/${fe(_te).replace(/-/g,``).slice(0,8).toLowerCase()}`}function y2e(e){return _2e.test(e.trim().toLowerCase())}function b2e(e){let t=e.trim().replace(/\/+$/g,``).replace(/\.git$/i,``).toLowerCase();if(/^(?:ssh|https?|git):\/\//i.test(t))try{let e=new URL(t),n=e.pathname.split(`/`).filter(e=>e.length>0).join(`/`);if(e.hostname&&n.includes(`/`))return`${e.hostname}/${n}`}catch{return t}let n=/^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(t);return n?.[1]&&n[2]?`${n[1]}/${n[2]}`:t}function x2e(e){let t=e?.trim()??``;if(t.length===0)return null;let n=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(t)?.[1]?.trim()??``;return n.length>0?n:null}function S2e(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`git@`)){let e=t.slice(4),n=e.search(/[:/]/);return n<=0?null:e.slice(0,n).toLowerCase()}try{return new URL(t).hostname.toLowerCase()}catch{return null}}function kQ(e){return`https://${e}`}function C2e(e){return e===`github.com`||e.includes(`github`)}function w2e(e){return e===`gitlab.com`||e.includes(`gitlab`)}function T2e(e){return e===`bitbucket.org`}function E2e(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function D2e(e){let t=S2e(e);if(!t)return null;let n=b2e(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?C2e(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:kQ(t)}:w2e(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:kQ(t)}:T2e(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:kQ(t)}:E2e(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:kQ(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:kQ(t)}:null}var O2e={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function AQ(e,t){return{...e,...t??O2e}}function k2e(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function A2e(e){return{isRepo:e.isRepo,...e.hostingProvider?{hostingProvider:e.hostingProvider}:{},hasOriginRemote:e.hasOriginRemote,isDefaultBranch:e.isDefaultBranch,branch:e.branch,hasWorkingTreeChanges:e.hasWorkingTreeChanges,workingTree:e.workingTree}}function j2e(e,t){switch(t._tag){case`snapshot`:return AQ(t.local,t.remote);case`localUpdated`:return AQ(t.local,e?k2e(e):null);case`remoteUpdated`:return AQ(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:A2e(e),t.remote)}}var M2e=262144,N2e=250;function P2e(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function F2e(e){return new Promise(t=>setTimeout(t,e))}function I2e(e){let t=Ace({controllerId:crypto.randomUUID(),maxPendingWriteBytes:M2e}),n=!1,r=e=>{if(!e.sessionEpoch)throw Error(`Connected Forge runtime does not support epoch-fenced terminal controls.`);t.register({threadId:e.threadId,terminalId:e.terminalId,sessionEpoch:e.sessionEpoch})},i=async e=>{for(;!n;)try{return await e()}catch(e){if(!aG(P2e(e)))throw e;await F2e(N2e)}throw Error(`Terminal control client was disposed before acknowledgement.`)};return{terminal:{open:async t=>{let n=await e.request(e=>e[M.terminalOpen]({...t,terminalId:t.terminalId??`default`}));return r(n),n},write:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,writeBytes:new TextEncoder().encode(n.data).byteLength,execute:t=>i(()=>e.request(e=>e[M.terminalWrite]({...n,terminalId:r,...t})))})},resize:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalResize]({...n,terminalId:r,...t})))})},signal:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalSignal]({...n,terminalId:r,...t})))})},clear:async n=>{let r=n.terminalId??`default`;await t.enqueue({threadId:n.threadId,terminalId:r,execute:t=>i(()=>e.request(e=>e[M.terminalClear]({...n,terminalId:r,...t})))})},restart:async n=>{let a=n.terminalId??`default`,o=null;if(await t.enqueue({threadId:n.threadId,terminalId:a,execute:async t=>{o=(await i(()=>e.request(e=>e[M.terminalRestart]({...n,terminalId:a,...t})))).snapshot}}),o===null)throw Error(`Terminal restart completed without a snapshot.`);return r(o),o},close:async n=>{let r=n.terminalId?[n.terminalId]:t.terminalIds(n.threadId);for(let a of r)await t.enqueue({threadId:n.threadId,terminalId:a,execute:t=>i(()=>e.request(e=>e[M.terminalClose]({...n,terminalId:a,...t})))}),t.remove(n.threadId,a)},onEvent:t=>e.subscribe(e=>e[M.subscribeTerminalEvents]({}),e=>{(e.type===`started`||e.type===`restarted`)&&r(e.snapshot),t(e)})},dispose:()=>{n=!0,t.dispose()}}}function L2e(e){return{createUploadUrl:t=>e.request(e=>e[M.attachmentsCreateUploadUrl](t)),delete:t=>e.request(e=>e[M.attachmentsDelete](t))}}async function R2e(e,t){await e.request(e=>e[M.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}var z2e=2e4,B2e=12e4,V2e=3e5;function H2e(e){return e instanceof wQ||aG(e instanceof Error?e.message:String(e))}async function U2e(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?V2e:z2e,r=()=>e.request(e=>e[qn.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!H2e(t))throw t;return await e.reconnect(),await r()}}function jQ(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function MQ(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>W2e(r,e,n),n),r.protocolError!==null)throw r.protocolError;let i=r.started,a=r.completed;if(i===null||a===null)throw Error(`Bulk transfer stream completed without start and completion metadata.`);if(a.transferId!==i.transferId||a.totalBytes!==i.totalBytes||a.sha256!==i.sha256)throw Error(`Bulk transfer completion metadata mismatch.`);return await g2e({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function W2e(e,t,n){if(e.protocolError===null){if(t.kind===`started`){G2e(e,t,n);return}if(e.started===null||t.transferId!==e.started.transferId){e.protocolError=Error(`Bulk transfer event identity mismatch.`);return}if(t.kind===`chunk`){K2e(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function G2e(e,t,n){if(e.started!==null||t.totalBytes>16777216){e.protocolError=Error(`Bulk transfer started with invalid or oversized metadata.`);return}e.started=t,n?.onProgress?.({completedBytes:0,totalBytes:t.totalBytes})}function K2e(e,t,n){let r=e.started;if(r!==null){if(e.receivedBytes+=t.bytes,e.receivedBytes>r.totalBytes){e.protocolError=Error(`Bulk transfer exceeded its declared byte count.`);return}e.chunks.push(t),n?.onProgress?.({completedBytes:e.receivedBytes,totalBytes:r.totalBytes})}}async function q2e(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${Jte}-byte write limit.`);let i=await m2e(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{jQ(n?.signal);let r=await J2e(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await Y2e(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await R2e(e,a),t}}function J2e(e,t,n,r){return e.request(e=>e[M.workspaceBeginWriteFile]({transferId:n,cwd:t.cwd,relativePath:t.relativePath,totalBytes:r.totalBytes,sha256:r.sha256}))}async function Y2e(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;jQ(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[M.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}jQ(i?.signal),await e.request(e=>e[M.workspaceCommitWriteFile]({transferId:t}))}}function NQ(e){let t=I2e(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{wne(),await e.reconnect()},terminal:t.terminal,browser:{openSession:t=>e.request(e=>e[M.browserOpenSession](t)),listSessions:t=>e.request(e=>e[M.browserListSessions](t)),closeSession:t=>e.request(e=>e[M.browserCloseSession](t)),getSession:t=>e.request(e=>e[M.browserGetSession](t)),command:t=>e.request(e=>e[M.browserCommand](t)),clearBrowsingData:t=>e.request(e=>e[M.browserClearBrowsingData](t)),attachDisplay:t=>e.request(e=>e[M.browserAttachDisplay](t)),addDisplayIceCandidate:t=>e.request(e=>e[M.browserAddDisplayIceCandidate](t)),onEvent:(t,n,r)=>e.subscribe(e=>e[M.subscribeBrowserEvents](t),n,r)},computer:{input:t=>e.request(e=>e[M.computerInput](t))},threadDevRuntime:{get:t=>e.request(e=>e[M.threadDevRuntimeGet](t)),allocatePort:t=>e.request(e=>e[M.threadDevRuntimeAllocatePort](t)),release:t=>e.request(e=>e[M.threadDevRuntimeRelease](t))},devTunnel:{register:t=>e.request(e=>e[M.devTunnelRegister](t)),unregister:t=>e.request(e=>e[M.devTunnelUnregister](t)),list:t=>e.request(e=>e[M.devTunnelList](t))},attachments:L2e(e),projects:{searchContents:(t,n)=>e.request(e=>e[M.projectsSearchContents](t),n),searchEntries:t=>e.request(e=>e[M.projectsSearchEntries](t)),readFile:(t,n)=>MQ(e,e=>e[M.workspaceReadFile](t),n),writeFile:(t,n)=>q2e(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[M.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[M.projectCheckoutDeletionExecute](t))},workspace:{environmentPreflight:t=>e.request(e=>e[M.workspaceEnvironmentPreflight](t)),ensureScratch:t=>e.request(e=>e[M.workspaceEnsureScratch](t))},shell:{openInEditor:t=>e.request(e=>e[M.shellOpenInEditor](t))},git:{pull:t=>e.request(e=>e[M.gitPull](t)),refreshStatus:t=>e.request(e=>e[M.gitRefreshStatus](t)),onStatus:(t,n,r)=>{let i=null;return e.subscribe(e=>e[M.subscribeGitStatus](t),e=>{i=j2e(i,e),n(i)},r)},runStackedAction:async(t,n)=>{let r=null;if(await e.requestStream(e=>e[M.gitRunStackedAction](t),e=>{n?.onProgress?.(e),e.kind===`action_finished`&&(r=e.result)}),r)return r;throw Error(`Git action stream completed without a final result.`)},listBranches:t=>e.request(e=>e[M.gitListBranches](t)),createWorktree:t=>e.request(e=>e[M.gitCreateWorktree](t)),removeWorktree:t=>e.request(e=>e[M.gitRemoveWorktree](t)),createBranch:t=>e.request(e=>e[M.gitCreateBranch](t)),checkout:t=>e.request(e=>e[M.gitCheckout](t)),init:t=>e.request(e=>e[M.gitInit](t)),resolvePullRequest:t=>e.request(e=>e[M.gitResolvePullRequest](t)),preparePullRequestThread:t=>e.request(e=>e[M.gitPreparePullRequestThread](t))},pullRequests:{list:t=>e.request(e=>e[M.pullRequestsList](t)),listStats:t=>e.request(e=>e[M.pullRequestsListStats](t)),detail:t=>e.request(e=>e[M.pullRequestsDetail](t)),activity:t=>e.request(e=>e[M.pullRequestsActivity](t)),threadComments:t=>e.request(e=>e[M.pullRequestsThreadComments](t)),diffFileContents:t=>e.request(e=>e[M.pullRequestsDiffFileContents](t)),runAction:t=>e.request(e=>e[M.pullRequestsRunAction](t)),update:t=>e.request(e=>e[M.pullRequestsUpdate](t)),comment:t=>e.request(e=>e[M.pullRequestsComment](t)),updateComment:t=>e.request(e=>e[M.pullRequestsUpdateComment](t)),submitReview:t=>e.request(e=>e[M.pullRequestsSubmitReview](t)),replyToThread:t=>e.request(e=>e[M.pullRequestsReplyToThread](t)),setThreadResolution:t=>e.request(e=>e[M.pullRequestsSetThreadResolution](t)),setReaction:t=>e.request(e=>e[M.pullRequestsSetReaction](t)),invalidate:t=>e.request(e=>e[M.pullRequestsInvalidate](t)),reviewerCandidates:t=>e.request(e=>e[M.pullRequestsReviewerCandidates](t)),requestReviewers:t=>e.request(e=>e[M.pullRequestsRequestReviewers](t))},server:{getConfig:()=>e.request(e=>e[M.serverGetConfig]({})),refreshProviders:()=>e.request(e=>e[M.serverRefreshProviders]({})),startProviderAuth:t=>e.request(e=>e[M.serverStartProviderAuth](t)),repairProviderAuthRuntime:t=>e.request(e=>e[M.serverRepairProviderAuthRuntime](t)),disconnectProviderAuth:t=>e.request(e=>e[M.serverDisconnectProviderAuth](t)),getProviderAuthSession:t=>e.request(e=>e[M.serverGetProviderAuthSession](t)),cancelProviderAuth:t=>e.request(e=>e[M.serverCancelProviderAuth](t)),submitProviderAuthCode:t=>e.request(e=>e[M.serverSubmitProviderAuthCode](t)),syncPersonalCodexToCloud:t=>e.request(e=>e[M.serverSyncPersonalCodexToCloud](t)),syncPersonalClaudeToCloud:t=>e.request(e=>e[M.serverSyncPersonalClaudeToCloud](t)),upsertKeybinding:t=>e.request(e=>e[M.serverUpsertKeybinding](t)),removeKeybinding:t=>e.request(e=>e[M.serverRemoveKeybinding](t)),getSettings:()=>e.request(e=>e[M.serverGetSettings]({})),updateSettings:t=>e.request(e=>e[M.serverUpdateSettings]({patch:t})),updateEnvironmentDisplayName:t=>e.request(e=>e[M.serverUpdateEnvironmentDisplayName](t)),getTraceDiagnostics:t=>e.request(e=>e[M.serverGetTraceDiagnostics](t)),subscribeConfig:(t,n)=>e.subscribe(e=>e[M.subscribeServerConfig]({}),t,n),subscribeLifecycle:(t,n)=>e.subscribe(e=>e[M.subscribeServerLifecycle]({}),t,n),subscribeAuthAccess:(t,n)=>e.subscribe(e=>e[M.subscribeAuthAccess]({}),t,n),subscribeWorkspaceReadiness:(t,n)=>e.subscribe(e=>e[M.subscribeWorkspaceReadiness]({}),t,n)},usage:{getSummary:t=>e.request(e=>e[M.usageGetSummary](t),{timeout:B2e})},orchestration:{dispatchCommand:t=>U2e(e,t),getTurnDiff:(t,n)=>MQ(e,e=>e[qn.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>MQ(e,e=>e[qn.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[qn.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[qn.subscribeThread](t),n,r)}}}var X2e=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function PQ(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!X2e.has(t)?null:t}function FQ(e,t){return e===401||e===403||PQ(t)!==null}function Z2e(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return FQ(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}var IQ=`forge.deviceRegistry.deviceKey`,LQ=`forge.deviceRegistry.runtimeId`;function Q2e(e){let t=BQ(IQ,e.desktopIdentity?.deviceKey,`device`),n=BQ(LQ,e.desktopIdentity?.runtimeId,`runtime`),r=zQ(e.desktopIdentity?.hostKey),i=n4e(),a=e.desktopAvailable?`desktop`:r4e(),o=e.desktopAvailable?t4e(e.desktopIdentity)??i4e(i):a4e(i);return{device:{...r?{hostKey:r}:{},deviceKey:t,displayName:o,platform:i,deviceType:a,metadata:{clientKind:e.desktopAvailable?`forge-desktop`:`forge-web`,userAgent:window.navigator.userAgent,origin:window.location.origin,...e.desktopIdentity?{desktopIdentity:{hostName:e.desktopIdentity.hostName,computerName:e.desktopIdentity.computerName,platform:e.desktopIdentity.platform}}:{}}},...e.desktopAvailable&&e.includeExecutableRuntime!==!1?{runtime:{runtimeId:n,runtimeKind:`desktop-local`,displayName:`Local Forge Desktop`,endpointUrl:e.desktopEndpointUrl??null,status:`online`,metadata:{origin:window.location.origin}}}:{}}}async function RQ(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return Q2e({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function zQ(e){let t=e?.trim()??``;return t.length>0?t:null}function BQ(e,t,n){let r=zQ(t);return r?(PJ(e,r),r):e4e(e,n)}function $2e(){return NJ(LQ)}function VQ(){return NJ(IQ)}function e4e(e,t){let n=NJ(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return PJ(e,r),r}function t4e(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function n4e(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`iphone`)||e.includes(`ipad`)?`ios`:e.includes(`android`)?`android`:e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:`unknown`}function r4e(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`ipad`)||e.includes(`tablet`)?`tablet`:e.includes(`mobi`)||e.includes(`iphone`)||e.includes(`android`)?`mobile`:`browser`}function i4e(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function a4e(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var HQ=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function UQ(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new HQ(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new HQ(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function o4e(e){let t=e.getStoredDeviceKey(),n=t?await e.apiClient.getDeviceRegistry():await e.apiClient.registerDevice(await e.buildDeviceRegistration());return t&&!n.devices.some(e=>e.deviceKey===t)&&(n=await e.apiClient.registerDevice(await e.buildDeviceRegistration())),t??=e.getStoredDeviceKey(),{deviceKey:t,registry:n}}function s4e(e){if(!e.deviceKey)throw new HQ(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface could not establish CMMD identity.`);let t=e.registry.devices.find(t=>t.deviceKey===e.deviceKey);if(t?.trustState===`revoked`||t?.authorization?.revoked===!0)throw new HQ(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new HQ(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function c4e(e,t){let n=async()=>s4e(await o4e(t));return{acquireRoute:async()=>{let r=await n(),i=await Dce();try{return kce({route:await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Un],protocolMinVersion:4,protocolMaxVersion:4,...Oce(i)}),runtimeId:e,endpoint:i})}catch(e){if(e instanceof tl)throw new HQ(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return UQ(e)}},acquireActionGrant:async r=>{let i=await n();try{return(await t.apiClient.issueRelayActionGrant(e,{controlDeviceId:i.id,controlSessionId:t.controlSessionId,...r})).token}catch(e){return UQ(e)}}}}var WQ=`forge.relayControlJournal.v1`;function GQ(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var l4e={read:()=>GQ().getItem(WQ),write:e=>GQ().setItem(WQ,e)},KQ=null,qQ=Xt()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function u4e(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));qQ.getState().replace(Object.fromEntries([...t].map(t=>[t,Vse(e.records,t)])))})}function JQ(){return KQ===null&&(KQ=zc({storage:l4e}),u4e(KQ)),KQ}function d4e(){let e=(0,cl.c)(1),t=qQ(p4e),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,F.useEffect)(f4e,n),t}function f4e(){JQ()}function p4e(e){return e.byRuntimeId}function m4e(e){let t=JQ();for(let n of t.records())n.runtimeId===e&&(n.status===`failed`||n.status===`outcome-unknown`)&&t.acknowledge(n.runtimeId,n.actorSessionId,n.transportRequestId)}var h4e=12e4,g4e=3e4,YQ=3e4;function XQ(e){let t=e.expiresAt?Date.parse(e.expiresAt):NaN;if(!Number.isFinite(t))throw Error(`Cloud runtime authority descriptor has no valid expiry.`);return t}function _4e(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function v4e(e){let t=e.now??Date.now,n=e.renewalSkewMs??h4e,r=!1,i=null,a=null,o=XQ(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=XQ(a);o=c;let l=Math.max(t(),c-n);e.onState?.({kind:`scheduled`,expiresAt:new Date(c).toISOString(),renewAt:new Date(l).toISOString()}),i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},Math.max(0,l-t()))},l=()=>{if(r)return null;let e=t()+YQ;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},YQ),new Date(e).toISOString())},u=()=>{if(r)return Promise.resolve();if(a)return a;s(),e.onState?.({kind:`renewing`,expiresAt:new Date(o).toISOString()});let n=e.renew().then(async n=>{let i=XQ(n);if(i<=t())throw Error(`Cloud runtime authority descriptor is already expired.`);r||(e.onState?.({kind:`ready`,expiresAt:new Date(i).toISOString(),renewedAt:new Date(t()).toISOString()}),c(n))}).catch(t=>{if(r)return;let n=_4e(t);throw e.onState?.({kind:`error`,code:n?`authority_auth_rejected`:`authority_renewal_failed`,retryAt:n?null:l()}),t}).finally(()=>{a=null});return a=n,n};return c(e.initialDescriptor),{ensureLive:()=>o>t()+g4e?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}var ZQ=new Map;function QQ(e,t){return e.acquire(t?{signal:t}:{})}function y4e(e,t){ZQ.set(e,t)}function b4e(e){return ZQ.has(e)}function $Q(e,t){let n=ZQ.get(e);t&&n!==t||(n?.dispose(),ZQ.delete(e))}async function x4e(e){let t=ZQ.get(e);if(t)return(await t.acquire()).bearerToken;let n=GK(e);return n&&WX(n)?null:XK(e)}function S4e(e){switch(e){case`running`:return`green`;case`provisioning`:case`starting`:return`amber-pulse`;case`registered`:return`idle`;case`stopped`:case`suspended`:case`draining`:return`grey`;case`destroyed`:return`idle`;case`error`:return`red-pulse`;default:return`grey`}}function e$(e){let t=e.githubRepoFullName;return t?t.split(`/`)[1]??t:C4e(e.projectName)}function C4e(e){let t=e.trim().toLowerCase().replaceAll(`'`,``).replaceAll(`"`,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:`project`}function t$(e){if(!e)return null;let t=e.trim().replace(/\/+$/,``);return t.length>0?t:null}function n$(e){let t=t$(e??void 0);return t&&r$(t).length>1?t:null}function r$(e){return e.split(`/`).flatMap(e=>e.split(`\\`)).filter(e=>e.length>0)}function i$(e){return e?r$(e).at(-1)??null:null}function w4e(e){let t=e.rows.length>0;return(e.isLoading||e.startupPhase===`auth-refreshing`)&&!t?{kind:`loading`}:e.error&&!t?{kind:`error-no-rows`,message:e.error}:e.error&&t?{kind:`stale-rows`,message:e.error}:t?{kind:`rows`}:{kind:`empty`}}function T4e(e,t){if(!t)return!1;let n=e.repositoryIdentity?.canonicalKey;return n!==void 0&&!n.toLowerCase().endsWith(`/${t.toLowerCase()}`)}function E4e(e,t){return e?e.cmmdOrganizationId===t.cmmdOrganizationId&&e.cmmdProjectId===t.cmmdProjectId:!1}function D4e(e,t){let n=e.filter(e=>!e.cmmdRegistration),r=n$(t.workspaceRoot),i=r?n.filter(e=>t$(e.cwd)===r):[];if(i.length>0)return i;let a=e$(t).toLowerCase();return n.filter(e=>i$(e.cwd)?.toLowerCase()===a)}function a$(e,t,n){let r=e[t];if(!r)return null;let i=r.projectIds.flatMap(e=>{let t=r.projectById[e];return!t||T4e(t,n.githubRepoFullName)?[]:[t]}),a=i.filter(e=>E4e(e.cmmdRegistration,n)),o=a.length>0?a:D4e(i,n),s=o.length===1?o[0]:void 0;return s?{environmentId:t,projectId:s.id}:null}function O4e(e){return{cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,githubRepoFullName:e.githubRepoFullName,projectName:e.projectName,workspaceRoot:e.workspaceRoot}}function k4e(e,t){let n=e.cmmdEnvironmentId??e.environmentId;if(e.runtimeId===null||n===null)return null;let r=a$(t,an.make(n),O4e(e));return r?Io(r.environmentId,r.projectId):null}function A4e(e,t){return e===t?!0:e===null||t===null?!1:e.environmentId===t.environmentId&&e.projectId===t.projectId}function j4e(e,t){let n=!1,r=e.map(e=>{let r=k4e(e,t);return A4e(r,e.resolvedRef)?e:(n=!0,{...e,resolvedRef:r})});return n?r:e}var o$=`registered`,M4e={destroyed:`destroyed`,superseded:`destroyed`,error:`error`,failed:`error`,draining:`draining`,recycling:`draining`,stopped:`stopped`,suspended:`suspended`,provisioning:`provisioning`,created:`provisioning`,starting:`starting`,restarting:`starting`};function s$(e,t){let n=M4e[e];if(n!==void 0)return n;if(e!==`running`)return`stopped`;if(t)switch(t){case`app_ready`:case`server_ready`:case`ready`:case`supervisor_up`:return`running`;case`starting`:case`image_pulling`:case`waiting_state`:return`starting`;case`error`:return`error`;default:return`running`}return`running`}function N4e(e){return e===`destroyed`}function P4e(e){switch(e){case`running`:case`starting`:case`provisioning`:return!0;case`suspended`:return!0;case`registered`:case`stopped`:case`draining`:case`error`:case`destroyed`:return!1;default:return!1}}function F4e(e){let t=e.shortName?.trim();if(t)return t;if(e.projectName)return e.projectName;if(e.githubRepoFullName){let t=e.githubRepoFullName.split(`/`),n=t[t.length-1];if(n)return n}return`project ${e.cmmdProjectId}`}var c$={state:`unknown`,label:`Unknown`,detail:`Current Environment availability has not been observed.`,tone:`muted`,automaticWakeAllowed:!1,shellConnected:!1,shellMayEstablishReady:!1};function l$(e,t,n,r,i,a,o=!1){return{state:e,label:t,detail:n,tone:r,automaticWakeAllowed:i,shellConnected:a,shellMayEstablishReady:o}}function I4e(e,t){return e.ownerIntent===`paused`?l$(`paused`,`Paused`,`Resume before live work can wake this Environment.`,`warning`,!1,t):e.ownerIntent===`deleting`?l$(`deleting`,`Deleting`,`This Environment is being removed.`,`muted`,!1,t):null}function L4e(e,t){return e.executionAdmission.state===`allowed`?null:l$(`unavailable`,`Unavailable`,`This Environment is not accepting live work while it drains.`,`warning`,!1,t)}function u$(e,t=!1){if(e==null)return c$;let n=I4e(e,t);if(n!==null)return n;if(e.ownerIntent!==`active`)return c$;let r=L4e(e,t);if(r!==null)return r;let{provider:i,guestReadiness:a,activeWork:o}=e;return i.observedAt===null||i.failure!==null||i.state===`absent`||i.state===`unknown`?l$(`unknown`,`Unknown`,`Current provider availability has not been observed.`,`muted`,e.automaticWakeAllowed,t):i.state===`sleeping`?l$(`sleeping`,`Sleeping`,`Live work wakes this Environment automatically.`,`muted`,e.automaticWakeAllowed,t):a.observedAt===null||a.failure!==null||a.state===`unknown`?l$(`unknown`,`Unknown`,`Current guest readiness has not been observed.`,`muted`,e.automaticWakeAllowed,t):a.state===`starting`?l$(`starting`,`Starting`,`Preparing live execution.`,`warning`,e.automaticWakeAllowed,t):a.state===`degraded`?l$(`degraded`,`Degraded`,`A required service needs attention.`,`warning`,e.automaticWakeAllowed,t):a.state===`failed`?l$(`needs-attention`,`Needs attention`,`The readiness check failed.`,`destructive`,e.automaticWakeAllowed,t):t?l$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,!0):o.state===`active`?l$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,t):l$(`unknown`,`Unknown`,`No current execution proof is available.`,`muted`,e.automaticWakeAllowed,t,!0)}function R4e(e,t){return!t||!e.shellMayEstablishReady?e:l$(`ready`,`Ready`,null,`success`,e.automaticWakeAllowed,!0)}function d$(e){return e?s$(e.status,e.readinessPhase??void 0):o$}function z4e(e){return e.runtime?.githubRepoFullName??e.githubRepoFullName??null}function B4e(e,t){return{cmmdOrganizationId:e.organizationId,cmmdProjectId:e.projectId,projectName:F4e({shortName:e.shortName??null,projectName:e.projectName??null,githubRepoFullName:t,cmmdProjectId:e.projectId}),githubRepoFullName:t,iconUrl:e.iconUrl??null,icon:e.icon??null}}function V4e(e){return e?{runtimeId:e.runtimeId,workspaceRoot:e.workspaceRoot??null,status:d$(e),desiredState:f$(e.desiredState),environmentId:Tl(e.runtimeId),cmmdEnvironmentId:e.environmentId??null,...e.maintenance===void 0?{}:{maintenance:e.maintenance}}:{runtimeId:null,workspaceRoot:null,status:o$,desiredState:null,environmentId:null,cmmdEnvironmentId:null}}function f$(e){return e===`running`||e===`stopped`||e===`destroyed`?e:null}function H4e(e){return{...B4e(e,z4e(e)),registeredAt:e.registeredAt??null,...V4e(e.runtime),removal:e.removal??null,resolvedRef:null}}function U4e(e){return e.map(H4e)}function W4e(e){return e.map(e=>({runtimeId:e.runtime.runtimeId,cmmdOrganizationId:e.organizationId,cmmdUserId:e.userId,displayName:e.displayName??null,userFirstName:e.userFirstName??null,environmentId:Tl(e.runtime.runtimeId),cmmdEnvironmentId:e.runtime.environmentId??null,status:d$(e.runtime),desiredState:f$(e.runtime.desiredState),...e.runtime.maintenance===void 0?{}:{maintenance:e.runtime.maintenance},lifecycle:u$(e.lifecycle)}))}var p$=`forge:cmmd-cloud-project-catalog:v5`,G4e=nr({runtimeId:Kn(j),cmmdOrganizationId:Ln,cmmdProjectId:Ln,cmmdEnvironmentId:Kn(j),registeredAt:yn(Kn(j)),projectName:j,githubRepoFullName:Kn(j),workspaceRoot:Kn(j),iconUrl:yn(Kn(j)),icon:yn(Kn(j)),status:j,desiredState:yn(Kn(j)),environmentId:Kn(j),removal:yn(Kn(nr({operationId:j,deletePlanningProject:Xn,status:Fn([`pending`,`running`,`retryable`]),phase:Fn([`destroy_runtime`,`purge_execution_state`,`delete_planning_project`,`unregister`,`complete`]),lastErrorCode:Kn(j),lastErrorMessage:Kn(j),updatedAt:j})))}),m$=nr({rows:Jn(G4e),environments:Jn(nr({runtimeId:j,cmmdOrganizationId:Ln,cmmdUserId:Ln,displayName:yn(Kn(j)),userFirstName:yn(Kn(j)),environmentId:j,cmmdEnvironmentId:Kn(j),status:j,desiredState:Kn(j)})),fetchedAt:j});function K4e(){try{let e=yl(p$,m$);return e?{rows:e.rows.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,registeredAt:e.registeredAt??null,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl??null,icon:e.icon??null,status:e.runtimeId===null?o$:s$(e.status),desiredState:f$(e.desiredState),environmentId:e.runtimeId===null?null:Tl(e.runtimeId),cmmdEnvironmentId:e.cmmdEnvironmentId,resolvedRef:null,removal:e.removal??null})),environments:e.environments.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdUserId:e.cmmdUserId,displayName:e.displayName??null,userFirstName:e.userFirstName??null,cmmdEnvironmentId:e.cmmdEnvironmentId,status:s$(e.status),desiredState:f$(e.desiredState),environmentId:Tl(e.runtimeId)})),fetchedAt:e.fetchedAt}:null}catch{return null}}function q4e(e,t,n){try{bl(p$,{rows:e.map(e=>({runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,environmentId:e.environmentId,removal:e.removal})),environments:t,fetchedAt:n},m$)}catch{}}var h$=1e3;function J4e(e){return e.reconnectPhase===`idle`?`hidden`:e.reconnectPhase===`exhausted`?`actionable`:!e.hasConnected||!e.stableConnectionSeen?`startup-pending`:`actionable`}function g$(e){let t=e.maxAttempts??2,n=e.retryDelayMs??1e3;return e.failedAttempt<t?{kind:`retry`,delayMs:n,nextAttempt:e.failedAttempt+1}:{kind:`terminal`,attempt:e.failedAttempt}}var Y4e=`auth-required`,X4e=`cloud-projects`;async function Z4e(e,t,n){let r=null,i=new PK(e).listCloudProjects({signal:t.signal}).then(e=>({kind:`catalog`,catalog:e})).catch(e=>({kind:`failed`,error:e})),a=new Promise(e=>{r=setTimeout(()=>{t.abort(),e({kind:`timed-out`})},n)});try{return await Promise.race([i,a])}finally{r!==null&&clearTimeout(r)}}function Q4e(e){let t=e.accessToken??e.resolveAccessToken?.(),n={Accept:`text/event-stream`};return t&&(n.Authorization=`Bearer ${t}`),n}function $4e(e,t){let n=new URL(e);return n.pathname=t,n.search=``,n.hash=``,n.toString()}async function e3e(e){return(e.status===401||e.status===403)&&(await i3e(e)||e.status===401)?`auth-required`:e.status===404||e.status===405||!e.ok||!e.body?`fallback`:e.body.getReader()}async function t3e({reader:e,signal:t,onAuthRequired:n,onCatalog:r}){let i=new TextDecoder,a=``;try{for(;!t.aborted;){let{done:o,value:s}=await e.read();if(t.aborted||o)return;let c=n3e(a,i.decode(s,{stream:!0}));if(a=c.buffer,c.messages.some(e=>r3e(e,n,r)))return}}finally{e.releaseLock()}}function n3e(e,t){let n=`${e}${t}`.split(/\n\n/);return{buffer:n.pop()??``,messages:n}}function r3e(e,t,n){let r=o3e(e);if(r.name===Y4e)return t(),!0;let i=r.name===X4e?a3e(r.data):null;return i&&n(i),!1}async function i3e(e){try{let t=await e.clone().json();return typeof t?.code==`string`&&t.code===`CMMD_AUTH_REQUIRED`}catch{return!1}}function a3e(e){try{return OK(JSON.parse(e))}catch{return null}}function o3e(e){let t=``,n=``;for(let r of e.split(`
1020
+ `))r.startsWith(`event: `)&&(t=r.slice(7).trim()),r.startsWith(`data: `)&&(n=r.slice(6).trim());return{name:t,data:n}}var s3e=`/api/cmmd/forge-cloud-projects`,c3e=`/api/cmmd/forge-cloud-projects/events`,l3e=15e3,u3e=3e4,d3e=2e3,f3e=3e4,p3e=200;function m3e({config:e,onEvent:t}){let n=!1,r=!1,i=!1,a=!1,o=!1,s=0,c=null,l=0,u=null,d=null,f=0,p=null,m=null,h=null,g=null;function _(e){return e!==null&&clearTimeout(e),null}function v(){p=_(p),g=_(g)}function y(){f+=1,d?.controller.abort(),d=null}function b(e,t){return d?.controller===e&&d.generation===t&&f===t}function x(e){return u===e}function S(){y(),u?.abort(),u=null,v(),h=_(h)}function C(){return!r&&!a}function w(e){t({kind:`catalog`,catalog:e,fetchedAt:new Date().toISOString()})}function T(e){a||r||(a=!0,c=null,S(),t({kind:`auth-required`,message:e}))}function E(e,n){if(r||a)return;s+=1,c=n;let i=g$({failedAttempt:s,retryDelayMs:h$});if(i.kind===`terminal`){T(e);return}u?.abort(),u=null,g=_(g),t({kind:`auth-refreshing`}),o=!0,h=_(h),h=setTimeout(()=>{h=null,o=!1,pe()},i.delayMs)}async function D(){if(!C())return!1;let n=new AbortController,r=++f;d={controller:n,generation:r},t({kind:`loading`});try{return ee(await Z4e(e,n,l3e),n,r)}finally{b(n,r)&&(d=null)}}function ee(e,t,n){return!C()||!b(t,n)?!1:e.kind===`catalog`?te(e.catalog):e.kind===`timed-out`?ne():O(e.error)}function te(e){return c!==`sse`&&(s=0,c=null),o=!1,w(e),!0}function ne(){return t({kind:`failed`,message:`Cloud connection refresh timed out. Showing last known connections.`}),!a}function O(e){let n=e instanceof Error?e.message:`Failed to load cloud projects`;return ZG(e)||h3e(e)||/authentication required/i.test(n)?E(n,`list`):t({kind:`failed`,message:n}),!a}function k(){C()&&(p=_(p),p=setTimeout(async()=>{await D(),C()&&k()},u3e))}function re(){!C()||o||(i?k():ae(l))}function A(e){l=e+1;let t=Math.min(d3e*2**e,f3e);g=_(g),g=setTimeout(()=>{g=null,ae(l)},t)}function ie(e){s=0,c=null,l=0,w(e)}async function ae(t){if(!C()||u!==null)return;u=new AbortController;let n=u,r=e.eventsUrl??$4e(e.cmmdHttpBaseUrl,`/api/forge/context/runtimes/events`),i=e.eventsUrl?{Accept:`text/event-stream`}:Q4e(e);try{await oe(await fetch(r,{headers:i,signal:n.signal,credentials:`include`}),n,t)}catch{de(n)}}async function oe(e,t,n){if(!se(t))return;let r=await e3e(e);if(se(t)){if(typeof r==`string`){ue(r);return}await t3e({reader:r,signal:t.signal,onAuthRequired:()=>ce(t),onCatalog:e=>le(t,e)}),fe(t,n)}}function se(e){return C()&&x(e)}function ce(e){se(e)&&E(`CMMD authentication required. Sign in again to continue.`,`sse`)}function le(e,t){se(e)&&ie(t)}function ue(e){if(u=null,e===`auth-required`){E(`CMMD authentication required. Sign in again to continue.`,`sse`);return}i=!0,k()}function de(e){e.signal.aborted||!se(e)||(u=null,i=!0,k())}function fe(e,t){e.signal.aborted||!se(e)||(u=null,A(t))}function pe(){return D().then(e=>{e&&C()&&re()})}return{initialize(){n||r||(n=!0,pe())},refresh(){r||(y(),m=_(m),m=setTimeout(()=>{m=null,a=!1,o=!1,s=0,c=null,S(),pe()},p3e))},teardown(){r=!0,m=_(m),S()}}}function h3e(e){return typeof e==`object`&&!!e&&`kind`in e&&e.kind===`auth`}var _$={connected:!1,isLoading:!1,error:null,rows:[],environments:[],fetchedAt:null,stale:!1,startupPhase:`idle`,capacity:null};function g3e({config:e}){let t=K4e(),n=t?{..._$,isLoading:!0,rows:t.rows,environments:t.environments,fetchedAt:t.fetchedAt,stale:!0}:_$,r=new Set;function i(e){n=e;for(let e of r)e()}function a(e){switch(e.kind){case`loading`:i({...n,isLoading:!0,error:null});return;case`catalog`:{let t=U4e(e.catalog.listRowsForDisplay()),n=W4e(e.catalog.listEnvironmentsForDisplay());q4e(t,n,e.fetchedAt),i({connected:!0,isLoading:!1,error:null,rows:t,environments:n,fetchedAt:e.fetchedAt,stale:!1,startupPhase:`idle`,capacity:e.catalog.capacity});return}case`failed`:i({...n,connected:!1,isLoading:!1,error:e.message,stale:n.rows.length>0,startupPhase:`idle`});return;case`auth-refreshing`:i({...n,connected:!1,isLoading:!0,error:null,stale:n.rows.length>0,startupPhase:`auth-refreshing`});return;case`auth-required`:i({...n,connected:!1,isLoading:!1,error:e.message,stale:n.rows.length>0,startupPhase:`idle`}),dr(`cmmd-runtimes`);return}}let o=m3e({config:e,onEvent:a});return{subscribe(e){return r.add(e),()=>r.delete(e)},read(){return n},initialize(){o.initialize()},refresh(){o.refresh()},_teardown(){o.teardown()},_setState(e){i(e)}}}var v$=null;function y$(e){return typeof window<`u`&&window.location?.href?new URL(e,window.location.href).toString():new URL(e,`http://localhost`).toString()}function b$(){return{cmmdHttpBaseUrl:`https://cmmd.ai`,resolveAccessToken:()=>null,listUrl:s3e,eventsUrl:c3e,destroyUrl:e=>y$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/destroy`),lifecycleUrl:(e,t)=>y$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/${t}`),updateCommitUrl:e=>y$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/update-commit`),updateCommitOperationUrl:(e,t)=>y$(`/api/cmmd/forge-runtimes/${encodeURIComponent(e)}/update-commit/${encodeURIComponent(String(t))}`),ensureUrl:y$(`/api/cmmd/forge-runtimes/ensure`)}}function x$(){return v$===null&&(v$=g3e({config:b$()})),v$}function _3e(){x$().refresh()}function v3e(e){return x$().subscribe(e)}function S$(){return x$().read()}function y3e(e){let t=(0,cl.c)(9),n=e?.enabled??!0,r,i;t[0]===n?(r=t[1],i=t[2]):(r=()=>{n&&x$().initialize()},i=[n],t[0]=n,t[1]=r,t[2]=i),(0,F.useEffect)(r,i);let a=(0,F.useSyncExternalStore)(v3e,S$,S$),o=aJ(b3e),s,c;t[3]!==o||t[4]!==a.rows?(c=j4e(a.rows,o),t[3]=o,t[4]=a.rows,t[5]=c):c=t[5],s=c;let l=s,u;return t[6]!==l||t[7]!==a?(u=l===a.rows?a:{...a,rows:l},t[6]=l,t[7]=a,t[8]=u):u=t[8],u}function b3e(e){return e.environmentStateById}var x3e=`forge:cloud-runtime-handoffs:v2`,S3e=3e5,C$=new Map,C3e={clear:()=>C$.clear(),getItem:e=>C$.get(e)??null,key:e=>Array.from(C$.keys())[e]??null,get length(){return C$.size},removeItem:e=>C$.delete(e),setItem:(e,t)=>C$.set(e,t)};function w3e(){return typeof window<`u`?window.localStorage:globalThis.localStorage??C3e}var w$=Xt()(CJ(e=>({byRuntimeId:{},record:t=>e(e=>({byRuntimeId:{...e.byRuntimeId,[t.runtimeId]:t}})),clearRuntime:t=>e(e=>t in e.byRuntimeId?{byRuntimeId:Object.fromEntries(Object.entries(e.byRuntimeId).filter(([e])=>e!==t))}:e),reconcileCatalog:(t,n=Date.now())=>e(e=>{let r=Object.entries(e.byRuntimeId).filter(([,e])=>{if(n-e.recordedAt>S3e)return!1;let r=t.find(t=>t.cmmdOrganizationId===e.cmmdOrganizationId&&t.cmmdProjectId===e.cmmdProjectId);return r?.runtimeId===e.previousCatalogRuntimeId&&r.registeredAt===e.catalogRegisteredAt});return r.length===Object.keys(e.byRuntimeId).length?e:{byRuntimeId:Object.fromEntries(r)}}),reset:()=>e({byRuntimeId:{}})}),{name:x3e,storage:xJ(w3e),partialize:e=>({byRuntimeId:e.byRuntimeId}),version:2}));function T3e(e){w$.getState().record({...e,recordedAt:Date.now()})}function E3e(e){w$.getState().clearRuntime(e)}var D3e=new Set([`filesystem`,`terminal`,`git`,`project-write`]);function O3e(e){return e===`desktop-local`}function k3e(e){return e===`cloud`||e===`cloud-vm`||e===`cmmd`||e===`github`}function T$(e){return e.actionKind===`cloud-api`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud API route`,description:`Cloud and Command work routes through authenticated Forge Cloud APIs.`}:D3e.has(e.actionKind)?k3e(e.workSource)?e.workSource===`cloud-vm`&&e.executionRuntime===`cloud`?{available:!0,route:`cloud-vm`,requiresPermissionGate:!1,title:`Cloud VM route`,description:`Filesystem, terminal, git, and project writes run inside the user's Forge Cloud VM.`}:e.executionRuntime===`cloud`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud work route`,description:`Cloud-scoped filesystem, terminal, git, and project writes run in the Forge Cloud runtime.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Open in Forge Cloud`,description:`Cloud projects must execute inside the Forge Cloud runtime. Local Desktop cannot run cloud project filesystem, terminal, git, or project-write actions.`}:O3e(e.workSource)?e.surface===`desktop-local`||e.executionRuntime===`desktop-local`?{available:!0,route:`desktop-local`,requiresPermissionGate:!1,title:`Desktop local route`,description:`Local filesystem, terminal, git, and project writes run through the Desktop local backend.`}:e.executionRuntime===`dev-local-web`?{available:!0,route:`dev-local-web`,requiresPermissionGate:!1,title:`Dev local route`,description:`Local Web is a development-only projection and routes local actions through the dev server.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Switch to Desktop Local`,description:`Local projects must execute in the Desktop Local runtime. Forge Cloud cannot run local filesystem, terminal, git, or project-write actions.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unknown work source`,description:`Forge cannot safely route local actions for this work source yet.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unsupported route`,description:`Forge does not have a runtime route for this action yet.`}}var A3e=`Ready to use. Your cloud project starts when you open the first thread.`;function j3e(e){let t=T$({actionKind:`project-write`,surface:`cloud-official`,workSource:`cloud-vm`,executionRuntime:`cloud`});return{actionAuthority:`runtime`,surface:`cloud-official`,hostKind:`user-cloud-vm`,workSource:`cloud-vm`,executionRuntime:`cloud`,modelRuntime:`cloud`,linkState:`cloud-only`,workspaceIdentity:null,hideLocalPath:!0,label:`Cloud project`,description:e?`This project runs in your Forge Cloud VM.`:A3e,actionRouteLabel:t.title,actionRouteDescription:t.description,actionRouteAvailable:t.available,requiresPermissionGate:t.requiresPermissionGate}}var M3e=3e5;function E$(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t of e){let e={cmmdOrganizationId:t.cmmdOrganizationId,cmmdProjectId:t.cmmdProjectId};r.set(O$(e),e),t.runtimeId!==null&&i.set(t.runtimeId,e)}for(let a of t){if(n-a.recordedAt>M3e)continue;let t=r.get(O$({cmmdOrganizationId:a.cmmdOrganizationId,cmmdProjectId:a.cmmdProjectId})),o=e.find(e=>e.cmmdOrganizationId===a.cmmdOrganizationId&&e.cmmdProjectId===a.cmmdProjectId);t&&o?.runtimeId===a.previousCatalogRuntimeId&&o.registeredAt===a.catalogRegisteredAt&&!i.has(a.runtimeId)&&i.set(a.runtimeId,t)}return i}function D$(e){return e.environmentId??`cmmd-cloud-project:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function N3e(e){return{environmentId:D$(e),workspaceRoot:e.workspaceRoot,resolvedRef:e.resolvedRef}}function O$(e){return`cloud:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function P3e(e){let t=/^cloud:(\d+):(\d+)$/.exec(e??``);return t?{cmmdOrganizationId:Number(t[1]),cmmdProjectId:Number(t[2])}:null}function F3e(e){return`cloud-runtime:${e}`}var I3e=`cloud-unconnected:`;function L3e(e,t,n=[]){let r=O$(e);return k$({id:tn.make(`${I3e}${r}`),environmentId:an.make(D$(e)),name:e.projectName,cwd:``,repositoryIdentity:null,availability:void 0,defaultModelSelection:null,createdAt:void 0,updatedAt:void 0,scripts:[],projectKey:r,environmentPresence:`remote-only`,source:j3e(e.runtimeId!==null),memberProjectRefs:t?[t]:[],remoteEnvironmentLabels:[],worktreeMembers:[],activeWorktreeKey:null,preConnectCloud:{runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,removal:e.removal},cloudRemoval:e.removal},n)}function k$(e,t){if(t.length===0)return e;let n=[...e.memberProjectRefs],r=new Set(n.map(e=>`${e.environmentId}:${e.projectId}`));for(let e of t){let t=`${e.environmentId}:${e.projectId}`;r.has(t)||(r.add(t),n.push(e))}return n.length===e.memberProjectRefs.length?e:{...e,memberProjectRefs:n}}function A$(e,t,n,r){if(!e)return null;let i=t.find(t=>t.cmmdEnvironmentId===String(e));if(i)return{row:i,runtimeId:i.runtimeId,matchedByHandoff:!1};let a=Dl(e).legacyRuntimeId;if(a){let e=t.find(e=>e.runtimeId===a);if(e)return{row:e,runtimeId:a,matchedByHandoff:!1};let i=E$(t,n,r).get(a);if(!i)return null;let o=t.find(e=>e.cmmdOrganizationId===i.cmmdOrganizationId&&e.cmmdProjectId===i.cmmdProjectId);return o?{row:o,runtimeId:a,matchedByHandoff:!0}:null}let o=t.find(t=>t.runtimeId===null&&D$(t)===String(e));return o?{row:o,runtimeId:null,matchedByHandoff:!1}:null}function R3e(e,t=e.runtimeId){return{runtimeId:t,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,desiredState:e.desiredState}}function z3e(e){return e.desiredState===`stopped`}var B3e=15e3;function V3e(e){return e===401||e===403}function H3e(e){return typeof e!=`object`||!e?!1:e.retryable===!0}function j$(e){return V3e(e.status)||e.attempt>=e.maxAttempts||e.status>=200&&e.status<300?!1:e.status>=500||e.status===409&&H3e(e.body)}function U3e(e,t){let n=e?.trim();if(!n)return null;if(/^-?\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:r-t}function M$(e){let t=e=>Math.min(B3e,Math.max(0,e)),n=U3e(e.retryAfter,e.nowMs??Date.now());return t(n===null?300*2**Math.max(0,e.attempt-1):n)}var W3e=6e4;function G3e(e,t){if(!e||typeof e!=`object`)return t;let n=e.error;return typeof n==`string`&&n.trim().length>0?n:t}var N$=`CMMD returned an invalid Cloud runtime connection descriptor.`;function P$(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw Error(N$);return n}function K3e(e){if(!e||typeof e!=`object`)throw Error(N$);let t=e;return{httpBaseUrl:P$(t,`httpBaseUrl`),wsBaseUrl:P$(t,`wsBaseUrl`),bearerToken:P$(t,`bearerToken`),expiresAt:P$(t,`expiresAt`)}}async function q3e(e){let t=or(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),n=ur({method:`POST`,...e.signal?{signal:e.signal}:{},headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})});for(let r=1;r<=8;r+=1){let i=await fetch(t,n),a=await i.json().catch(()=>null);if(i.ok)return K3e(a);if(!j$({status:i.status,body:a,attempt:r,maxAttempts:8})){let e=FQ(i.status,a)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${i.status}).`;throw Object.assign(Error(G3e(a,e)),{status:i.status,...PQ(a)?{code:PQ(a)}:{}})}await HX(M$({attempt:r,retryAfter:i.headers.get(`retry-after`)}),e.signal)}throw Error(`Cloud runtime connection retry budget was exhausted.`)}function J3e(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+W3e}function F$(e){let t=e.requestDescriptor??q3e,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=new AbortController,s=e=>VX(e,o.signal),c=()=>i||(i=s(t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId},signal:o.signal})).then(async t=>(await s(Promise.resolve(e.validateDescriptor?.(t))),await s(Promise.resolve(e.persistDescriptor?.(t))),await s(Promise.resolve()),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>{if(o.signal.aborted)return s(Promise.resolve(r));let t=e?.forceRefresh||a||J3e(r,n())?c():Promise.resolve(r);return VX(s(t),e?.signal)},invalidate:()=>{a=!0},dispose:()=>{o.abort()}}}function Y3e(e){let t=e.runtimeId?.trim();if(t)return t;let n=Dl(e.environmentId).legacyRuntimeId;if(n)return n;let r=S$().rows,i=Object.values(w$.getState().byRuntimeId);return A$(e.environmentId,r,i)?.runtimeId??null}function X3e(e,t,n,r){let i=e,a=F$({runtimeId:t,...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...n===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:n,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await FX({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(r&&!r())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...UX(i),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:un(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:new Date().toISOString()};await YK(t),await ZK(t.environmentId),VK.getState().upsert(t),i=t}});return y4e(e.environmentId,a),a}function Z3e(e){let t={wsBaseUrl:e.record.wsBaseUrl,httpBaseUrl:e.record.httpBaseUrl,bearerToken:e.bearerToken,expiresAt:e.record.runtimeTicketExpiresAt??null};return{acquire:()=>Promise.resolve(t)}}function I$(e){let t=e.toLowerCase();return t.includes(`authentication`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`credential`)||t.includes(`runtime ticket`)||t.includes(`status 401`)||t.includes(`status 403`)}var L$=new Map,R$=new Map,z$=new Map,B$=new Map,V$=new Map,H$=new Set,U$=new Map,W$=null,G$=!1;function K$(e){return B$.get(e)??0}function q$(e){B$.set(e,K$(e)+1)}function J$(e,t){return e.environmentId===t.environmentId&&e.httpBaseUrl===t.httpBaseUrl&&e.wsBaseUrl===t.wsBaseUrl&&e.runtimeId===t.runtimeId&&e.cmmdOrganizationId===t.cmmdOrganizationId}function Y$(e){if(K$(e.record.environmentId)!==e.generation)return!1;let t=GK(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||J$(t,e.record):t!==null&&J$(t,e.registryExpectation.record)}var Q3e=9e5,X$=32,Z$=()=>void 0;function Q$(e,t){return Vo(Lo(e,t))}function $$(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function $3e(e){let t=Lo(e.environmentId,e.threadId),n=aJ.getState(),r=iJ(n,t);if(r){if(r.hasPendingApprovals||r.hasPendingUserInput||r.hasActionableProposedPlan)return!0;let e=r.session?.orchestrationStatus;if(e&&e!==`idle`&&e!==`stopped`||r.latestTurn?.state===`running`)return!0}let i=rJ(n,t);if(!i)return!1;let a=i.session?.orchestrationStatus;return!!(a&&a!==`idle`&&a!==`stopped`)||i.latestTurn?.state===`running`||i.pendingSourceProposedPlan!==void 0}function e1(e){return e.refCount===0&&!$3e(e)}function t1(e){if(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Z$)return!0;let t=A1(e.environmentId);return t?(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`event`?C6e(t.event,e.environmentId):t.kind===`snapshot`&&(aJ.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),aJ.getState().clearThreadSubscriptionError(e.environmentId,e.threadId))},{onError:t=>gXe(e.environmentId,e.threadId,t)}),!0):!1}function n1(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=k1(()=>{t1(e)&&(e.lastAccessedAt=Date.now())}),t1(e))}function r1(e){let t=U$.get(e);return t?($$(t),t.unsubscribeConnectionListener?.(),t.unsubscribeConnectionListener=null,U$.delete(e),t.unsubscribe(),t.unsubscribe=Z$,a6e(),!0):!1}var i1=null;function e6e(e){let t=Lo(e.environmentId,e.threadId),n=aJ.getState(),r=iJ(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=rJ(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function t6e(e){e.unsubscribe!==Z$&&(e.unsubscribe(),e.unsubscribe=Z$),t1(e)||n1(e)}function n6e(e,t,n){if(e.recoveryAttempts+=1,e.lastEventAt=Date.now(),console.warn(`[forge] thread-detail liveness watchdog recovering`,{action:t,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:Math.round(n),recoveryAttempts:e.recoveryAttempts}),t===`resubscribe`){t6e(e);return}A1(e.environmentId)?.reconnect().catch(t=>{gG(t,{route:`thread-detail-liveness-watchdog-reconnect-failed`,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:String(Math.round(n)),recoveryAttempts:String(e.recoveryAttempts)})})}function r6e(){let e=Date.now();for(let t of U$.values()){let n=W$e({isWorking:e6e(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:G$e,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&n6e(t,n,e-t.lastEventAt)}}function i6e(){i1===null&&(i1=setInterval(r6e,K$e))}function a6e(){U$.size>0||i1!==null&&(clearInterval(i1),i1=null)}function o6e(e){for(let[t,n]of U$)n.environmentId===e&&r1(t)}function s6e(e){let t=Lo(e.environmentId,e.threadId),n=aJ.getState(),r=rJ(n,t);if(!r)return null;let i=iJ(n,t),a=i?.latestUserMessageAt??null;if(a===null)for(let e=r.messages.length-1;e>=0;--e){let t=r.messages[e];if(t?.role===`user`){a=t.createdAt;break}}return{id:r.id,projectId:r.projectId,title:r.title,modelSelection:r.modelSelection,runtimeMode:r.runtimeMode,interactionMode:r.interactionMode,branch:r.branch,worktreePath:r.worktreePath,latestTurn:r.latestTurn,createdAt:r.createdAt,updatedAt:r.updatedAt??r.createdAt,archivedAt:r.archivedAt,session:r.session?{threadId:r.id,updatedAt:r.session.updatedAt,providerName:r.session.provider,runtimeMode:r.runtimeMode,activeTurnId:r.session.activeTurnId??null,lastError:r.session.lastError??null,status:r.session.orchestrationStatus}:null,latestUserMessageAt:a,hasPendingApprovals:i?.hasPendingApprovals??!1,hasPendingUserInput:i?.hasPendingUserInput??!1,hasActionableProposedPlan:i?.hasActionableProposedPlan??!1,anchorKind:r.anchorKind,anchorCmmdId:r.anchorCmmdId,kind:r.kind,parentThreadId:r.parentThreadId,status:r.status,workerRole:r.workerRole,goal:r.goal,titleRegeneration:r.titleRegeneration??null}}function c6e(e,t){if(U$.size===0)return e;let n=new Set(e.threads.map(e=>e.id)),r=[];for(let e of U$.values()){if(e.environmentId!==t||e.refCount<=0||n.has(e.threadId))continue;let i=s6e(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function l6e(e,t){let n=new Set(t);for(let[t,r]of U$)r.environmentId===e&&!n.has(r.threadId)&&e1(r)&&r1(t)}function u6e(e){$$(e),e1(e)&&(e.evictionTimeoutId=setTimeout(()=>{let t=U$.get(Q$(e.environmentId,e.threadId));t&&(t.evictionTimeoutId=null,e1(t)&&r1(Q$(e.environmentId,e.threadId)))},Q3e))}function a1(){if(U$.size<=X$)return;let e=[...U$.entries()].filter(([,e])=>e1(e)).toSorted(([,e],[,t])=>e.lastAccessedAt-t.lastAccessedAt);for(let[t]of e){if(U$.size<=X$)return;r1(t)}}function o1(e){$$(e),e1(e)&&u6e(e)}function d6e(e,t){let n=U$.get(Q$(e,t));n&&o1(n)}function s1(e){for(let t of U$.values())t.environmentId===e&&o1(t);a1()}function f6e(e,t){let n=Q$(e,t),r=U$.get(n);if(r){$$(r),r.refCount+=1,r.lastAccessedAt=Date.now(),t1(r)||n1(r);let e=!1;return()=>{e||(e=!0,r.refCount=Math.max(0,r.refCount-1),r.lastAccessedAt=Date.now(),r.refCount===0&&(o1(r),a1()))}}let i={environmentId:e,threadId:t,unsubscribe:Z$,unsubscribeConnectionListener:null,refCount:1,lastAccessedAt:Date.now(),evictionTimeoutId:null,lastEventAt:Date.now(),recoveryAttempts:0};U$.set(n,i),t1(i)||n1(i),i6e(),a1();let a=!1;return()=>{a||(a=!0,i.refCount=Math.max(0,i.refCount-1),i.lastAccessedAt=Date.now(),i.refCount===0&&(o1(i),a1()))}}function c1(){for(let e of H$)e()}function p6e(e){return{lastError:e instanceof Error?e.message:String(e),lastErrorAt:new Date().toISOString()}}function l1(){return new Date().toISOString()}var u1=8,d1=[1e3,2e3,4e3,8e3,12e3,16e3,2e4],m6e=9e4;function h6e(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function g6e(e){if(Z2e(e))return!1;let t=h6e(e);if(t===502||t===503||t===504||e._tag===`OrchestrationGetSnapshotError`)return!0;let n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return r.includes(`all fibers interrupted without error`)||r.includes(`timed out while waiting for forge cloud runtime metadata`)||r.includes(`timed out while waiting for`)||r.includes(`to stream its shell snapshot`)||r.includes(`forge runtime route not found`)||r.includes(`fly-replay`)||r.includes(`could not find a good candidate`)||r.includes(`instance refused connection`)||n.includes(`Unknown socket error`)||n.includes(`Failed to fetch remote auth endpoint`)||n.includes(`Forge runtime replay target is unavailable`)||n.includes(`Remote auth request failed (502)`)||n.includes(`Remote auth request failed (503)`)||n.includes(`Remote auth request failed (504)`)||n.includes(`Unable to connect to the Forge server WebSocket`)}function _6e(e){return d1[e]??d1[d1.length-1]}function v6e(){return m6e}function y6e(e,t){if(!WX(e))return t;let n=null,r=new Promise((t,r)=>{n=globalThis.setTimeout(()=>{r(Error(`Timed out while waiting for Forge Cloud runtime metadata for ${e.environmentId}. The VM may still be starting.`))},v6e())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function f1(e){RX.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function p1(e){let t=l1();RX.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),VK.getState().markConnected(e,t)}function m1(e,t){RX.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function h1(e,t){RX.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:l1(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:l1()}:{}})}function g1(e,t){RX.getState().patch(e,{connectionState:`error`,...p6e(t)})}function b6e(e){if(e.length<2)return[...e];let t=[];for(let n of e){let e=t.at(-1);if(e?.type===`thread.message-sent`&&n.type===`thread.message-sent`&&e.payload.threadId===n.payload.threadId&&e.payload.messageId===n.payload.messageId){t[t.length-1]={...n,payload:{...n.payload,attachments:n.payload.attachments??e.payload.attachments,createdAt:e.payload.createdAt,text:!n.payload.streaming&&n.payload.text.length>0?n.payload.text:e.payload.text+n.payload.text}};continue}t.push(n)}return t}function _1(){let e=Qq(aJ.getState());$Z.getState().syncProjects(e.map(e=>({key:Bo(Io(e.environmentId,e.id)),cwd:e.cwd})))}function v1(){let e=$q(aJ.getState());$Z.getState().syncThreads(e.map(e=>({key:Vo(Lo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),b$e(e.map(e=>Lo(e.environmentId,e.id)))}function x6e(){_1(),v1();let e=S$e({snapshotThreads:$q(aJ.getState()).map(e=>({key:Vo(Lo(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:kX.getState().listDraftThreadKeys()});jZ.getState().removeOrphanedTerminalStates(e)}function y1(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function S6e(e,t){if(e.length===0)return;let n=C$e(e),r=b6e(e),i=e.some(e=>e.type===`project.created`||e.type===`project.meta-updated`||e.type===`project.deleted`);if(n.needsProviderInvalidation&&(G$=!0,W$?.queryInvalidationThrottler.maybeExecute()),aJ.getState().applyOrchestrationEvents(r,t),i){let e=Qq(aJ.getState());$Z.getState().syncProjects(e.map(e=>({key:Bo(Io(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=$q(aJ.getState());$Z.getState().syncThreads(e.map(e=>({key:Vo(Lo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=kX.getState();for(let e of n.promoteDraftThreadIds)AX(Lo(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(Lo(t,e)),$Z.getState().clearThreadUi(Vo(Lo(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=Lo(t,e);jZ.getState().removeTerminalState(n),RZ.getState().clearBrowserState(n)}s1(t)}function C6e(e,t){S6e([e],t)}function w6e(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?Lo(t,n):null,i=r?rJ(aJ.getState(),r):void 0;switch(aJ.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:_1();return;case`thread-upserted`:v1(),!i&&r&&AX(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(jZ.getState().removeTerminalState(r),RZ.getState().clearBrowserState(r)),d6e(t,e.thread.id),a1();return;case`thread-removed`:r&&(r1(Vo(r)),kX.getState().clearDraftThread(r),$Z.getState().clearThreadUi(Vo(r)),jZ.getState().removeTerminalState(r),RZ.getState().clearBrowserState(r)),v1();return}}function T6e(e,t){return e.invalidateQueries({queryKey:NX.all(t)})}function b1(e){return{onWelcome:(t,n)=>{e?.(t),W$&&T6e(W$.queryClient,n)},applyShellEvent:w6e,syncShellSnapshot:(e,t)=>{let n=c6e(e,t);aJ.getState().syncServerShellSnapshot(n,t),l6e(t,n.threads.map(e=>e.id)),s1(t),x6e()},applyTerminalEvent:(e,t)=>{let n=Lo(t,Vn.make(e.threadId)),r=rJ(aJ.getState(),n),i=kX.getState().getDraftThreadByRef(n)!==null;y1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&jZ.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=Lo(t,Vn.make(e.threadId)),r=rJ(aJ.getState(),n),i=kX.getState().getDraftThreadByRef(n)!==null;y1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&RZ.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{g1(t,e)}}}function x1(){if(typeof window>`u`)return;let e=pr();if(e?.primaryMode===`cloud`&&e.bearerToken)return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function E6e(){if(typeof window>`u`)return;let e=pr(),t=e?.primaryMode===`cloud`?e.desktopLocal??null:e??null;if(!(!t?.httpBaseUrl||!t.wsBaseUrl||!t.bearerToken))return{bearerToken:t.bearerToken,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,label:t.label}}function D6e(e){let t=Xie(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return NQ(new TQ(async()=>{await lr().catch(()=>null);let e=x1();if(e)try{return await IX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})}catch(e){throw ZG(e)&&dr(`ws-token`),e}return mJe(t)}))}function O6e(e){return NQ(new TQ(()=>IX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken}),{trackGlobalConnection:!1,onAttempt:()=>{f1(e.environmentId)},onOpen:()=>{p1(e.environmentId)},onError:t=>{RX.getState().patch(e.environmentId,{connectionState:`error`,lastError:t,lastErrorAt:l1()})},onClose:t=>{h1(e.environmentId,t.reason)}}))}function k6e(e,t,n,r){return n()&&RX.getState().ensure(e.environmentId),NQ(new TQ(async()=>{let e=await t.acquire(),n=e=>IX({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken,...r?{runtimeTicket:e.bearerToken}:{}});try{return await n(e)}catch(e){if(!r||!ZG(e))throw e;return n(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&f1(e.environmentId)},onOpen:()=>{n()&&p1(e.environmentId)},onError:i=>{r&&I$(i)&&t.invalidate?.(),n()&&RX.getState().patch(e.environmentId,{connectionState:`error`,lastError:i,lastErrorAt:l1()})},onClose:i=>{r&&(i.code===1008||I$(i.reason))&&t.invalidate?.(),n()&&h1(e.environmentId,i.reason)}}))}async function S1(e,t,n,r,i,a,o){let s=await QQ(t,o),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),FX({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);if(!r())return!1;RX.getState().patch(e.environmentId,{authState:l.authenticated?`authenticated`:`requires-auth`,descriptor:c.environment,serverConfig:c,role:l.authenticated?l.role??i??null:null});let u=GK(e.environmentId);return r()&&l.authenticated&&u&&VK.getState().upsert({...u,lastAuthenticatedPullRequestCapability:c.environment.capabilities?.pullRequests===!0}),!0}function C1(e){let t=L$.get(e.environmentId);if(t&&t!==e)throw Error(`Environment ${e.environmentId} already has an active connection.`);return L$.set(e.environmentId,e),c1(),e}async function w1(e){let t=L$.get(e);return t?(L$.delete(e),$Q(e),o6e(e),c1(),await t.dispose(),!0):!1}function T1(){let e=wK();if(!e?.environmentId)throw Error(`Unable to resolve the primary environment.`);let t=L$.get(e.environmentId);if(t)return t;let n=x1(),r=e.source===`paired-bearer`||!0;return C1(KX({kind:`primary`,knownEnvironment:e,client:D6e(e),resolveEnvironmentId:()=>wK()?.environmentId??e.environmentId,...r?{readiness:n?{bearerToken:n.bearerToken}:{}}:{},...b1()}))}async function A6e(e,t,n){let r=L$.get(e.environmentId);if(r)return r;let i=WX(e)?Y3e(e):null,a=i!==null,o=()=>Y$({record:e,generation:t,registryExpectation:n?.registryExpectation??{kind:`existing-record`,record:e}}),s=a?n?.bearerToken:n?.bearerToken??await XK(e.environmentId);if(!a&&!s)throw o()&&RX.getState().patch(e.environmentId,{authState:`requires-auth`,role:null,connectionState:`disconnected`,lastError:`Saved environment is missing its saved credential. Pair it again.`,lastErrorAt:l1()}),Error(`Saved environment is missing its saved credential.`);let c=a?X3e(e,i,s??void 0,o):Z3e({record:e,bearerToken:s}),l=await QQ(c,n?.signal);if(!o())throw Error(`Saved environment changed while its connection was being acquired.`);let u=n?.client??k6e(e,c,o,a),d=Po({id:e.environmentId,label:e.label,source:`manual`,target:{httpBaseUrl:l.httpBaseUrl,wsBaseUrl:l.wsBaseUrl}}),f=a&&l.expiresAt?v4e({initialDescriptor:{httpBaseUrl:l.httpBaseUrl,wsBaseUrl:l.wsBaseUrl,bearerToken:l.bearerToken,expiresAt:l.expiresAt},renew:async()=>{let e=await c.acquire({forceRefresh:!0});return{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken,expiresAt:e.expiresAt??null}},onState:t=>{o()&&RX.getState().patch(e.environmentId,{providerAuthority:t})}}):null,p=KX({kind:`saved`,knownEnvironment:{...d,environmentId:e.environmentId},client:u,readiness:{bearerToken:l.bearerToken},tolerateReportedEnvironmentIdentity:a,refreshMetadata:async()=>{await S1(e,c,u,o)},...f?{ensureProviderAuthority:f.ensureLive,onDispose:f.dispose}:{},onConfigSnapshot:t=>{o()&&RX.getState().patch(e.environmentId,{descriptor:t.environment,serverConfig:t})},...b1(t=>{o()&&RX.getState().patch(e.environmentId,{descriptor:t.environment})})});try{if(!await y6e(e,S1(e,c,u,o,n?.role??null,n?.serverConfig??null,n?.signal))||!o())throw Error(`Saved environment changed while its connection was being acquired.`);return C1(p)}catch(t){throw a&&$Q(e.environmentId,c),o()&&g1(e.environmentId,t),await p.dispose().catch(()=>void 0),t}}async function E1(e,t){let n=L$.get(e.environmentId);if(n)return n;let r=K$(e.environmentId),i=V$.get(e.environmentId);if(i&&i.generation===r&&J$(i.record,e))return i.promise;let a=A6e(e,r,t).finally(()=>{V$.get(e.environmentId)?.promise===a&&V$.delete(e.environmentId)});return V$.set(e.environmentId,{generation:r,record:e,promise:a}),a}async function D1(e){await zl(e);let t=new Map(e.map(e=>[e.environmentId,e]));for(let[e,n]of V$){let r=t.get(e);(!r||!J$(r,n.record))&&q$(e)}let n=new Set(e.map(e=>e.environmentId)),r=[...L$.values()].filter(e=>e.kind===`saved`).map(e=>e.environmentId).filter(e=>!n.has(e));await Promise.all(r.map(async e=>{q$(e),await M1(e)}))}function O1(){W$?.stop(),W$=null}function k1(e){return H$.add(e),()=>{H$.delete(e)}}function A1(e){return L$.get(e)??null}function j6e(e){let t=A1(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function j1(){return T1()}async function M6e(){let e=E6e();if(!e)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let t=await k$e({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return L$.get(t.environmentId)||C1(KX({kind:`desktop-local`,knownEnvironment:{...Po({id:t.environmentId,label:e.label,source:`desktop-managed`,target:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}),environmentId:t.environmentId,label:t.label},client:O6e({environmentId:t.environmentId,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken}),...b1()}))}async function N6e(e){let t=an.make(e.runtimeId),n=L$.get(t);if(n)return n;f1(t);let r=JQ(),i=c4e(e.runtimeId,{apiClient:JG,getStoredDeviceKey:VQ,buildDeviceRegistration:RQ,controlSessionId:r.controlSessionId}),a=await i.acquireRoute(),o=a,s=Ece({acquireRoute:async()=>{let e=o;return o=null,e??i.acquireRoute()},acquireActionGrant:i.acquireActionGrant,journal:r,lifecycle:{onConnecting:()=>{f1(t)},onAuthenticated:()=>{p1(t)},onDisconnected:e=>{h1(t,e.reason)},onError:e=>{g1(t,Object.assign(Error(e.message),e))}}}),c=NQ(new TQ(a.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:s,makeClient:Tce(Un)})),l=KX({kind:`saved`,knownEnvironment:{...Po({id:t,label:e.label,source:`manual`,target:{httpBaseUrl:mr()?.target.httpBaseUrl??a.relayWebSocketUrl,wsBaseUrl:a.relayWebSocketUrl}}),environmentId:t},client:c,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>{m1(t,e)},...b1(e=>{RX.getState().patch(t,{descriptor:e.environment})})});try{let[,e]=await Promise.all([l.ensureBootstrapped(),c.server.getConfig()]);return m1(t,e),p1(t),C1(l)}catch(e){throw g1(t,e),await l.dispose().catch(()=>void 0),e}}function P6e(e){let t=an.make(e.runtimeId),n=L$.get(t);if(n)return Promise.resolve(n);let r=R$.get(t);if(r)return r;let i=N6e(e).finally(()=>{R$.delete(t)});return R$.set(t,i),i}async function M1(e){L$.get(e)?.kind===`saved`&&(RX.getState().clear(e),await w1(e).catch(()=>!1))}async function F6e(e){let t=GK(e);if(!t)throw Error(`Saved environment not found.`);let n=L$.get(e);if(!n){try{await P1(t)}catch(t){throw g1(e,t),t}return}f1(e);try{await n.reconnect()}catch(t){throw g1(e,t),t}}function N1(e){for(let t of e){let e=z$.get(t);e===void 0||e<=1?z$.delete(t):z$.set(t,e-1)}}async function I6e(e){let t=e.environmentId;z$.set(t,(z$.get(t)??0)+1);try{return A1(t)||await P1(e),!0}catch{return N1([t]),!1}}async function L6e(){await UK();let e=(await Promise.all(tYe().map(async e=>await I6e(e)?e.environmentId:null))).flatMap(e=>e===null?[]:[e]),t=!1;return()=>{t||(t=!0,N1(e))}}async function R6e(e){q$(e),VK.getState().remove(e),await ZK(e),await M1(e)}async function z6e(e){let t=an.make(e.environment.environmentId),{existing:n,replacedRecord:r}=N$e({environmentId:t,replacesEnvironmentId:e.environment.replacesEnvironmentId}),{kind:i,cmmdOrganizationId:a,cmmdProjectId:o,runtimeId:s,runtimeTicketExpiresAt:c}=e.environment,l={environmentId:t,label:e.environment.label,wsBaseUrl:un(e.environment.wsBaseUrl),httpBaseUrl:e.environment.httpBaseUrl,createdAt:n?.createdAt??l1(),lastConnectedAt:l1(),...i===void 0?{}:{kind:i},...a===void 0?{}:{cmmdOrganizationId:a},...o===void 0?{}:{cmmdProjectId:o},...s===void 0?{}:{runtimeId:s},...c===void 0?{}:{runtimeTicketExpiresAt:c}};BX(e.signal);let u=await P$e(n);q$(l.environmentId),await w1(l.environmentId).catch(()=>!1),r&&(q$(r.environmentId),await w1(r.environmentId).catch(()=>!1)),await P1(l,{bearerToken:e.bearerToken,registryExpectation:n&&!r?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}});let d=!1;try{return BX(e.signal),await F$e({record:l,replacedRecord:r,rollback:u,...e.signal?{signal:e.signal}:{}}),d=!0,BX(e.signal),VK.getState().upsert(UX(l)),l}catch(t){throw await w1(l.environmentId).catch(()=>!1),d&&await GX({record:l,replacedRecord:r,rollback:u}),BX(e.signal),t}}async function P1(e,t){if(!WX(e))return E1(e,t);let n=K$(e.environmentId),r=()=>Y$({record:e,generation:n,registryExpectation:t?.registryExpectation??{kind:`existing-record`,record:e}}),i=null;for(let n=0;n<u1;n+=1){BX(t?.signal);try{let n=await E1(e,t);return await VX(n.ensureBootstrapped(),t?.signal),n}catch(a){if(i=a,!r())throw a;if(await w1(e.environmentId).catch(()=>!1),BX(t?.signal),n>=7||!g6e(a))throw r()&&g1(e.environmentId,a),a;let o=_6e(n);t?.onBootstrapRetry?.({attempt:n+2,maxAttempts:u1,retryDelayMs:o,error:a}),r()&&RX.getState().patch(e.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await HX(o,t?.signal)}}let a=i instanceof Error?i:Error(String(i));throw r()&&g1(e.environmentId,a),a}async function B6e(e){await L$.get(e)?.ensureBootstrapped()}async function V6e(e){let t=L$.get(e);if(t?.ensureProviderAuthority){await t.ensureProviderAuthority();return}if(b4e(e))throw Error(`Cloud runtime provider authority is not available.`)}function H6e(e){if(W$?.queryClient===e)return W$.refCount+=1,()=>{!W$||W$.queryClient!==e||(--W$.refCount,W$.refCount===0&&O1())};O1(),G$=!1;let t=new vXe(()=>{G$&&(G$=!1,e.invalidateQueries({queryKey:MX.all}),e.invalidateQueries({queryKey:jX.all}))},{wait:100,leading:!1,trailing:!0});T1(),lr().catch(()=>void 0);let n=VK.subscribe(()=>{HK()&&D1(WK())});return UK().then(()=>D1(WK())).catch(()=>void 0),W$={queryClient:e,queryInvalidationThrottler:t,refCount:1,stop:()=>{n(),t.cancel()}},()=>{!W$||W$.queryClient!==e||(--W$.refCount,W$.refCount===0&&O1())}}var U6e=wte(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]);function W6e(e){return{environmentId:e.environmentId,threadId:e.threadId}}function G6e(e){return{draftId:e}}function K6e(e){return!e.environmentId||!e.threadId?null:Lo(e.environmentId,e.threadId)}function q6e(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:Lo(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}var J6e=F.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return vte(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function F1(e){let t=(0,cl.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Zt(`relative overflow-hidden rounded-sm bg-muted [--skeleton-highlight:--alpha(var(--color-white)/64%)] after:absolute after:inset-0 after:animate-skeleton after:bg-[linear-gradient(120deg,transparent_40%,var(--skeleton-highlight),transparent_60%)] motion-reduce:after:content-none dark:[--skeleton-highlight:--alpha(var(--color-white)/4%)]`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Nr.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function Y6e(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=Kt(i),[,o]=F.useState(!1),s=Gt(Z6e).current,c=Gt(X6e).current,l=F.useRef(0),u=F.useRef(!0),d=F.useRef([]),f=F.useRef(null),p=Kt(()=>{u.current||(u.current=!0,o(e=>!e))}),m=Kt((e,t)=>{c.set(e,t),p()}),h=Kt(e=>{c.delete(e),p()}),g=Kt(e=>{let t=new Map;return n.current.length=0,r&&(r.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),n.current[e.index]=e.element,r&&(r.current[e.index]=e.registration.label===void 0?e.registration.textRef?.current?.textContent??e.element.textContent:e.registration.label)}),l.current=n.current.length,t});function _(e){if(f.current?.disconnect(),f.current=null,typeof MutationObserver!=`function`||e.length<2)return;let t=new MutationObserver(n=>{if(!e8e(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&I1(r,n)>0){t.disconnect(),p();return}r=n}});f.current=t;let n=new Set;for(let t=1;t<e.length;t+=1){let r=$6e(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=Kt(()=>{let[e,t]=Q6e(c),n=g(e);_(t),d.current=e,u.current=!1,s.forEach(e=>e(n)),a(n)});Jt(()=>(u.current||g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),Jt(()=>{u.current&&v()}),Jt(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=Kt(e=>(s.add(e),()=>{s.delete(e)})),b=F.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,Nr.jsx)(Ste.Provider,{value:b,children:t})}function X6e(){return new Map}function Z6e(){return new Set}function Q6e(e){let t=new Set,n=[],r=[];e.forEach((e,i)=>{if(!i.isConnected)return;let a=e.index,o={index:a??-1,element:i,registration:e};a===null?r.push(o):a>=0&&(t.add(a),n.push(o))});let i=0;return r.sort((e,t)=>I1(e.element,t.element)),r.forEach(e=>{for(;t.has(i);)i+=1;e.index=i,n.push(e),i+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}function $6e(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function e8e(e){for(let t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}function I1(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function L1(e){let t=e.browser,n=t?{openSession:t.openSession,listSessions:t.listSessions,closeSession:t.closeSession,getSession:t.getSession,command:t.command,clearBrowsingData:t.clearBrowsingData,attachDisplay:t.attachDisplay,addDisplayIceCandidate:async e=>{await t.addDisplayIceCandidate(e)},onEvent:(e,n)=>t.onEvent(e,n)}:void 0;return{...n?{browser:n}:{},attachments:{createUploadUrl:t=>e.attachments.createUploadUrl(t),delete:t=>e.attachments.delete(t)},computer:{input:t=>e.computer.input(t)},threadDevRuntime:{get:t=>e.threadDevRuntime.get(t),allocatePort:t=>e.threadDevRuntime.allocatePort(t),release:t=>e.threadDevRuntime.release(t)},devTunnel:{register:t=>e.devTunnel.register(t),unregister:t=>e.devTunnel.unregister(t),list:t=>e.devTunnel.list(t)},terminal:{open:t=>e.terminal.open(t),write:t=>e.terminal.write(t),resize:t=>e.terminal.resize(t),signal:t=>e.terminal.signal(t),clear:t=>e.terminal.clear(t),restart:t=>e.terminal.restart(t),close:t=>e.terminal.close(t),onEvent:t=>e.terminal.onEvent(t)},projects:{searchContents:e.projects.searchContents,searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},workspace:{environmentPreflight:e.workspace.environmentPreflight,ensureScratch:e.workspace.ensureScratch},shell:{openInEditor:t=>e.shell.openInEditor(t)},git:{pull:e.git.pull,refreshStatus:e.git.refreshStatus,onStatus:(t,n,r)=>e.git.onStatus(t,n,r),listBranches:e.git.listBranches,createWorktree:e.git.createWorktree,removeWorktree:e.git.removeWorktree,createBranch:e.git.createBranch,checkout:e.git.checkout,init:e.git.init,resolvePullRequest:e.git.resolvePullRequest,preparePullRequestThread:e.git.preparePullRequestThread},pullRequests:{list:t=>e.pullRequests.list(t),listStats:t=>e.pullRequests.listStats(t),detail:t=>e.pullRequests.detail(t),activity:t=>e.pullRequests.activity(t),threadComments:t=>e.pullRequests.threadComments(t),diffFileContents:t=>e.pullRequests.diffFileContents(t),runAction:t=>e.pullRequests.runAction(t),update:t=>e.pullRequests.update(t),comment:t=>e.pullRequests.comment(t),updateComment:t=>e.pullRequests.updateComment(t),submitReview:t=>e.pullRequests.submitReview(t),replyToThread:t=>e.pullRequests.replyToThread(t),setThreadResolution:t=>e.pullRequests.setThreadResolution(t),setReaction:t=>e.pullRequests.setReaction(t),invalidate:t=>e.pullRequests.invalidate(t),reviewerCandidates:t=>e.pullRequests.reviewerCandidates(t),requestReviewers:t=>e.pullRequests.requestReviewers(t)},orchestration:{dispatchCommand:e.orchestration.dispatchCommand,getTurnDiff:e.orchestration.getTurnDiff,getFullThreadDiff:e.orchestration.getFullThreadDiff,subscribeShell:(t,n)=>e.orchestration.subscribeShell(t,n),subscribeThread:(t,n,r)=>e.orchestration.subscribeThread(t,n,r)}}}function R1(e){if(typeof window>`u`||!e)return;let t=A1(e);return t?L1(t.client):void 0}function t8e(e){let t=(0,cl.c)(4),n;t[0]===e?n=t[1]:(n=()=>A1(e),t[0]=e,t[1]=n);let r=(0,F.useSyncExternalStore)(k1,n,n8e),i,a;return t[2]===r?a=t[3]:(a=r?L1(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function n8e(){return null}function r8e(e){let t=R1(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}var z1=`forge:last-editor`;function i8e(e){let t=(0,cl.c)(5),[n,r]=Cl(z1,null,zn),i;bb0:{if(n&&e.includes(n)){i=n;break bb0}let r;t[0]===e?r=t[1]:(r=en.find(t=>e.includes(t.id))?.id??null,t[0]=e,t[1]=r),i=r}let a=i,o;return t[2]!==a||t[3]!==r?(o=[a,r],t[2]=a,t[3]=r,t[4]=o):o=t[4],o}function B1(e){let t=new Set(e),n=yl(z1,zn);if(n&&t.has(n))return n;let r=en.find(e=>t.has(e.id))?.id??null;return r&&bl(z1,r,zn),r??null}async function a8e(e,t){let{availableEditors:n}=await e.server.getConfig(),r=B1(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}function V1(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var H1=Object.freeze({data:null,error:null,cause:null,isPending:!1}),U1=Object.freeze({...H1,isPending:!0}),o8e=Wt(H1).pipe(Ut,Vt(`git-status:null`)),W1=()=>void 0,G1=new Map,s8e=new Set,K1=new Map,q1=new Map,c8e=1e3,J1=gte(e=>(s8e.add(e),Wt(U1).pipe(Ut,Vt(`git-status:${e}`))));function Y1(e){return e.environmentId===null||V1(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function X1(e){if(e.environmentId===null)return null;let t=A1(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function Z1(e){let t=Y1(e);return t===null?H1:Ht.get(J1(t))}function l8e(e,t){let n=Y1(e);if(n===null)return W1;let r=G1.get(n);return r?(r.refCount+=1,()=>Q1(n)):(G1.set(n,{refCount:1,unsubscribe:f8e(n,e,t)}),()=>Q1(n))}function u8e(e,t){let n=Y1(e),r=V1(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??X1(e)?.client;if(!i)return Promise.resolve(Z1(e).data);let a=K1.get(n);if(a)return a;let o=q1.get(n)??0;if(Date.now()-o<c8e)return Promise.resolve(Z1(e).data);q1.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{K1.delete(n)});return K1.set(n,s),s}function d8e(e){let t=(0,cl.c)(4),n=Y1(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>l8e({environmentId:e.environmentId,cwd:e.cwd}),i=[e.environmentId,e.cwd],t[0]=e.cwd,t[1]=e.environmentId,t[2]=r,t[3]=i):(r=t[2],i=t[3]),(0,F.useEffect)(r,i);let a=cr(n===null?o8e:J1(n));return n===null?H1:a}function Q1(e){let t=G1.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),G1.delete(e)))}function f8e(e,t,n){let r=V1(t.cwd);if(r===null)return W1;let i=null,a=W1,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:X1(t);if(!o){i!==null&&(a(),a=W1,i=null),$1(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=p8e(e,r,o.client))},s=n?W1:k1(o);return o(),()=>{s(),a()}}function p8e(e,t,n){return $1(e),n.onStatus({cwd:t},t=>{Ht.set(J1(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{$1(e)}})}function $1(e){let t=J1(e),n=Ht.get(t),r=n.data===null?U1:{...n,error:null,cause:null,isPending:!0};(n.data!==r.data||n.error!==r.error||n.cause!==r.cause||n.isPending!==r.isPending)&&Ht.set(t,r)}function e0(e,t){return Wt(t).pipe(Ut,Vt(e))}function t0(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var m8e=[],h8e=[],g8e=[],_8e=e=>e?.availableEditors??m8e,v8e=e=>e?.keybindings??h8e,y8e=e=>e?.keybindingsConfigPath??null,b8e=e=>e?.observability??null,x8e=e=>e?.providers??g8e,S8e=e=>e?.settings??bne,n0=e0(`server-welcome`,null),r0=e0(`server-config`,null),i0=e0(`server-config-updated`,null),C8e=e0(`server-providers-updated`,null);function a0(){return Ht.get(r0)}function w8e(){return Ht.get(i0)}function o0(e){u0(e),d0({providers:e.providers}),f0(t0(e),`snapshot`)}function T8e(e){switch(e.type){case`snapshot`:o0(e.config);return;case`keybindingsUpdated`:{let t=a0();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};u0(n),f0(t0(n),e.type);return}case`providerStatuses`:s0(e.payload);return;case`settingsUpdated`:c0(e.payload.settings);return;case`environmentUpdated`:l0(e.payload.environment);return}}function s0(e){let t=a0();if(d0(e),!t)return;let n={...t,providers:e.providers};u0(n),f0(t0(n),`providerStatuses`)}function c0(e){let t=a0();if(!t)return;let n={...t,settings:e};u0(n),f0(t0(n),`settingsUpdated`)}function l0(e){let t=a0();if(SK()?.environmentId===e.environmentId&&CK(e),!t)return;let n={...t,environment:e};u0(n),f0(t0(n),`environmentUpdated`)}function E8e(e){Ht.set(n0,e)}function D8e(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&E8e(e.payload)}),e.subscribeConfig(e=>{T8e(e)})];return a0()===null&&e.getConfig().then(e=>{t||a0()!==null||o0(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var O8e=1;function u0(e){Ht.set(r0,e)}function d0(e){Ht.set(C8e,e)}function f0(e,t){Ht.set(i0,{id:O8e++,payload:e,source:t})}function p0(e,t){let n=(0,F.useRef)(t);n.current=t;let r=(0,F.useCallback)(e=>{e!==null&&n.current(e)},[]);Ene(e,r,{immediate:!0})}function k8e(){return cr(r0)}function m0(){return cr(r0,S8e)}function A8e(){return cr(r0,x8e)}function j8e(){return cr(r0,v8e)}function M8e(){return cr(r0,_8e)}function N8e(){return cr(r0,y8e)}function P8e(){return cr(r0,b8e)}function F8e(e){p0(n0,e)}function I8e(e){p0(i0,e)}function L8e(e){let t=[];for(let n of e){let e=n.children??[];if(e.length>0){t.push({item:n,isGroupLabel:!0});for(let n of e)t.push({item:n,isGroupLabel:!1});continue}Array.isArray(n.children)||t.push({item:n,isGroupLabel:!1})}return t}function R8e(e){let t=document.createElement(`div`);return t.textContent=e,t.className=`px-2 pt-1.5 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,t}function z8e(e){let t=document.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled,t.className=e.disabled?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-muted-foreground/50 cursor-not-allowed`:e.destructive?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-destructive transition-colors hover:bg-accent`:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-popover-foreground transition-colors hover:bg-accent`,t}function B8e(e,t){return new Promise(n=>{let r=document.createElement(`div`);r.style.cssText=`position:fixed;inset:0;z-index:9999`;let i=document.createElement(`div`);i.className=`fixed z-[10000] min-w-[160px] rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg/5 outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]`;let a=t?.x??0,o=t?.y??0;i.style.top=`${o}px`,i.style.left=`${a}px`;function s(e){document.removeEventListener(`keydown`,c),r.remove(),i.remove(),n(e)}function c(e){e.key===`Escape`&&(e.preventDefault(),s(null))}r.addEventListener(`mousedown`,()=>s(null)),document.addEventListener(`keydown`,c);let l=!1;for(let{item:t,isGroupLabel:n}of L8e(e)){if(n){i.appendChild(R8e(t.label));continue}let e=t.destructive===!0||t.id===`delete`,r=t.disabled===!0;if(e&&!l){let e=document.createElement(`div`);e.className=`-mx-1 my-1 h-px bg-border`,i.appendChild(e),l=!0}let a=z8e({label:t.label,disabled:r,destructive:e});r||a.addEventListener(`click`,()=>s(t.id)),i.appendChild(a)}document.body.appendChild(r),document.body.appendChild(i),requestAnimationFrame(()=>{let e=i.getBoundingClientRect();e.right>window.innerWidth&&(i.style.left=`${window.innerWidth-e.width-4}px`),e.bottom>window.innerHeight&&(i.style.top=`${window.innerHeight-e.height-4}px`)})})}var h0;function V8e(){return g0(j1().client)}function g0(e){return{getConfig:e.server.getConfig,refreshProviders:e.server.refreshProviders,startProviderAuth:e.server.startProviderAuth,repairProviderAuthRuntime:e.server.repairProviderAuthRuntime,disconnectProviderAuth:e.server.disconnectProviderAuth,getProviderAuthSession:e.server.getProviderAuthSession,cancelProviderAuth:e.server.cancelProviderAuth,submitProviderAuthCode:e.server.submitProviderAuthCode,syncPersonalCodexToCloud:e.server.syncPersonalCodexToCloud,syncPersonalClaudeToCloud:e.server.syncPersonalClaudeToCloud,upsertKeybinding:e.server.upsertKeybinding,removeKeybinding:e.server.removeKeybinding,getSettings:e.server.getSettings,updateSettings:e.server.updateSettings,updateEnvironmentDisplayName:async t=>{let n=await e.server.updateEnvironmentDisplayName({displayName:t});return l0(n.environment),n}}}function H8e(e,t){return{...e,...t,dialogs:{...e.dialogs,...t.dialogs},shell:{...e.shell,...t.shell},contextMenu:{...e.contextMenu,...t.contextMenu},persistence:{...e.persistence,...t.persistence},server:{...e.server,...t.server}}}function U8e(e){return{dialogs:{pickFolder:async()=>window.desktopBridge?window.desktopBridge.pickFolder():null,confirm:async e=>window.desktopBridge?window.desktopBridge.confirm(e):window.confirm(e)},shell:{openInEditor:(t,n)=>e.shell.openInEditor({cwd:t,editor:n}),openExternal:async e=>{if(window.desktopBridge){if(!await window.desktopBridge.openExternal(e))throw Error(`Unable to open link.`);return}window.open(e,`_blank`,`noopener,noreferrer`)}},contextMenu:{show:async(e,t)=>window.desktopBridge?window.desktopBridge.showContextMenu(e,t):B8e(e,t)},persistence:{getClientSettings:Il,setClientSettings:Ll,getSavedEnvironmentRegistry:Rl,setSavedEnvironmentRegistry:zl,getSavedEnvironmentSecret:Bl,setSavedEnvironmentSecret:Vl,removeSavedEnvironmentSecret:Hl},server:g0(e)}}function _0(){if(typeof window>`u`)return;if(h0)return h0;let e=U8e(j1().client);return window.nativeApi?(h0=H8e(e,window.nativeApi),h0):(h0=e,h0)}function W8e(){let e=_0();if(!e)throw Error(`Local API not found`);return e}var G8e=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,K8e=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function q8e(e){let t=e.trim();return t.length===0?``:/^(['"]).*\1$/u.test(t)||/^[a-zA-Z][a-zA-Z0-9-]*$/u.test(t)?t:`"${t.replaceAll(`"`,``)}"`}function J8e(e){let t=e.split(`,`).map(q8e).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var v0={fontSans:`--font-sans`,fontMono:`--font-mono`,fontComposer:`--font-composer`,fontTerminal:`--font-terminal`,promptFontSize:`--forge-prompt-font-size`,terminalFontSize:`--forge-terminal-font-size`,glassOpacity:`--glass-opacity`};function Y8e(e,t){let n=[[v0.fontSans,t.fontFamilySans,G8e],[v0.fontMono,t.fontFamilyCode,K8e],[v0.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[v0.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=J8e(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(v0.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(v0.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(v0.glassOpacity,`${String(t.glassOpacity)}%`),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}var y0=`themeId`,b0=`forge:theme-boot:v1`;function X8e(e,t){try{window.localStorage.setItem(b0,JSON.stringify({appearance:t,background:e}))}catch{}}function Z8e(){try{window.localStorage.removeItem(b0)}catch{}}function x0(){return typeof document>`u`?null:document.documentElement}function S0(){let e=x0();if(e!==null){for(let t of nn)e.style.removeProperty(_n[t]);delete e.dataset[y0],Z8e()}}function Q8e(e,t){let n=x0();if(n===null)return;let r=t===`dark`?e.dark:e.light;for(let e of nn){let t=r[e];if(t===void 0){n.style.removeProperty(_n[e]);continue}n.style.setProperty(_n[e],t)}n.dataset[y0]=e.id,r.background!==void 0&&X8e(r.background,t)}function $8e(e,t){if(e===`forge`){S0();return}let n=lne(e);if(n===void 0){S0();return}Q8e(n,t)}function C0(e,t){if(!Fe(e)||!Fe(t))return t;let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=Fe(t)&&Fe(r)?C0(t,r):r}return n}var w0=`[CLIENT_SETTINGS]`,T0=new Set,E0=An,D0=!1,O0=null;function e5e(){for(let e of T0)e()}function k0(){return E0}function A0(e){E0=e,e5e()}function t5e(e){return T0.add(e),n5e(),()=>{T0.delete(e)}}async function n5e(){if(D0)return;if(O0)return O0;let e=(async()=>{try{let e=await Il();e&&A0(e)}catch(e){console.error(`${w0} hydrate failed`,e)}finally{D0=!0}})().finally(()=>{O0===e&&(O0=null)});return O0=e,O0}function r5e(e){A0(e),Ll(e).catch(e=>{console.error(`${w0} persist failed`,e)})}var i5e=new Set(Kte(yne.fields));function a5e(e){let t={},n={};for(let[r,i]of Object.entries(e))i5e.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function j0(e){let t=m0(),n=(0,F.useSyncExternalStore)(t5e,k0,()=>An),r=(0,F.useMemo)(()=>({...t,...n}),[n,t]);return(0,F.useMemo)(()=>e?e(r):r,[r,e])}function M0(){let e=(0,cl.c)(2),t=o5e,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(Ate)},e[0]=n):n=e[0];let r=n,i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={updateSettings:t,resetSettings:r},e[1]=i):i=e[1],i}function o5e(e){let{serverPatch:t,clientPatch:n}=a5e(e);if(Object.keys(t).length>0){let e=a0();e&&c0(C0(e.settings,t)),j1().client.server.updateSettings(t)}Object.keys(n).length>0&&r5e({...k0(),...n})}var s5e=`forge:theme`,N0=`theme-color`,c5e=`meta[name="${N0}"][data-dynamic-theme-color="true"]`,P0=`(prefers-color-scheme: dark)`,l5e={dark:`#0a0a0a`,light:`#ffffff`};function u5e(){return typeof window<`u`&&typeof localStorage<`u`}function F0(e){return e===`system`||e===`light`||e===`dark`}function I0(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function d5e(){if(!u5e())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(Ol);if(e){let t=jl(JSON.parse(e));return{theme:F0(t.theme)?t.theme:`system`,uiFontSize:I0(t.uiFontSize,16),codeFontSize:I0(t.codeFontSize,13)}}let t=window.localStorage.getItem(s5e);return{theme:F0(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function f5e(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(P0).matches?`dark`:`light`}function L0(e){return e===`system`?f5e():e}function p5e(){let e=document.querySelector(c5e);return e||(e=document.createElement(`meta`),e.name=N0,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function R0(e){let t=e?.trim().toLowerCase();return!t||t===`transparent`||t===`rgba(0, 0, 0, 0)`||t===`rgba(0 0 0 / 0)`?null:e?.trim()??null}function m5e(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function h5e(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function z0(e=h5e()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=R0(getComputedStyle(m5e()).backgroundColor),n=R0(getComputedStyle(document.body).backgroundColor),r=t??n??l5e[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,p5e().setAttribute(`content`,r)}function g5e(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function B0(e,t=!1){let n=L0(e);return typeof document>`u`||typeof window>`u`?n:(t&&document.documentElement.classList.add(`no-transitions`),document.documentElement.classList.toggle(`dark`,n===`dark`),document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=n,z0(n),g5e(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function V0(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${I0(e,16)}px`)}function H0(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${I0(e,13)}px`)}function U0(e){V0(e.uiFontSize),H0(e.codeFontSize)}if(typeof document<`u`){let e=d5e();B0(e.theme),U0(e)}function _5e(){let e=(0,cl.c)(34),t=j0(x5e),n=j0(b5e),r=j0(y5e),i=j0(v5e),{updateSettings:a}=M0(),o;e[0]===t?o=e[1]:(o=()=>L0(t),e[0]=t,e[1]=o);let[s,c]=(0,F.useState)(o),l;e[2]===a?l=e[3]:(l=e=>{a({theme:e}),c(B0(e,!0))},e[2]=a,e[3]=l);let u=l,d;e[4]===a?d=e[5]:(d=e=>{a({themeId:e})},e[4]=a,e[5]=d);let f=d,p;e[6]===a?p=e[7]:(p=e=>{let t=I0(e,16);a({uiFontSize:t}),V0(t)},e[6]=a,e[7]=p);let m=p,h;e[8]===a?h=e[9]:(h=e=>{let t=I0(e,13);a({codeFontSize:t}),H0(t)},e[8]=a,e[9]=h);let g=h,_,v;e[10]===t?(_=e[11],v=e[12]):(_=()=>{c(B0(t))},v=[t],e[10]=t,e[11]=_,e[12]=v),(0,F.useEffect)(_,v);let y,b;e[13]!==i||e[14]!==r?(y=()=>{U0({uiFontSize:r,codeFontSize:i})},b=[r,i],e[13]=i,e[14]=r,e[15]=y,e[16]=b):(y=e[15],b=e[16]),(0,F.useEffect)(y,b);let x,S;e[17]!==s||e[18]!==n?(S=()=>{$8e(n,s===`dark`?`dark`:`light`)},x=[n,s],e[17]=s,e[18]=n,e[19]=x,e[20]=S):(x=e[19],S=e[20]),(0,F.useEffect)(S,x);let C,w;e[21]===t?(C=e[22],w=e[23]):(C=()=>{if(t!==`system`||typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(P0),n=()=>{c(B0(`system`,!0))};return e.addEventListener(`change`,n),()=>{e.removeEventListener(`change`,n)}},w=[t],e[21]=t,e[22]=C,e[23]=w),(0,F.useEffect)(C,w);let T;return e[24]!==i||e[25]!==s||e[26]!==g||e[27]!==u||e[28]!==f||e[29]!==m||e[30]!==t||e[31]!==n||e[32]!==r?(T={theme:t,setTheme:u,themeId:n,setThemeId:f,resolvedTheme:s,uiFontSize:r,codeFontSize:i,setUiFontSize:m,setCodeFontSize:g},e[24]=i,e[25]=s,e[26]=g,e[27]=u,e[28]=f,e[29]=m,e[30]=t,e[31]=n,e[32]=r,e[33]=T):T=e[33],T}function v5e(e){return e.codeFontSize}function y5e(e){return e.uiFontSize}function b5e(e){return e.themeId}function x5e(e){return e.theme}function S5e(){let e=(0,cl.c)(10),t=j0(A5e),n=j0(k5e),r=j0(O5e),i=j0(D5e),a=j0(E5e),o=j0(T5e),s=j0(w5e),c=j0(C5e),l,u;e[0]!==n||e[1]!==r||e[2]!==t||e[3]!==i||e[4]!==s||e[5]!==c||e[6]!==a||e[7]!==o?(l=()=>{typeof document>`u`||Y8e(document.documentElement,{fontFamilyCode:n,fontFamilyComposer:r,fontFamilySans:t,fontFamilyTerminal:i,fontSmoothing:s,glassOpacity:c,promptFontSize:a,terminalFontSize:o})},u=[n,r,t,i,s,c,a,o],e[0]=n,e[1]=r,e[2]=t,e[3]=i,e[4]=s,e[5]=c,e[6]=a,e[7]=o,e[8]=l,e[9]=u):(l=e[8],u=e[9]),(0,F.useEffect)(l,u)}function C5e(e){return e.glassOpacity}function w5e(e){return e.fontSmoothing}function T5e(e){return e.terminalFontSize}function E5e(e){return e.promptFontSize}function D5e(e){return e.fontFamilyTerminal}function O5e(e){return e.fontFamilyComposer}function k5e(e){return e.fontFamilyCode}function A5e(e){return e.fontFamilySans}function j5e(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var W0=new Map;function G0(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=W0.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,j5e(e,t));return W0.set(n,i),i}function M5e(e,t){return G0(t,!0).format(new Date(e))}function N5e(e,t){return G0(t,!1).format(new Date(e))}function K0(e){let t=Date.now()-new Date(e).getTime();if(t<0)return{value:`just now`,suffix:null};let n=Math.floor(t/1e3);if(n<60)return{value:`just now`,suffix:null};let r=Math.floor(n/60);if(r<60)return{value:`${r}m`,suffix:`ago`};let i=Math.floor(r/60);return i<24?{value:`${i}h`,suffix:`ago`}:{value:`${Math.floor(i/24)}d`,suffix:`ago`}}function P5e(e){let t=K0(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}var F5e=new Set([`tool.started`,`task.started`,`context-window.updated`,`text-generation.usage`,`worktree.stage`,`launch.agent-starting`]);function q0(e){return F5e.has(e.kind)||e.summary===`Checkpoint captured`}function I5e(e,t){return!t.latestTurnId||e.turnId===t.latestTurnId||L5e(e)?!0:R5e(e,t.latestTurnStartedAt)}function L5e(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function R5e(e,t){return e.turnId!==null||e.tone!==`error`||t===null?!1:e.createdAt>=t}var z5e=[{value:`codex`,label:`Codex`,available:!0},{value:`claudeAgent`,label:`Claude`,available:!0},{value:`cmmd`,label:`CMMD`,available:!0},{value:`ollama`,label:`Ollama`,available:!1},{value:`cursor`,label:`Cursor`,available:!1}];function B5e(e){if(!Number.isFinite(e)||e<0)return`0ms`;if(e<1e3)return`${Math.max(1,Math.round(e))}ms`;if(e<1e4)return`${(e/1e3).toFixed(1)}s`;if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n===0?`${t}m`:n===60?`${t+1}m`:`${t}m ${n}s`}function V5e(e,t){if(!t)return null;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)||r<n?null:B5e(r-n)}function J0(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function H5e(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?J0(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function Y0(e){switch(e){case`command_execution_approval`:case`exec_command_approval`:return`command`;case`file_read_approval`:return`file-read`;case`file_change_approval`:case`apply_patch_approval`:return`file-change`;default:return null}}function X0(e){let t=e?.toLowerCase();return t?t.includes(`stale pending approval request`)||t.includes(`stale pending user-input request`)||t.includes(`unknown pending approval request`)||t.includes(`unknown pending permission request`)||t.includes(`unknown pending user-input request`):!1}function U5e(e){let t=new Map,n=[...e].toSorted(m2);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?Sn.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?Y0(n.requestType):null,a=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`approval.requested`&&r&&i){t.set(r,{requestId:r,requestKind:i,createdAt:e.createdAt,...a?{detail:a}:{}});continue}if(e.kind===`approval.resolved`&&r){t.delete(r);continue}if(e.kind===`provider.approval.respond.failed`&&r&&X0(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function W5e(e){let t=e?.questions;if(!Array.isArray(t))return null;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||typeof t.header!=`string`||typeof t.question!=`string`||!Array.isArray(t.options))return null;let n=t.options.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.description!=`string`?null:{label:t.label,description:t.description}}).filter(e=>e!==null);return n.length===0?null:{id:t.id,header:t.header,question:t.question,options:n,multiSelect:t.multiSelect===!0}}).filter(e=>e!==null);return n.length>0?n:null}function G5e(e){let t=new Map,n=[...e].toSorted(m2);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?Sn.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=W5e(n);if(!i)continue;t.set(r,{requestId:r,createdAt:e.createdAt,questions:i});continue}if(e.kind===`user-input.resolved`&&r){t.delete(r);continue}e.kind===`provider.user-input.respond.failed`&&r&&X0(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function K5e(e,t){if(!t)return null;let n=[...e].toSorted(m2),r=null;for(let e of n){let t=Q0(e.payload&&typeof e.payload==`object`?e.payload:null);t&&(r={request:t,turnId:e.turnId})}return!r||r.turnId!==t?null:r.request}function q5e(e,t){let n=[...e].toSorted(m2),r=n.filter(e=>e.kind===`turn.plan.updated`),i=(t?r.findLast(e=>e.turnId===t):void 0)??r.at(-1)??null;if(!i)return null;let a=i.payload&&typeof i.payload==`object`?i.payload:null,o=a?.plan;if(!Array.isArray(o))return null;let s=o.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.step!=`string`)return null;let n=t.status===`completed`||t.status===`inProgress`?t.status:`pending`;return{step:t.step,status:n}}).filter(e=>e!==null);if(s.length===0)return null;let c=i.turnId!==null&&n.some(e=>e.kind===`turn.completed`&&e.turnId===i.turnId&&m2(i,e)<0)?s.map(e=>e.status===`inProgress`?{...e,status:`completed`}:e):s;return{createdAt:i.createdAt,turnId:i.turnId,...a&&`explanation`in a?{explanation:a.explanation}:{},steps:c}}function Z0(e,t){if(t){let n=[...e].filter(e=>e.turnId===t).toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);if(n)return a2(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?a2(n):null}function J5e(e){let t=e.threads.find(t=>t.id===e.threadId)?.proposedPlans??[];if(!e.latestTurnSettled){let t=e.latestTurn?.sourceProposedPlan;if(t){let n=e.threads.find(e=>e.id===t.threadId)?.proposedPlans.find(e=>e.id===t.planId);if(n)return a2(n)}}return Z0(t,e.latestTurn?.turnId??null)}function Y5e(e){return e!==null&&e.implementedAt===null}function X5e(e,t,n){let r=Z5e(),i={latestTurnId:t,latestTurnStartedAt:n??null};return a7e([...e].toSorted(m2).filter(e=>I5e(e,i)).filter(e=>!q0(e)).filter(e=>r||e.kind!==`runtime.warning`).filter(e=>!Q5e(e)).map($5e)).map(({activityKind:e,collapseKey:t,...n})=>n)}function Z5e(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function Q5e(e){if(e.kind!==`tool.updated`&&e.kind!==`tool.completed`)return!1;let t=e.payload&&typeof e.payload==`object`?e.payload:null;return typeof t?.detail==`string`&&t.detail.startsWith(`ExitPlanMode:`)}function $5e(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=b7e(t),r=E7e(t),i=x7e(t),a=e.kind===`task.progress`||e.kind===`task.completed`,o=a&&typeof t?.summary==`string`&&t.summary.length>0?t.summary:null,s=a&&!o&&typeof t?.detail==`string`&&t.detail.length>0?t.detail:null,c=o||s,l={id:e.id,createdAt:e.createdAt,label:c||e.summary,tone:e.kind===`task.progress`?`thinking`:e.tone,activityKind:e.kind},u=w7e(t),d=T7e(t);if(!s&&t&&typeof t.detail==`string`&&t.detail.length>0){let e=d2(t.detail).output;e&&(l.detail=e)}n.command&&(l.command=n.command),n.rawCommand&&(l.rawCommand=n.rawCommand),r.length>0&&(l.changedFiles=r),i&&(l.toolTitle=i),u&&(l.itemType=u),d&&(l.requestKind=d);let f=e7e(t);if(f)l.githubConfirmation=f,l.tone=`approval`,l.label=`GitHub action needs approval`,l.toolTitle=e2(f.operation),l.detail=t2(f);else{let e=Q0(t);e&&(l.githubActionRequired=e,l.tone=`approval`,l.label=n2(e.action),l.toolTitle=`GitHub setup required`,l.detail=i2(e))}let p=l7e(l);return p&&(l.collapseKey=p),l}function e7e(e){for(let t of $0(e)){if(t.userActionRequired!==`confirm_github_tool`)continue;let e=o2(t.confirmation),n=o2(e?.request),r=s2(e?.confirmationId),i=s2(e?.toolName),a=s2(e?.operation);if(!(!r||!i||!a||!n))return{confirmationId:r,toolName:i,operation:a,request:n}}return null}function Q0(e){let t=$0(e)[0];if(!t)return null;let n=s2(t.userActionRequired);return!n||n===`confirm_github_tool`?null:{action:n,toolName:s2(t.toolName),message:s2(t.error)??s2(t.message)}}function $0(e){if(!e)return[];let t=[],n=new Set,r=(e,i)=>{if(i>8||e==null)return;if(typeof e==`string`){let n=s2(e);if(!n)return;let r=t7e(n);r&&s2(r.userActionRequired)&&t.push(r);return}if(typeof e!=`object`||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let t of e)r(t,i+1);return}let a=e;if(s2(a.userActionRequired)){t.push(a);return}for(let e of Object.values(a))r(e,i+1)};return r(e,0),t}function t7e(e){try{return o2(JSON.parse(e))}catch{return null}}function e2(e){switch(e){case`create_repository`:return`Create GitHub repository`;case`link_project_repository`:return`Link project repository`;case`push_branch`:return`Push Git branch`;case`create_pull_request`:return`Create pull request`;case`rerun_workflow`:return`Rerun GitHub Actions workflow`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function t2(e){return[s2(e.request.repoFullName)??(s2(e.request.owner)&&s2(e.request.name)?`${s2(e.request.owner)}/${s2(e.request.name)}`:null),s2(e.request.cwd),s2(e.request.branch),s2(e.request.title)].filter(Boolean).join(` - `)}function n2(e){switch(e){case`connect_github`:return`Connect GitHub to continue`;case`connect_cmmd`:return`Forge couldn't authorize this action`;case`start_from_authenticated_forge_session`:return`Open this thread in Forge`;case`link_project_repository`:return`Link this project to GitHub`;case`create_branch`:return`Create a branch before pushing`;case`retry_in_user_vm`:return`Retry in the project VM`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function r2(e){switch(e){case`connect_github`:return`Connect GitHub so agents can create repos, push branches, and open PRs.`;case`connect_cmmd`:return`Reconnect Forge, then retry. Your conversation is preserved.`;case`start_from_authenticated_forge_session`:return`Open it in Forge so this action uses your signed-in account.`;case`link_project_repository`:return`Link a GitHub repo to this project before pushing or opening PRs.`;case`create_branch`:return`Forge needs a branch before it can push to GitHub.`;case`retry_in_user_vm`:return`This has to run from the project's cloud VM.`;default:return`Finish the required setup, then retry.`}}function i2(e){return e.action===`connect_cmmd`?r2(e.action):e.message??r2(e.action)}function n7e(e,t){return e.action===t.action&&e.toolName===t.toolName&&e.message===t.message}function r7e(e){switch(e){case`connect_cmmd`:return`Reconnect Forge`;case`connect_github`:return`Connect GitHub`;default:return`Open Git settings`}}function i7e(e){return[`The required Forge GitHub setup has been completed by the user.`,e.toolName?`Retry the previous GitHub tool request for \`${e.toolName}\`.`:`Retry the previous GitHub tool request.`,`Continue the previous GitHub lifecycle request using Forge brokered GitHub tools only.`,"Do not use shell `gh` or direct GitHub CLI commands."].join(`
1021
+ `)}function a7e(e){let t=[];for(let n of e){let e=t.at(-1);if(e&&o7e(e,n)){t[t.length-1]=s7e(e,n);continue}t.push(n)}return t}function o7e(e,t){return e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`||t.activityKind!==`tool.updated`&&t.activityKind!==`tool.completed`||e.activityKind===`tool.completed`?!1:e.collapseKey!==void 0&&e.collapseKey===t.collapseKey}function s7e(e,t){let n=c7e(e.changedFiles,t.changedFiles),r=t.detail??e.detail,i=t.command??e.command,a=t.rawCommand??e.rawCommand,o=t.toolTitle??e.toolTitle,s=t.itemType??e.itemType,c=t.requestKind??e.requestKind,l=t.collapseKey??e.collapseKey;return{...e,...t,...r?{detail:r}:{},...i?{command:i}:{},...a?{rawCommand:a}:{},...n.length>0?{changedFiles:n}:{},...o?{toolTitle:o}:{},...s?{itemType:s}:{},...c?{requestKind:c}:{},...l?{collapseKey:l}:{}}}function c7e(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function l7e(e){if(e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`)return;let t=u7e(e.toolTitle??e.label),n=e.detail?.trim()??``,r=e.itemType??``;if(t.length!==0||n.length!==0||r.length!==0)return[r,t,n].join(``)}function u7e(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}function a2(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function o2(e){return e&&typeof e==`object`?e:null}function s2(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function c2(e){let t=e.trim();if(t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)){let e=t.slice(1,-1).trim();return e.length>0?e:t}return t}function d7e(e){let t=c2(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function f7e(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`"`)||t.startsWith(`'`)){let e=t.charAt(0),n=t.indexOf(e,1);return n<=0?null:{executable:t.slice(0,n+1),rest:t.slice(n+1).trim()}}let n=t.search(/\s/);return n<0?{executable:t,rest:``}:{executable:t.slice(0,n),rest:t.slice(n).trim()}}var p7e=[{executables:[`pwsh`,`pwsh.exe`,`powershell`,`powershell.exe`],wrapperFlagPattern:/(?:^|\s)-command\s+/i},{executables:[`cmd`,`cmd.exe`],wrapperFlagPattern:/(?:^|\s)\/c\s+/i},{executables:[`bash`,`sh`,`zsh`],wrapperFlagPattern:/(?:^|\s)-(?:l)?c\s+/i}];function m7e(e){return p7e.find(t=>t.executables.includes(e))}function h7e(e,t){let n=t.exec(e);if(!n)return null;let r=e.slice(n.index+n[0].length).trim();if(r.length===0)return null;let i=c2(r);return i.length>0?i:null}function g7e(e){let t=f7e(e);if(!t||t.rest.length===0)return e;let n=d7e(t.executable);if(!n)return e;let r=m7e(n);return r?h7e(t.rest,r.wrapperFlagPattern)??e:e}function _7e(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function l2(e){let t=s2(e);if(t)return t;if(!Array.isArray(e))return null;let n=e.map(e=>s2(e)).filter(e=>e!==null);return n.length===0?null:n.map(e=>_7e(e)).join(` `)}function v7e(e){let t=l2(e);return t?g7e(t):null}function y7e(e,t){let n=l2(e);return!n||t===null||n===t?null:n}function b7e(e){let t=o2(e?.data),n=o2(t?.item),r=o2(n?.result),i=o2(n?.input),a=s2(e?.itemType),o=s2(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?d2(o).output:null];for(let e of s){let t=v7e(e);if(t)return{command:t,rawCommand:y7e(e,t)}}return{command:null,rawCommand:null}}function x7e(e){return S7e(e)??s2(e?.title)}function S7e(e){if(!e)return null;let t=o2(e.data),n=o2(t?.item),r=o2(n?.input)??o2(t?.input),i=s2(e.title),a=s2(e.itemType),o=s2(n?.name)??s2(n?.toolName)??s2(t?.name)??s2(e.toolName)??i,s=s2(e.detail),c=[o,i,a,s].filter(Boolean).join(` `).toLowerCase();if(!c.includes(`browser`)&&!c.includes(`forge-browser`))return null;switch(C7e(o,r,s)){case`open-session`:return`Opened browser session`;case`name-session`:return`Named browser session`;case`new-tab`:return u2(r)??`Opened browser tab`;case`navigate`:return u2(r)??`Navigated browser`;case`reload`:return`Reloaded page`;case`back`:return`Went back`;case`forward`:return`Went forward`;case`screenshot`:return`Captured screenshot`;case`snapshot`:return`Read DOM snapshot`;case`logs`:return`Read console logs`;case`click`:return`Clicked page`;case`type`:return`Typed text`;case`scroll`:return`Scrolled page`;case`viewport`:return`Updated viewport`;case`visibility`:return`Updated browser visibility`;default:return null}}function C7e(e,t,n){let r=[s2(t?.type)??s2(t?.command),e,n].filter(Boolean).join(` `).toLowerCase();return/\b(open[-_.\s]?session|create[-_.\s]?session|session[-_.\s]?open)\b/.test(r)?`open-session`:/\b(name[-_.\s]?session|session[-_.\s]?name)\b/.test(r)?`name-session`:/\b(new[-_.\s]?tab|create[-_.\s]?tab|open[-_.\s]?tab)\b/.test(r)?`new-tab`:/\b(navigate|goto|go[-_.\s]?to)\b/.test(r)?`navigate`:/\breload\b/.test(r)?`reload`:/\b(go[-_.\s]?back|back)\b/.test(r)?`back`:/\b(go[-_.\s]?forward|forward)\b/.test(r)?`forward`:/\b(screenshot|capture)\b/.test(r)?`screenshot`:/\b(snapshot|dom[-_.\s]?snapshot|read[-_.\s]?dom)\b/.test(r)?`snapshot`:/\b(console[-_.\s]?logs?|logs?)\b/.test(r)?`logs`:/\bclick\b/.test(r)?`click`:/\btype|fill\b/.test(r)?`type`:/\bscroll\b/.test(r)?`scroll`:/\bviewport\b/.test(r)?`viewport`:/\bvisibility|visible|hidden\b/.test(r)?`visibility`:null}function u2(e){let t=s2(e?.url)??s2(e?.initialUrl);if(!t)return null;try{let e=new URL(t);return e.hostname.length===0?null:`Navigated to ${e.hostname}`}catch{return null}}function d2(e){let t=e.trim(),n=/^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(t);if(!n?.groups)return{output:t.length>0?t:null};let r=Number.parseInt(n.groups.code??``,10),i=n.groups.output?.trim()??``;return{output:i.length>0?i:null,...Number.isInteger(r)?{exitCode:r}:{}}}function w7e(e){if(typeof e?.itemType==`string`&&Lte(e.itemType))return e.itemType}function T7e(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:Y0(e?.requestType)??void 0}function f2(e,t,n){let r=s2(n);!r||t.has(r)||(t.add(r),e.push(r))}function p2(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(p2(i,t,n,r+1),t.length>=12)return;return}let i=o2(e);if(i){f2(t,n,i.path),f2(t,n,i.filePath),f2(t,n,i.relativePath),f2(t,n,i.filename),f2(t,n,i.newPath),f2(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(p2(i[e],t,n,r+1),t.length>=12))return}}function E7e(e){let t=[],n=new Set;return p2(o2(e?.data),t,n,0),t}function m2(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;let n=e.createdAt.localeCompare(t.createdAt);if(n!==0)return n;let r=h2(e.kind)-h2(t.kind);return r===0?e.id.localeCompare(t.id):r}function h2(e){return e.endsWith(`.started`)||e===`tool.started`?0:e.endsWith(`.progress`)||e.endsWith(`.updated`)?1:e.endsWith(`.completed`)||e.endsWith(`.resolved`)?2:1}function D7e(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}function O7e(e,t,n){let r=e.map(e=>({id:e.id,kind:`message`,createdAt:e.createdAt,message:e})),i=t.map(e=>({id:e.id,kind:`proposed-plan`,createdAt:e.createdAt,proposedPlan:e})),a=n.map(e=>({id:e.id,kind:`work`,createdAt:e.createdAt,entry:e})),o=e.flatMap(e=>{if(e.role!==`assistant`)return[];let t=k7e(e.text,{workEntries:n,createdAt:e.createdAt});return t?[{id:`${e.id}:github-confirmation:${t.confirmationId}`,kind:`work`,createdAt:e.createdAt,entry:{id:`${e.id}:github-confirmation:${t.confirmationId}`,createdAt:e.createdAt,label:`GitHub action needs approval`,detail:t2(t),tone:`approval`,toolTitle:e2(t.operation),githubConfirmation:t}}]:[]});return[...r,...i,...a,...o].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function k7e(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=N7e(e,/\b(?:New confirmation id|Confirmation id):\s*`?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})`?/i)??null,r=/\bRepo(?: to create)?:\s*(private|public|internal)\s+`?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)`?/i.exec(e);if(!n)return null;let i=A7e(e,n,t);if(i)return i;if(!r)return null;let a=r[1]?.toLowerCase(),o=r[2],s=r[3];return!o||!s?null:{confirmationId:n,toolName:`forge_github_create_repository`,operation:`create_repository`,request:{owner:o,name:s,visibility:a}}}function A7e(e,t,n){if(!j7e(e))return null;let r=M7e(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?s2(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function j7e(e){return/\bforge_github_refresh_credentials\b/i.test(e)||/\bcredential refresh\b/i.test(e)||/\brefresh(?:ing)? GitHub credentials\b/i.test(e)}function M7e(e,t,n){for(let r of e.toReversed()){if(t!==void 0&&r.createdAt>t)continue;let e=r.githubConfirmation;if(e?.toolName===n)return e}return null}function N7e(e,t){return t.exec(e)?.[1]??null}function P7e(e,t){if(!t?.startedAt||!t.completedAt)return null;if(t.assistantMessageId){let n=e.find(e=>e.kind===`message`&&e.message.role===`assistant`&&e.message.id===t.assistantMessageId);if(n)return n.id}let n=Date.parse(t.startedAt),r=Date.parse(t.completedAt);if(Number.isNaN(n)||Number.isNaN(r))return null;let i=null,a=null;for(let t of e){if(t.kind!==`message`||t.message.role!==`assistant`)continue;let e=Date.parse(t.message.createdAt);Number.isNaN(e)||e<n||(a=t.id,e<=r&&(i=t.id))}return i??a}function F7e(e){let t=[...e].toSorted((e,t)=>e.completedAt.localeCompare(t.completedAt)),n={};for(let e=0;e<t.length;e+=1){let r=t[e];r&&(n[r.turnId]=e+1)}return n}function I7e(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function L7e(e,t){if(t===`disconnected`||t===`connecting`)return null;for(let t of e.toReversed())if(t.kind===`work`&&t.entry.githubConfirmation)return t.entry.githubConfirmation;return null}var g2=[`preview`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`pull-request`],_2={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function v2(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function R7e(e,t,n,r=`execution-intent`){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n,readPolicy:r}}function y2(e){let t=[e.provider,e.environmentId,e.repositoryLinkId??``,e.projectId,e.host.toLowerCase(),e.repository,String(e.number)].map(e=>encodeURIComponent(e)).join(`:`);return{...e,id:`pull-request:${t}`,kind:`pull-request`}}function b2(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var z7e=`workspace:pull-requests`;function x2(e){return typeof e==`object`&&!!e}function B7e(e){return typeof e==`string`&&g2.includes(e)}function S2(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function V7e(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function H7e(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:S2(e.revealLine),revealRequestId:V7e(e.revealRequestId),readPolicy:e.readPolicy===`connected-only`?`connected-only`:`execution-intent`}}function U7e(e){let t=e.resourceId;return t==null?{id:`browser:new`,kind:`preview`,resourceId:null}:typeof t!=`string`||t.length===0?null:{id:`browser:${t}`,kind:`preview`,resourceId:t}}function W7e(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?gn.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var G7e=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function C2(e){return typeof e==`string`&&e.length>0}function w2(e){return e===null||typeof e==`string`}function K7e(e){return e===void 0||w2(e)}function q7e(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=S2(e.number),c=e.title;return![C2(t)&&G7e.has(t),C2(n),w2(r),C2(i),C2(a),C2(o),s!==null,K7e(c)].every(Boolean)||!C2(t)||!C2(n)?null:y2({provider:t,environmentId:an.make(n),repositoryLinkId:r,projectId:tn.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function J7e(e){if(!x2(e)||!B7e(e.kind))return null;let t=e.kind;return t===`file`?H7e(e):t===`preview`?U7e(e):t===`diff`?W7e(e):t===`pull-request`?q7e(e):{id:t,kind:t}}function Y7e(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=J7e(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function X7e(e){if(!x2(e))return null;let t=Y7e(e.surfaces);if(t.length===0)return null;let n=e.activeSurfaceId,r=t.some(e=>e.id===n),i=typeof n==`string`&&r?n:t[0]?.id??null;return{isOpen:e.isOpen===!0,activeSurfaceId:i,surfaces:t}}function Z7e(e){if(!x2(e)||!x2(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===z7e)continue;let e=X7e(r);e&&(t[n]=e)}return{byThreadKey:t}}var Q7e=`forge:right-panel-state`,$7e=3,e9e=e=>e===`workspace:pull-requests`;function t9e(e){return`draft:${e}`}function n9e(e){return e.startsWith(`draft:`)}function r9e(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var T2=(e,t,n=!0)=>({...e,isOpen:!0,surfaces:e.surfaces.some(e=>e.id===t.id)?e.surfaces:[...e.surfaces,t],activeSurfaceId:n?t.id:e.activeSurfaceId}),E2=(e,t,n)=>{let r=e[t]??_2,i=n(r);if(!i.isOpen&&i.activeSurfaceId===null&&i.surfaces.length===0){if(!(t in e))return e;let{[t]:n,...r}=e;return r}return i===r?e:{...e,[t]:i}},i9e=Xt()(CJ(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>T2(e,e.surfaces.find(e=>e.kind===n)??b2(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return T2({...e,surfaces:t},v2(n))})})),revealBrowser:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>T2(e,e.surfaces.find(e=>e.kind===`preview`)??v2(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t={id:`diff`,kind:`diff`,turnId:n??null,filePath:n?r??null:null};return{...e,isOpen:!0,activeSurfaceId:t.id,surfaces:e.surfaces.some(e=>e.id===`diff`)?e.surfaces.map(e=>e.id===`diff`?t:e):[...e.surfaces,t]}})})),openFile:(t,n,r,i=`execution-intent`)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t=`file:${n}`,a=e.surfaces.find(e=>e.id===t&&e.kind===`file`),o=R7e(n,r9e(r),(a?.revealRequestId??0)+1,i);return{...e,isOpen:!0,activeSurfaceId:o.id,surfaces:a?e.surfaces.map(e=>e.id===o.id?o:e):[...e.surfaces,o]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>T2(e,y2(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0)return e;let r=e.surfaces.filter(e=>e.id!==n);if(e.activeSurfaceId!==n)return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r};let i=r[Math.min(t,r.length-1)]??null;return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r,activeSurfaceId:i?.id??null}})})),closeOtherSurfaces:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t=e.surfaces.find(e=>e.id===n);return!t||e.surfaces.length===1?e:{...e,isOpen:!0,surfaces:[t],activeSurfaceId:t.id}})})),closeSurfacesToRight:(t,n)=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0||t===e.surfaces.length-1)return e;let r=e.surfaces.slice(0,t+1),i=r.some(t=>t.id===e.activeSurfaceId);return{...e,surfaces:r,activeSurfaceId:i?e.activeSurfaceId:n}})})),closeAllSurfaces:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,()=>_2)})),show:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:E2(e.byThreadKey,t,e=>e.isOpen?{...e,isMaximized:!(e.isMaximized??!1)}:e)})),removeThread:t=>e(e=>{if(!(t in e.byThreadKey))return e;let{[t]:n,...r}=e.byThreadKey;return{byThreadKey:r}})}),{name:Q7e,version:$7e,storage:xJ(()=>MJ),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!n9e(e)&&!e9e(e)))}),migrate:e=>Z7e(e)}));function a9e(e){return t=>e?Zq(t,e.environmentId).projectById[e.projectId]:void 0}function D2(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=Zq(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=yq(o,a.threadId),r)}}function o9e(e){return D2(()=>e)}function s9e(e){return t=>{if(e)return Zq(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function c9e(e){let t,n,r,i;return a=>{if(!e){i=void 0,t=void 0,n=void 0,r=void 0;return}let o=Zq(a,e.environmentId).threadShellById,s=o[e.threadId];if(!s){i=void 0,t=void 0,n=void 0,r=void 0;return}let c=s.kind===`master`?s.id:s.parentThreadId,l=c==null?void 0:o[c];if(i&&t===o&&n===s&&r===l)return i;let u=[];if(c!=null){for(let e of Object.values(o))e.kind===`worker`&&e.parentThreadId===c&&u.push(e);u.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}return t=o,n=s,r=l,i={you:s,master:l,workers:u},i}}function l9e(e){return D2(t=>{if(!e)return;let n,r,i;for(let[a,o]of Object.entries(t.environmentStateById))if(o.threadShellById[e]){let s={environmentId:a,threadId:e};if(n??=s,t.activeEnvironmentId===a&&(r=s),o.bootstrapComplete&&(i=s,t.activeEnvironmentId===a))break}return i??r??n})}var u9e=/https?:\/\/[^\s"'`<>]+/g,d9e=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,f9e=/[.,;!?]+$/;function p9e(e){let t=e.replace(f9e,``);if(t.length===0)return t;let n=(e,n)=>{for(;t.endsWith(n);){if(t.split(e).length-1>=t.split(n).length-1)return;t=t.slice(0,-1)}};return n(`(`,`)`),n(`[`,`]`),n(`{`,`}`),t}function m9e(e,t){return e.start<t.end&&t.start<e.end}function O2(e,t,n,r){let i=[];n.lastIndex=0;for(let a of e.matchAll(n)){let e=a[0],n=a.index??-1;if(n<0||e.length===0)continue;let o=p9e(e);if(o.length===0||t===`path`&&/^https?:\/\//i.test(o))continue;let s={kind:t,text:o,start:n,end:n+o.length};[...r,...i].some(e=>m9e(s,e))||i.push(s)}return i}function k2(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function h9e(e){return e.startsWith(`/`)||k2(e)}function A2(e){return k2(e)||/[A-Za-z]:\\/.test(e)}function j2(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function g9e(e){let t=e.match(/^\/Users\/([^/]+)/);if(t?.[1])return`/Users/${t[1]}`;let n=e.match(/^\/home\/([^/]+)/);if(n?.[1])return`/home/${n[1]}`;let r=e.match(/^([A-Za-z]:\\Users\\[^\\]+)/);if(r?.[1])return r[1]}function M2(e){let t=e,n,r,i=t.match(/:(\d+)$/);if(!i?.[1])return{path:t,line:void 0,column:void 0};n=i[1],t=t.slice(0,-i[0].length);let a=t.match(/:(\d+)$/);return a?.[1]?(r=a[1],t=t.slice(0,-a[0].length)):(r=n,n=void 0),{path:t,line:r,column:n}}function _9e(e){let t=O2(e,`url`,u9e,[]),n=O2(e,`path`,d9e,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function v9e(e,t){let n=t(e-1);if(!n)return null;let r=e,i=n;for(;r>1&&i.isWrapped;){let e=t(r-2);if(!e)return null;--r,i=e}let a=[],o=0,s=r;for(;;){let e=t(s-1);if(!e)break;let n=t(s)?.isWrapped===!0,r=e.translateToString(!n);if(a.push({bufferLineNumber:s,text:r,startIndex:o,endIndex:o+r.length}),o+=r.length,!n)break;s+=1}return{text:a.map(e=>e.text).join(``),segments:a}}function N2(e,t){for(let n of e)if(t<n.endIndex)return{x:t-n.startIndex+1,y:n.bufferLineNumber};let n=e[e.length-1];return{x:Math.max(n?.text.length??0,1),y:n?.bufferLineNumber??1}}function y9e(e,t){return{start:N2(e.segments,t.start),end:N2(e.segments,t.end-1)}}function b9e(e,t){return e.start.y<=t&&t<=e.end.y}function x9e(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:xte(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function S9e(e,t){let{path:n,line:r,column:i}=M2(e),a=n;if(n.startsWith(`~/`)){let e=g9e(t);if(e){let t=A2(e)?`\\`:`/`;a=j2(e,n.slice(2),t)}}else h9e(n)||(a=j2(t,n,A2(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var P2=`diffs-container`,C9e=(()=>{try{return!1}catch{return!1}})(),w9e=/(?=^From [a-f0-9]+ .+$)/m,T9e=/(?=^diff --git)/gm,E9e=/(?<=\n)/,D9e=/^(---|\+\+\+)\s+([^\t\r\n]+)/,O9e=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,k9e=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,A9e=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,F2=`header-prefix`,I2=`header-filename-suffix`,L2=`header-metadata`,R2=`header-custom`,z2={dark:`pierre-dark`,light:`pierre-light`},j9e=`data-theme-css`,M9e=`data-unsafe-css`,N9e=`data-diffs-scrollbar-measure`,P9e=`data-diffs-code-view-header`,F9e=`data-diffs-code-view-footer`,B2=`--diffs-scrollbar-gutter-measured`,I9e=1e5,V2={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},L9e={...V2,hunkLineCount:1},R9e={paddingTop:8,paddingBottom:8,gap:8},z9e={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},B9e=Object.freeze({fromStart:0,fromEnd:0}),V9e={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},H9e={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},H2=new Set,U2=null;function W2(e){H2.add(e),U2??=requestAnimationFrame(K2)}function G2(e){H2.delete(e)&&H2.size===0&&U2!=null&&(cancelAnimationFrame(U2),U2=null)}function K2(e){let t=new Set(H2);H2.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}U2=H2.size>0?requestAnimationFrame(K2):null}function q2(e,t,n){if(e===t||e==null||t==null)return e===t;let r=new Set(n),i=Object.keys(e),a=new Set(Object.keys(t));for(let n of i)if(a.delete(n),!r.has(n)&&(!(n in t)||e[n]!==t[n]))return!1;for(let e of Array.from(a))if(!r.has(e))return!1;return!0}function J2(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function U9e(e,t){let n=e?.theme??z2,r=t?.theme??z2,i=Y2(e),a=Y2(t);return J2(n,r)&&q2(e,t,[`theme`,`parseDiffOptions`])&&q2(i,a)}function Y2(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function X2(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function W9e({scrollTop:e,scrollHeight:t,height:n,fitPerfectly:r=!1,fitPerfectlyOverscroll:i=0,overscrollSize:a}){let o=n+a*2,s=r?n+i*2:o;if(t=Math.max(t,s),o>=t||r){let n=Math.max(e-i,0),r=Math.min(e+s,t);return{top:n,bottom:Math.max(r,n)}}let c=e+n/2-o/2,l=c+o;return c<0&&(c=0),l>t&&(l=t),c=Math.floor(Math.max(c,0)),{top:c,bottom:Math.ceil(Math.max(Math.min(l,t),c))}}function Z2(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function Q2(e,t){return e-(t===0?0:1)}function $2(e,t){return Q2(e,t)+t}var e4=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},G9e=new class extends e4{};function K9e(e,t,n){return G9e.diff(e,t,n)}function t4(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function n4(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function r4(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function i4(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function a4(e,t){return r4(e,t,``)}function o4(e,t){return i4(e,t,``)}function s4(e,t){return t.slice(0,q9e(e,t))}function q9e(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function c4(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function l4(e,t){if(t)return d4(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function u4(e,t){if(t)return d4(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function d4(e,t){if(!t)return[u4(e),l4(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=c4(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var f4=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,J9e=RegExp(`[${f4}]+|\\s+|[^${f4}]`,`ug`);new class extends e4{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=c4(e,r)}else n=e.match(J9e)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&p4(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&p4(n,i,r,null,t.intlSegmenter),e}};function p4(e,t,n,r,i){if(t&&n){let[a,o]=d4(t.value,i),[s,c]=d4(n.value,i);if(e){let r=t4(a,s);e.value=i4(e.value,s,r),t.value=a4(t.value,r),n.value=a4(n.value,r)}if(r){let e=n4(o,c);r.value=r4(r.value,c,e),t.value=o4(t.value,e),n.value=o4(n.value,e)}}else if(n){if(e){let e=u4(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=u4(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=u4(r.value,i),[a,o]=d4(t.value,i),s=t4(n,a);t.value=a4(t.value,s);let c=n4(a4(n,s),o);t.value=o4(t.value,c),r.value=r4(r.value,n,c),e.value=i4(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=u4(r.value,i),n=s4(l4(t.value,i),e);t.value=o4(t.value,n)}else if(e){let n=s4(l4(e.value,i),u4(t.value,i));t.value=a4(t.value,n)}}var Y9e=new class extends e4{tokenize(e){let t=RegExp(`(\\r?\\n)|[${f4}]+|[^\\S\\n\\r]+|[^${f4}]`,`ug`);return e.match(t)||[]}};function X9e(e,t,n){return Y9e.diff(e,t,n)}var Z9e=new class extends e4{constructor(){super(...arguments),this.tokenize=h4}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
1022
1022
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
1023
1023
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
1024
1024
  `)&&(e=e.slice(0,-1)),t.endsWith(`
1025
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function h4(e,t,n){return Q9e.diff(e,t,n)}function g4(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
1026
- `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function $9e(e){return e==`.`||e==`!`||e==`?`}new class extends t4{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if($9e(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends t4{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends t4{constructor(){super(...arguments),this.tokenize=g4}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(_4(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function _4(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=_4(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=_4(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends t4{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function eet(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function v4(e){if(!eet(e))return e;let t=`"`,n=new TextEncoder().encode(e),r=0;for(;r<n.length;){let e=n[r];t+=e===7?`\\a`:e===8?`\\b`:e===9?`\\t`:e===10?`\\n`:e===11?`\\v`:e===12?`\\f`:e===13?`\\r`:e===34?`\\"`:e===92?`\\\\`:e>=32&&e<=126?String.fromCharCode(e):`\\`+e.toString(8).padStart(3,`0`),r++}return t+=`"`,t}var y4={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function b4(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;h4(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(h4(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||net(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
1027
- `)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function x4(e,t){if(t||=y4,Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders&&!e.every(e=>e.isGit))throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>x4(e,t)).join(`
1028
- `)}let n=[];if(e.isGit){if(t=y4,!e.oldFileName)throw Error(`oldFileName must be specified for Git patches`);if(!e.newFileName)throw Error(`newFileName must be specified for Git patches`);let r=e.oldFileName,i=e.newFileName;e.isCreate&&r===`/dev/null`?r=i.replace(/^b\//,`a/`):e.isDelete&&i===`/dev/null`&&(i=r.replace(/^a\//,`b/`)),n.push(`diff --git `+v4(r)+` `+v4(i)),e.isDelete&&n.push(`deleted file mode `+(e.oldMode??`100644`)),e.isCreate&&n.push(`new file mode `+(e.newMode??`100644`)),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(n.push(`old mode `+e.oldMode),n.push(`new mode `+e.newMode)),e.isRename&&(n.push(`rename from `+v4((e.oldFileName??``).replace(/^a\//,``))),n.push(`rename to `+v4((e.newFileName??``).replace(/^b\//,``)))),e.isCopy&&(n.push(`copy from `+v4((e.oldFileName??``).replace(/^a\//,``))),n.push(`copy to `+v4((e.newFileName??``).replace(/^b\//,``))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`);let r=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||r)&&(n.push(`--- `+v4(e.oldFileName)+(e.oldHeader?` `+e.oldHeader:``)),n.push(`+++ `+v4(e.newFileName)+(e.newHeader?` `+e.newHeader:``)));for(let t=0;t<e.hunks.length;t++){let r=e.hunks[t],i=r.oldLines===0?r.oldStart-1:r.oldStart,a=r.newLines===0?r.newStart-1:r.newStart;n.push(`@@ -`+i+`,`+r.oldLines+` +`+a+`,`+r.newLines+` @@`);for(let e of r.lines)n.push(e)}return n.join(`
1025
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function m4(e,t,n){return Z9e.diff(e,t,n)}function h4(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
1026
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function Q9e(e){return e==`.`||e==`!`||e==`?`}new class extends e4{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(Q9e(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends e4{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends e4{constructor(){super(...arguments),this.tokenize=h4}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(g4(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function g4(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=g4(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=g4(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends e4{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function $9e(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function _4(e){if(!$9e(e))return e;let t=`"`,n=new TextEncoder().encode(e),r=0;for(;r<n.length;){let e=n[r];t+=e===7?`\\a`:e===8?`\\b`:e===9?`\\t`:e===10?`\\n`:e===11?`\\v`:e===12?`\\f`:e===13?`\\r`:e===34?`\\"`:e===92?`\\\\`:e>=32&&e<=126?String.fromCharCode(e):`\\`+e.toString(8).padStart(3,`0`),r++}return t+=`"`,t}var v4={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function y4(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;m4(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(m4(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||tet(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
1027
+ `)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function b4(e,t){if(t||=v4,Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders&&!e.every(e=>e.isGit))throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>b4(e,t)).join(`
1028
+ `)}let n=[];if(e.isGit){if(t=v4,!e.oldFileName)throw Error(`oldFileName must be specified for Git patches`);if(!e.newFileName)throw Error(`newFileName must be specified for Git patches`);let r=e.oldFileName,i=e.newFileName;e.isCreate&&r===`/dev/null`?r=i.replace(/^b\//,`a/`):e.isDelete&&i===`/dev/null`&&(i=r.replace(/^a\//,`b/`)),n.push(`diff --git `+_4(r)+` `+_4(i)),e.isDelete&&n.push(`deleted file mode `+(e.oldMode??`100644`)),e.isCreate&&n.push(`new file mode `+(e.newMode??`100644`)),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(n.push(`old mode `+e.oldMode),n.push(`new mode `+e.newMode)),e.isRename&&(n.push(`rename from `+_4((e.oldFileName??``).replace(/^a\//,``))),n.push(`rename to `+_4((e.newFileName??``).replace(/^b\//,``)))),e.isCopy&&(n.push(`copy from `+_4((e.oldFileName??``).replace(/^a\//,``))),n.push(`copy to `+_4((e.newFileName??``).replace(/^b\//,``))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`);let r=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||r)&&(n.push(`--- `+_4(e.oldFileName)+(e.oldHeader?` `+e.oldHeader:``)),n.push(`+++ `+_4(e.newFileName)+(e.newHeader?` `+e.newHeader:``)));for(let t=0;t<e.hunks.length;t++){let r=e.hunks[t],i=r.oldLines===0?r.oldStart-1:r.oldStart,a=r.newLines===0?r.newStart-1:r.newStart;n.push(`@@ -`+i+`,`+r.oldLines+` +`+a+`,`+r.newLines+` @@`);for(let e of r.lines)n.push(e)}return n.join(`
1029
1029
  `)+`
1030
- `}function tet(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;b4(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?x4(e,o.headerOptions):void 0)}}))}else{let s=b4(e,t,n,r,i,a,o);return s?x4(s,o?.headerOptions):void 0}}function net(e){let t=e.endsWith(`
1030
+ `}function eet(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;y4(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?b4(e,o.headerOptions):void 0)}}))}else{let s=y4(e,t,n,r,i,a,o);return s?b4(s,o?.headerOptions):void 0}}function tet(e){let t=e.endsWith(`
1031
1031
  `),n=e.split(`
1032
1032
  `).map(e=>e+`
1033
- `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function S4(e,t){return e?.cacheKey===t?.cacheKey&&e?.contents===t?.contents&&e?.name===t?.name&&e?.lang===t?.lang}function C4(e){return{type:`text`,value:e}}function w4({tagName:e,children:t=[],properties:n={}}){return{type:`element`,tagName:e,properties:n,children:t}}function T4({name:e,width:t=16,height:n=16,properties:r}){return w4({tagName:`svg`,properties:{width:t,height:n,viewBox:`0 0 16 16`,...r},children:[w4({tagName:`use`,properties:{href:`#${e.replace(/^#/,``)}`}})]})}function ret(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t;t=`children`in t?t.children[0]:null}}function iet(e){return w4({tagName:`div`,properties:{"data-gutter":``},children:e})}function aet(e,t,n,r={}){return w4({tagName:`div`,properties:{"data-line-type":e,"data-column-number":t,"data-line-index":n,...r},children:t==null?void 0:[w4({tagName:`span`,properties:{"data-line-number-content":``},children:[C4(`${t}`)]})]})}function oet(e,t,n){return w4({tagName:`div`,properties:{"data-gutter-buffer":t,"data-buffer-size":n,"data-line-type":t===`annotation`?void 0:e,style:t===`annotation`?`grid-row: span ${n};`:`grid-row: span ${n};min-height:calc(${n} * 1lh);`}})}function set(){return w4({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[T4({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function cet(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function E4(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute(`data-utility-button`)||t.hasAttribute(`data-gutter-utility-slot`)||t.getAttribute(`slot`)===`gutter-utility-slot`||t.getAttribute(`name`)===`gutter-utility-slot`))return!0;return!1}var D4=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],O4=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};O4.prototype.normal={},O4.prototype.property={},O4.prototype.space=void 0;function k4(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new O4(n,r,t)}function A4(e){return e.toLowerCase()}var j4=class{constructor(e,t){this.attribute=t,this.property=e}};j4.prototype.attribute=``,j4.prototype.booleanish=!1,j4.prototype.boolean=!1,j4.prototype.commaOrSpaceSeparated=!1,j4.prototype.commaSeparated=!1,j4.prototype.defined=!1,j4.prototype.mustUseProperty=!1,j4.prototype.number=!1,j4.prototype.overloadedBoolean=!1,j4.prototype.property=``,j4.prototype.spaceSeparated=!1,j4.prototype.space=void 0;var M4=e({boolean:()=>N4,booleanish:()=>P4,commaOrSpaceSeparated:()=>R4,commaSeparated:()=>L4,number:()=>$,overloadedBoolean:()=>F4,spaceSeparated:()=>I4}),uet=0,N4=z4(),P4=z4(),F4=z4(),$=z4(),I4=z4(),L4=z4(),R4=z4();function z4(){return 2**++uet}var B4=Object.keys(M4),V4=class extends j4{constructor(e,t,n,r){let i=-1;if(super(e,t),H4(this,`space`,r),typeof n==`number`)for(;++i<B4.length;){let e=B4[i];H4(this,B4[i],(n&M4[e])===M4[e])}}};V4.prototype.defined=!0;function H4(e,t,n){n&&(e[t]=n)}function U4(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new V4(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[A4(r)]=r,n[A4(a.attribute)]=r}return new O4(t,n,e.space)}var W4=U4({properties:{ariaActiveDescendant:null,ariaAtomic:P4,ariaAutoComplete:null,ariaBusy:P4,ariaChecked:P4,ariaColCount:$,ariaColIndex:$,ariaColSpan:$,ariaControls:I4,ariaCurrent:null,ariaDescribedBy:I4,ariaDetails:null,ariaDisabled:P4,ariaDropEffect:I4,ariaErrorMessage:null,ariaExpanded:P4,ariaFlowTo:I4,ariaGrabbed:P4,ariaHasPopup:null,ariaHidden:P4,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:I4,ariaLevel:$,ariaLive:null,ariaModal:P4,ariaMultiLine:P4,ariaMultiSelectable:P4,ariaOrientation:null,ariaOwns:I4,ariaPlaceholder:null,ariaPosInSet:$,ariaPressed:P4,ariaReadOnly:P4,ariaRelevant:null,ariaRequired:P4,ariaRoleDescription:I4,ariaRowCount:$,ariaRowIndex:$,ariaRowSpan:$,ariaSelected:P4,ariaSetSize:$,ariaSort:null,ariaValueMax:$,ariaValueMin:$,ariaValueNow:$,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function G4(e,t){return t in e?e[t]:t}function K4(e,t){return G4(e,t.toLowerCase())}var det=U4({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:L4,acceptCharset:I4,accessKey:I4,action:null,allow:null,allowFullScreen:N4,allowPaymentRequest:N4,allowUserMedia:N4,alt:null,as:null,async:N4,autoCapitalize:null,autoComplete:I4,autoFocus:N4,autoPlay:N4,blocking:I4,capture:null,charSet:null,checked:N4,cite:null,className:I4,cols:$,colSpan:null,content:null,contentEditable:P4,controls:N4,controlsList:I4,coords:$|L4,crossOrigin:null,data:null,dateTime:null,decoding:null,default:N4,defer:N4,dir:null,dirName:null,disabled:N4,download:F4,draggable:P4,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:N4,formTarget:null,headers:I4,height:$,hidden:F4,high:$,href:null,hrefLang:null,htmlFor:I4,httpEquiv:I4,id:null,imageSizes:null,imageSrcSet:null,inert:N4,inputMode:null,integrity:null,is:null,isMap:N4,itemId:null,itemProp:I4,itemRef:I4,itemScope:N4,itemType:I4,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:N4,low:$,manifest:null,max:null,maxLength:$,media:null,method:null,min:null,minLength:$,multiple:N4,muted:N4,name:null,nonce:null,noModule:N4,noValidate:N4,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:N4,optimum:$,pattern:null,ping:I4,placeholder:null,playsInline:N4,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:N4,referrerPolicy:null,rel:I4,required:N4,reversed:N4,rows:$,rowSpan:$,sandbox:I4,scope:null,scoped:N4,seamless:N4,selected:N4,shadowRootClonable:N4,shadowRootDelegatesFocus:N4,shadowRootMode:null,shape:null,size:$,sizes:null,slot:null,span:$,spellCheck:P4,src:null,srcDoc:null,srcLang:null,srcSet:null,start:$,step:null,style:null,tabIndex:$,target:null,title:null,translate:null,type:null,typeMustMatch:N4,useMap:null,value:P4,width:$,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:I4,axis:null,background:null,bgColor:null,border:$,borderColor:null,bottomMargin:$,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:N4,declare:N4,event:null,face:null,frame:null,frameBorder:null,hSpace:$,leftMargin:$,link:null,longDesc:null,lowSrc:null,marginHeight:$,marginWidth:$,noResize:N4,noHref:N4,noShade:N4,noWrap:N4,object:null,profile:null,prompt:null,rev:null,rightMargin:$,rules:null,scheme:null,scrolling:P4,standby:null,summary:null,text:null,topMargin:$,valueType:null,version:null,vAlign:null,vLink:null,vSpace:$,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:N4,disableRemotePlayback:N4,prefix:null,property:null,results:$,security:null,unselectable:null},space:`html`,transform:K4}),fet=U4({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:R4,accentHeight:$,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:$,amplitude:$,arabicForm:null,ascent:$,attributeName:null,attributeType:null,azimuth:$,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:$,by:null,calcMode:null,capHeight:$,className:I4,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:$,diffuseConstant:$,direction:null,display:null,dur:null,divisor:$,dominantBaseline:null,download:N4,dx:null,dy:null,edgeMode:null,editable:null,elevation:$,enableBackground:null,end:null,event:null,exponent:$,externalResourcesRequired:null,fill:null,fillOpacity:$,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:L4,g2:L4,glyphName:L4,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:$,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:$,horizOriginX:$,horizOriginY:$,id:null,ideographic:$,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:$,k:$,k1:$,k2:$,k3:$,k4:$,kernelMatrix:R4,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:$,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:$,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:$,overlineThickness:$,paintOrder:null,panose1:null,path:null,pathLength:$,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:I4,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:$,pointsAtY:$,pointsAtZ:$,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:R4,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:R4,rev:R4,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:R4,requiredFeatures:R4,requiredFonts:R4,requiredFormats:R4,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:$,specularExponent:$,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:$,strikethroughThickness:$,string:null,stroke:null,strokeDashArray:R4,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:$,strokeOpacity:$,strokeWidth:null,style:null,surfaceScale:$,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:R4,tabIndex:$,tableValues:null,target:null,targetX:$,targetY:$,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:R4,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:$,underlineThickness:$,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:$,values:null,vAlphabetic:$,vMathematical:$,vectorEffect:null,vHanging:$,vIdeographic:$,version:null,vertAdvY:$,vertOriginX:$,vertOriginY:$,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:$,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:G4}),q4=U4({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),J4=U4({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:K4}),Y4=U4({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),pet=/[A-Z]/g,X4=/-[a-z]/g,met=/^data[-\w.:]+$/i;function Z4(e,t){let n=A4(t),r=t,i=j4;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&met.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(X4,get);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!X4.test(e)){let n=e.replace(pet,het);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=V4}return new i(r,t)}function het(e){return`-`+e.toLowerCase()}function get(e){return e.charAt(1).toUpperCase()}var Q4=k4([W4,det,q4,J4,Y4],`html`),$4=k4([W4,fet,q4,J4,Y4],`svg`),e3={}.hasOwnProperty;function t3(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&e3.call(t,e)){let n=String(t[e]);i=e3.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var _et=/["&'<>`]/g,vet=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,yet=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,bet=/[|\\{}()[\]^$+*?.]/g,n3=new WeakMap;function xet(e,t){if(e=e.replace(t.subset?Cet(t.subset):_et,r),t.subset||t.escapeOnly)return e;return e.replace(vet,n).replace(yet,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function Cet(e){let t=n3.get(e);return t||(t=wet(e),n3.set(e,t)),t}function wet(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(bet,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var Tet=/[\dA-Fa-f]/;function Eet(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!Tet.test(String.fromCharCode(t))?r:r+`;`}var Det=/\d/;function Oet(e,t,n){let r=`&#`+String(e);return n&&t&&!Det.test(String.fromCharCode(t))?r:r+`;`}var ket=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),r3={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:`­`,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:`‌`,zwj:`‍`,lrm:`‎`,rlm:`‏`,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},Aet=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],i3={}.hasOwnProperty,a3={},o3;for(o3 in r3)i3.call(r3,o3)&&(a3[r3[o3]]=o3);var jet=/[^\dA-Za-z]/;function Met(e,t,n,r){let i=String.fromCharCode(e);if(i3.call(a3,i)){let e=a3[i],a=`&`+e;return n&&ket.includes(e)&&!Aet.includes(e)&&(!r||t&&t!==61&&jet.test(String.fromCharCode(t)))?a:a+`;`}return``}function Net(e,t,n){let r=Eet(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=Met(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=Oet(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function s3(e,t){return xet(e,Object.assign({format:Net},t))}var Pet=/^>|^->|<!--|-->|--!>|<!-$/g,Fet=[`>`],Iet=[`<`,`>`];function Let(e,t,n,r){return r.settings.bogusComments?`<?`+s3(e.value,Object.assign({},r.settings.characterReferences,{subset:Fet}))+`>`:`<!--`+e.value.replace(Pet,i)+`-->`;function i(e){return s3(e,Object.assign({},r.settings.characterReferences,{subset:Iet}))}}function Ret(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function c3(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function zet(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function l3(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function Bet(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function u3(e){return e.join(` `).trim()}var Vet=/[ \t\n\f\r]/g;function d3(e){return typeof e==`object`?e.type===`text`&&f3(e.value):f3(e)}function f3(e){return e.replace(Vet,``)===``}var p3=h3(1),m3=h3(-1),Het=[];function h3(e){return t;function t(t,n,r){let i=t?t.children:Het,a=(n||0)+e,o=i[a];if(!r)for(;o&&d3(o);)a+=e,o=i[a];return o}}var Uet={}.hasOwnProperty;function g3(e){return t;function t(t,n,r){return Uet.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var _3=g3({body:Get,caption:v3,colgroup:v3,dd:Yet,dt:Jet,head:v3,html:Wet,li:qet,optgroup:Xet,option:Zet,p:Ket,rp:y3,rt:y3,tbody:$et,td:b3,tfoot:ett,th:b3,thead:Qet,tr:ttt});function v3(e,t,n){let r=p3(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&d3(r.value.charAt(0)))}function Wet(e,t,n){let r=p3(n,t);return!r||r.type!==`comment`}function Get(e,t,n){let r=p3(n,t);return!r||r.type!==`comment`}function Ket(e,t,n){let r=p3(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function qet(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&r.tagName===`li`}function Jet(e,t,n){let r=p3(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function Yet(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function y3(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function Xet(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function Zet(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function Qet(e,t,n){let r=p3(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function $et(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function ett(e,t,n){return!p3(n,t)}function ttt(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function b3(e,t,n){let r=p3(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var ntt=g3({body:att,colgroup:ott,head:itt,html:rtt,tbody:stt});function rtt(e){let t=p3(e,-1);return!t||t.type!==`comment`}function itt(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function att(e){let t=p3(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&d3(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function ott(e,t,n){let r=m3(n,t),i=p3(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&_3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function stt(e,t,n){let r=m3(n,t),i=p3(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&_3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var x3={name:[[`
1033
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function x4(e,t){return e?.cacheKey===t?.cacheKey&&e?.contents===t?.contents&&e?.name===t?.name&&e?.lang===t?.lang}function S4(e){return{type:`text`,value:e}}function C4({tagName:e,children:t=[],properties:n={}}){return{type:`element`,tagName:e,properties:n,children:t}}function w4({name:e,width:t=16,height:n=16,properties:r}){return C4({tagName:`svg`,properties:{width:t,height:n,viewBox:`0 0 16 16`,...r},children:[C4({tagName:`use`,properties:{href:`#${e.replace(/^#/,``)}`}})]})}function net(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t;t=`children`in t?t.children[0]:null}}function ret(e){return C4({tagName:`div`,properties:{"data-gutter":``},children:e})}function iet(e,t,n,r={}){return C4({tagName:`div`,properties:{"data-line-type":e,"data-column-number":t,"data-line-index":n,...r},children:t==null?void 0:[C4({tagName:`span`,properties:{"data-line-number-content":``},children:[S4(`${t}`)]})]})}function aet(e,t,n){return C4({tagName:`div`,properties:{"data-gutter-buffer":t,"data-buffer-size":n,"data-line-type":t===`annotation`?void 0:e,style:t===`annotation`?`grid-row: span ${n};`:`grid-row: span ${n};min-height:calc(${n} * 1lh);`}})}function oet(){return C4({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[w4({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function set(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function T4(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute(`data-utility-button`)||t.hasAttribute(`data-gutter-utility-slot`)||t.getAttribute(`slot`)===`gutter-utility-slot`||t.getAttribute(`name`)===`gutter-utility-slot`))return!0;return!1}var E4=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],D4=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};D4.prototype.normal={},D4.prototype.property={},D4.prototype.space=void 0;function O4(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new D4(n,r,t)}function k4(e){return e.toLowerCase()}var A4=class{constructor(e,t){this.attribute=t,this.property=e}};A4.prototype.attribute=``,A4.prototype.booleanish=!1,A4.prototype.boolean=!1,A4.prototype.commaOrSpaceSeparated=!1,A4.prototype.commaSeparated=!1,A4.prototype.defined=!1,A4.prototype.mustUseProperty=!1,A4.prototype.number=!1,A4.prototype.overloadedBoolean=!1,A4.prototype.property=``,A4.prototype.spaceSeparated=!1,A4.prototype.space=void 0;var j4=e({boolean:()=>M4,booleanish:()=>N4,commaOrSpaceSeparated:()=>L4,commaSeparated:()=>I4,number:()=>$,overloadedBoolean:()=>P4,spaceSeparated:()=>F4}),cet=0,M4=R4(),N4=R4(),P4=R4(),$=R4(),F4=R4(),I4=R4(),L4=R4();function R4(){return 2**++cet}var z4=Object.keys(j4),B4=class extends A4{constructor(e,t,n,r){let i=-1;if(super(e,t),V4(this,`space`,r),typeof n==`number`)for(;++i<z4.length;){let e=z4[i];V4(this,z4[i],(n&j4[e])===j4[e])}}};B4.prototype.defined=!0;function V4(e,t,n){n&&(e[t]=n)}function H4(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new B4(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[k4(r)]=r,n[k4(a.attribute)]=r}return new D4(t,n,e.space)}var U4=H4({properties:{ariaActiveDescendant:null,ariaAtomic:N4,ariaAutoComplete:null,ariaBusy:N4,ariaChecked:N4,ariaColCount:$,ariaColIndex:$,ariaColSpan:$,ariaControls:F4,ariaCurrent:null,ariaDescribedBy:F4,ariaDetails:null,ariaDisabled:N4,ariaDropEffect:F4,ariaErrorMessage:null,ariaExpanded:N4,ariaFlowTo:F4,ariaGrabbed:N4,ariaHasPopup:null,ariaHidden:N4,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:F4,ariaLevel:$,ariaLive:null,ariaModal:N4,ariaMultiLine:N4,ariaMultiSelectable:N4,ariaOrientation:null,ariaOwns:F4,ariaPlaceholder:null,ariaPosInSet:$,ariaPressed:N4,ariaReadOnly:N4,ariaRelevant:null,ariaRequired:N4,ariaRoleDescription:F4,ariaRowCount:$,ariaRowIndex:$,ariaRowSpan:$,ariaSelected:N4,ariaSetSize:$,ariaSort:null,ariaValueMax:$,ariaValueMin:$,ariaValueNow:$,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function W4(e,t){return t in e?e[t]:t}function G4(e,t){return W4(e,t.toLowerCase())}var uet=H4({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:I4,acceptCharset:F4,accessKey:F4,action:null,allow:null,allowFullScreen:M4,allowPaymentRequest:M4,allowUserMedia:M4,alt:null,as:null,async:M4,autoCapitalize:null,autoComplete:F4,autoFocus:M4,autoPlay:M4,blocking:F4,capture:null,charSet:null,checked:M4,cite:null,className:F4,cols:$,colSpan:null,content:null,contentEditable:N4,controls:M4,controlsList:F4,coords:$|I4,crossOrigin:null,data:null,dateTime:null,decoding:null,default:M4,defer:M4,dir:null,dirName:null,disabled:M4,download:P4,draggable:N4,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:M4,formTarget:null,headers:F4,height:$,hidden:P4,high:$,href:null,hrefLang:null,htmlFor:F4,httpEquiv:F4,id:null,imageSizes:null,imageSrcSet:null,inert:M4,inputMode:null,integrity:null,is:null,isMap:M4,itemId:null,itemProp:F4,itemRef:F4,itemScope:M4,itemType:F4,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:M4,low:$,manifest:null,max:null,maxLength:$,media:null,method:null,min:null,minLength:$,multiple:M4,muted:M4,name:null,nonce:null,noModule:M4,noValidate:M4,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:M4,optimum:$,pattern:null,ping:F4,placeholder:null,playsInline:M4,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:M4,referrerPolicy:null,rel:F4,required:M4,reversed:M4,rows:$,rowSpan:$,sandbox:F4,scope:null,scoped:M4,seamless:M4,selected:M4,shadowRootClonable:M4,shadowRootDelegatesFocus:M4,shadowRootMode:null,shape:null,size:$,sizes:null,slot:null,span:$,spellCheck:N4,src:null,srcDoc:null,srcLang:null,srcSet:null,start:$,step:null,style:null,tabIndex:$,target:null,title:null,translate:null,type:null,typeMustMatch:M4,useMap:null,value:N4,width:$,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:F4,axis:null,background:null,bgColor:null,border:$,borderColor:null,bottomMargin:$,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:M4,declare:M4,event:null,face:null,frame:null,frameBorder:null,hSpace:$,leftMargin:$,link:null,longDesc:null,lowSrc:null,marginHeight:$,marginWidth:$,noResize:M4,noHref:M4,noShade:M4,noWrap:M4,object:null,profile:null,prompt:null,rev:null,rightMargin:$,rules:null,scheme:null,scrolling:N4,standby:null,summary:null,text:null,topMargin:$,valueType:null,version:null,vAlign:null,vLink:null,vSpace:$,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:M4,disableRemotePlayback:M4,prefix:null,property:null,results:$,security:null,unselectable:null},space:`html`,transform:G4}),det=H4({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:L4,accentHeight:$,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:$,amplitude:$,arabicForm:null,ascent:$,attributeName:null,attributeType:null,azimuth:$,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:$,by:null,calcMode:null,capHeight:$,className:F4,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:$,diffuseConstant:$,direction:null,display:null,dur:null,divisor:$,dominantBaseline:null,download:M4,dx:null,dy:null,edgeMode:null,editable:null,elevation:$,enableBackground:null,end:null,event:null,exponent:$,externalResourcesRequired:null,fill:null,fillOpacity:$,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:I4,g2:I4,glyphName:I4,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:$,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:$,horizOriginX:$,horizOriginY:$,id:null,ideographic:$,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:$,k:$,k1:$,k2:$,k3:$,k4:$,kernelMatrix:L4,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:$,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:$,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:$,overlineThickness:$,paintOrder:null,panose1:null,path:null,pathLength:$,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:F4,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:$,pointsAtY:$,pointsAtZ:$,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:L4,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:L4,rev:L4,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:L4,requiredFeatures:L4,requiredFonts:L4,requiredFormats:L4,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:$,specularExponent:$,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:$,strikethroughThickness:$,string:null,stroke:null,strokeDashArray:L4,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:$,strokeOpacity:$,strokeWidth:null,style:null,surfaceScale:$,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:L4,tabIndex:$,tableValues:null,target:null,targetX:$,targetY:$,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:L4,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:$,underlineThickness:$,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:$,values:null,vAlphabetic:$,vMathematical:$,vectorEffect:null,vHanging:$,vIdeographic:$,version:null,vertAdvY:$,vertOriginX:$,vertOriginY:$,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:$,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:W4}),K4=H4({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),q4=H4({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:G4}),J4=H4({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),fet=/[A-Z]/g,Y4=/-[a-z]/g,pet=/^data[-\w.:]+$/i;function X4(e,t){let n=k4(t),r=t,i=A4;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&pet.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(Y4,het);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!Y4.test(e)){let n=e.replace(fet,met);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=B4}return new i(r,t)}function met(e){return`-`+e.toLowerCase()}function het(e){return e.charAt(1).toUpperCase()}var Z4=O4([U4,uet,K4,q4,J4],`html`),Q4=O4([U4,det,K4,q4,J4],`svg`),$4={}.hasOwnProperty;function e3(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&$4.call(t,e)){let n=String(t[e]);i=$4.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var get=/["&'<>`]/g,_et=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,vet=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,yet=/[|\\{}()[\]^$+*?.]/g,t3=new WeakMap;function bet(e,t){if(e=e.replace(t.subset?xet(t.subset):get,r),t.subset||t.escapeOnly)return e;return e.replace(_et,n).replace(vet,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function xet(e){let t=t3.get(e);return t||(t=Cet(e),t3.set(e,t)),t}function Cet(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(yet,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var wet=/[\dA-Fa-f]/;function Tet(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!wet.test(String.fromCharCode(t))?r:r+`;`}var Eet=/\d/;function Det(e,t,n){let r=`&#`+String(e);return n&&t&&!Eet.test(String.fromCharCode(t))?r:r+`;`}var Oet=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),n3={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:`­`,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:`‌`,zwj:`‍`,lrm:`‎`,rlm:`‏`,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},ket=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],r3={}.hasOwnProperty,i3={},a3;for(a3 in n3)r3.call(n3,a3)&&(i3[n3[a3]]=a3);var Aet=/[^\dA-Za-z]/;function jet(e,t,n,r){let i=String.fromCharCode(e);if(r3.call(i3,i)){let e=i3[i],a=`&`+e;return n&&Oet.includes(e)&&!ket.includes(e)&&(!r||t&&t!==61&&Aet.test(String.fromCharCode(t)))?a:a+`;`}return``}function Met(e,t,n){let r=Tet(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=jet(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=Det(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function o3(e,t){return bet(e,Object.assign({format:Met},t))}var Net=/^>|^->|<!--|-->|--!>|<!-$/g,Pet=[`>`],Fet=[`<`,`>`];function Iet(e,t,n,r){return r.settings.bogusComments?`<?`+o3(e.value,Object.assign({},r.settings.characterReferences,{subset:Pet}))+`>`:`<!--`+e.value.replace(Net,i)+`-->`;function i(e){return o3(e,Object.assign({},r.settings.characterReferences,{subset:Fet}))}}function Let(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function s3(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function Ret(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function c3(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function zet(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function l3(e){return e.join(` `).trim()}var Bet=/[ \t\n\f\r]/g;function u3(e){return typeof e==`object`?e.type===`text`&&d3(e.value):d3(e)}function d3(e){return e.replace(Bet,``)===``}var f3=m3(1),p3=m3(-1),Vet=[];function m3(e){return t;function t(t,n,r){let i=t?t.children:Vet,a=(n||0)+e,o=i[a];if(!r)for(;o&&u3(o);)a+=e,o=i[a];return o}}var Het={}.hasOwnProperty;function h3(e){return t;function t(t,n,r){return Het.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var g3=h3({body:Wet,caption:_3,colgroup:_3,dd:Jet,dt:qet,head:_3,html:Uet,li:Ket,optgroup:Yet,option:Xet,p:Get,rp:v3,rt:v3,tbody:Qet,td:y3,tfoot:$et,th:y3,thead:Zet,tr:ett});function _3(e,t,n){let r=f3(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&u3(r.value.charAt(0)))}function Uet(e,t,n){let r=f3(n,t);return!r||r.type!==`comment`}function Wet(e,t,n){let r=f3(n,t);return!r||r.type!==`comment`}function Get(e,t,n){let r=f3(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function Ket(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&r.tagName===`li`}function qet(e,t,n){let r=f3(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function Jet(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function v3(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function Yet(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function Xet(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function Zet(e,t,n){let r=f3(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function Qet(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function $et(e,t,n){return!f3(n,t)}function ett(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function y3(e,t,n){let r=f3(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var ttt=h3({body:itt,colgroup:att,head:rtt,html:ntt,tbody:ott});function ntt(e){let t=f3(e,-1);return!t||t.type!==`comment`}function rtt(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function itt(e){let t=f3(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&u3(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function att(e,t,n){let r=p3(n,t),i=f3(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&g3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function ott(e,t,n){let r=p3(n,t),i=f3(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&g3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var b3={name:[[`
1034
1034
  \f\r &/=>`.split(``),`
1035
1035
  \f\r "&'/=>\``.split(``)],[`\0
1036
1036
  \f\r "&'/<=>`.split(``),`\0
@@ -1038,10 +1038,10 @@ If init has been called in the preload and contextIsolation is disabled, is not
1038
1038
  \f\r &>`.split(``),`\0
1039
1039
  \f\r "&'<=>\``.split(``)],[`\0
1040
1040
  \f\r "&'<=>\``.split(``),`\0
1041
- \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function ctt(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=$4);let l=ltt(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!ntt(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!_3(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function ltt(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=utt(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function utt(e,t,n){let r=Z4(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=s3(r.attribute,Object.assign({},e.settings.characterReferences,{subset:x3.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?l3:u3)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=s3(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:x3.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&c3(n,o)>c3(n,e.alternative)&&(o=e.alternative),s=o+s3(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?x3.single:x3.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var dtt=[`<`,`&`];function S3(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:s3(e.value,Object.assign({},r.settings.characterReferences,{subset:dtt}))}function ftt(e,t,n,r){return r.settings.allowDangerousHtml?e.value:S3(e,t,n,r)}function ptt(e,t,n,r){return r.all(e)}var mtt=t3(`type`,{invalid:htt,unknown:gtt,handlers:{comment:Let,doctype:Ret,element:ctt,raw:ftt,root:ptt,text:S3}});function htt(e){throw Error("Expected node, not `"+e+"`")}function gtt(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var _tt={},vtt={},ytt=[];function C3(e,t){let n=t||_tt,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:btt,all:xtt,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||D4,characterReferences:n.characterReferences||vtt,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?$4:Q4,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function btt(e,t,n){return mtt(e,t,n,this)}function xtt(e){let t=[],n=e&&e.children||ytt,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var Stt=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;selectedRangeHighlightSide;selectedRangeLineNumberOnly=!1;editorActiveLine=null;editorActiveLineSide;editorLineNumberOnly=!1;proposedSelectedRange;renderedSelectedLinesState;renderedEditorActiveLineState;selectionAnchor;pointerSession={mode:`idle`};constructor(e,t){this.mode=e,this.options=t}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener(`click`,this.handlePointerClick),this.pre?.removeEventListener(`pointerdown`,this.handlePointerDown),this.pre?.removeEventListener(`pointermove`,this.handlePointerMove),this.pre?.removeEventListener(`pointerleave`,this.handlePointerLeave),this.pre?.removeAttribute(`data-interactive-lines`),this.pre?.removeAttribute(`data-interactive-line-numbers`),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),K2(this.renderSelection),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1,this.setSelectionDirty()}setup(e){this.setSelectionDirty();let{usesCustomGutterUtility:t=!1,enableGutterUtility:n=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),n?this.ensureGutterUtilityNode(t):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode===`gutterSelecting`&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectedLinesState=void 0,this.renderedEditorActiveLineState=void 0}isSelectionDirty(){return this.renderedSelectedLinesState===void 0||this.renderedEditorActiveLineState===void 0}setSelection(e,t){let n=!(e===this.selectedRange||Z2(e??void 0,this.selectedRange??void 0)),r=t?.lineNumberOnly??!1,i=t?.activeLineSide!==this.selectedRangeHighlightSide||r!==this.selectedRangeLineNumberOnly;!this.isSelectionDirty()&&!n&&!i||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.selectedRangeHighlightSide=t?.activeLineSide,this.selectedRangeLineNumberOnly=r,this.renderSelection(),this.placeUtility(),n&&t?.notify!==!1&&this.notifySelectionCommitted(e))}setEditorActiveLine(e,{lineNumberOnly:t=!1,side:n}={}){let r=e!==this.editorActiveLine,i=n!==this.editorActiveLineSide||t!==this.editorLineNumberOnly;!this.isSelectionDirty()&&!r&&!i||(this.editorActiveLine=e,this.editorActiveLineSide=n,this.editorLineNumberOnly=t,this.renderSelection())}getSelection(){return this.selectedRange}getHoveredLine=()=>{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode===`diff`&&e.type===`diff-line`)return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode===`file`&&e.type===`line`)return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:r,onTokenClick:i,onMergeConflictActionClick:a}=this.options;(t!=null||n!=null||r!=null||a!=null||i!=null)&&(this.options.onGutterUtilityClick!=null&&E4(e.composedPath())||(N3(this.options.__debugPointerEvents,`click`,`FileDiff.DEBUG.handlePointerClick:`,e),this.handlePointerEvent({eventType:`click`,event:e})))};handlePointerMove=e=>{if(e.pointerType!==`mouse`)return;let{lineHoverHighlight:t=`disabled`,onLineEnter:n,onLineLeave:r,onTokenEnter:i,onTokenLeave:a,enableGutterUtility:o=!1}=this.options;t===`disabled`&&!o&&n==null&&r==null&&i==null&&a==null||(N3(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if(N3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){N3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token`);return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:t}){let{__debugPointerEvents:n}=this.options,r=t.composedPath();N3(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);N3(n,e,`FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:`,i);let{onLineClick:a,onLineNumberClick:o,onLineEnter:s,onLineLeave:c,onTokenClick:l,onTokenEnter:u,onTokenLeave:d,onHunkExpand:f,onMergeConflictActionClick:p}=this.options;switch(e){case`move`:{let e=E3(i)&&this.hoveredLine?.lineElement===i.lineElement;T3(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),T3(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),E3(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(Ett(i)&&p!=null){p(i);break}if(Ttt(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!E3(i))break;T3(i)&&l!=null&&l(this.toTokenEventBaseProps(i),t);let e=this.toEventBaseProps(i);o!=null&&i.numberColumn?o({...e,event:t}):a?.({...e,event:t});break}}}syncPointerListeners(e){let{__debugPointerEvents:t,lineHoverHighlight:n=`disabled`,onLineClick:r,onLineNumberClick:i,onLineEnter:a,onLineLeave:o,onTokenClick:s,onTokenEnter:c,onTokenLeave:l,onHunkExpand:u,onMergeConflictActionClick:d,enableGutterUtility:f=!1,enableLineSelection:p=!1,onGutterUtilityClick:m}=this.options,h=m!=null,g=n!==`disabled`||r!=null||i!=null||a!=null||o!=null||s!=null||c!=null||l!=null||u!=null||d!=null||f||p||h;g&&!this.hasPointerListeners?(e.addEventListener(`click`,this.handlePointerClick),e.addEventListener(`pointerdown`,this.handlePointerDown),e.addEventListener(`pointermove`,this.handlePointerMove),e.addEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!0,N3(t,`click`,`FileDiff.DEBUG.attachEventListeners: Attaching click events for:`,(()=>{let e=[];return(t===`both`||t===`click`)&&(r!=null&&e.push(`onLineClick`),i!=null&&e.push(`onLineNumberClick`),u!=null&&e.push(`expandable hunk separators`),d!=null&&e.push(`merge conflict actions`)),e})()),N3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),N3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event`)):!g&&this.hasPointerListeners&&(e.removeEventListener(`click`,this.handlePointerClick),e.removeEventListener(`pointerdown`,this.handlePointerDown),e.removeEventListener(`pointermove`,this.handlePointerMove),e.removeEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!1);let _=this.pointerSession.mode===`selecting`||this.pointerSession.mode===`pendingSingleLineUnselect`,v=this.pointerSession.mode===`gutterSelecting`;(!p&&_||!h&&v)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,r=e!=null,i=t!=null||n;r&&!this.interactiveLinesAttr?(this.pre.setAttribute(`data-interactive-lines`,``),this.interactiveLinesAttr=!0):!r&&this.interactiveLinesAttr&&(this.pre.removeAttribute(`data-interactive-lines`),this.interactiveLinesAttr=!1),i&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute(`data-interactive-line-numbers`,``),this.interactiveLineNumbersAttr=!0):!i&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute(`data-interactive-line-numbers`),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType===`mouse`&&e.button!==0||this.pre==null||this.pointerSession.mode!==`idle`)return;let t=e.composedPath();E4(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!==`mouse`&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:`event-path`,requireNumberColumn:!0});if(n==null)return;let{pre:r}=this;if(r==null)return;let{lineNumber:i,eventSide:a,lineIndex:o}=n;if(e.shiftKey&&this.selectedRange!=null){let t=this.getIndexesFromSelection(this.selectedRange,r.getAttribute(`data-diff-type`)===`split`);if(t==null)return;let n=t.start<=t.end?o>=t.start:o<=t.end;this.selectionAnchor={lineNumber:n?this.selectedRange.start:this.selectedRange.end,side:n?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===i&&this.selectedRange?.end===i){let t={lineNumber:i,side:a};this.selectionAnchor=t,this.pointerSession={mode:`pendingSingleLineUnselect`,pointerId:e.pointerId,anchor:t,pending:t},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:i,side:a},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{onGutterUtilityClick:t}=this.options;if(t==null)return;let n=this.currentSelectionEnds(),r=n?.bottom??this.resolveSelectionPoint(e,{source:`event-path`,excludeUtility:!1}),i=n?.top??r;r!=null&&i!=null&&(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:`gutterSelecting`,pointerId:e.pointerId,anchor:i,current:r},this.selectionAnchor={lineNumber:i.lineNumber,side:i.side},this.updateSelection(r.lineNumber,r.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionPoint(e,{source:`coordinates-first`});if(t==null)return;this.pointerSession.current=t,this.updateSelection(t.lineNumber,t.side);return}case`selecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case`pendingSingleLineUnselect`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;let n={lineNumber:t.lineNumber,side:t.eventSide};if(cet(this.pointerSession.pending,n))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:`selecting`,pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{let{onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{let{pointerSession:n}=this;if(e.pointerId!==n.pointerId)return;e.preventDefault();let r=this.resolveSelectionPoint(e,{source:`coordinates-first`});r!=null&&(n.current=r,this.updateSelection(r.lineNumber,r.side));let i=this.buildSelectedLineRange(n.anchor,n.current);t?.({...i}),this.selectionAnchor=void 0,this.notifySelectionEnd(i),this.notifySelectionCommitted(i),this.clearProposedSelection(),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case`pendingSingleLineUnselect`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection();return;case`selecting`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:case`selecting`:case`pendingSingleLineUnselect`:if(`pointerId`in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute(`data-hovered`),this.hoveredLine.numberElement.removeAttribute(`data-hovered`),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t=`disabled`}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!==`disabled`&&((t===`both`||t===`line`)&&this.hoveredLine.lineElement.setAttribute(`data-hovered`,``),(t===`both`||t===`number`)&&this.hoveredLine.numberElement.setAttribute(`data-hovered`,``))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer??(this.gutterUtilityContainer=document.createElement(`div`),this.gutterUtilityContainer.setAttribute(`data-gutter-utility-slot`,``)),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot??(this.gutterUtilitySlot=document.createElement(`slot`),this.gutterUtilitySlot.name=`gutter-utility-slot`),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let e=document.createElement(`div`);e.innerHTML=C3(set());let t=e.firstElementChild;if(!(t instanceof HTMLButtonElement))throw Error(`InteractionManager.ensureGutterUtilityNode: Node element should be a button`);t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);w3(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},r=this.selectionPointRowIndex(t),i=this.selectionPointRowIndex(n);if(r!=null&&i!=null)return r>i?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode===`diff`?`${t[0]},${t[1]}`:`${t[0]}`,r=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let t of r){if(!(t instanceof HTMLElement))continue;let n=this.resolvePointerTarget(O3(t));if(w3(n)&&(this.mode!==`diff`||e.side==null||n.side===e.side))return n}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||=(document.addEventListener(`pointermove`,this.handleDocumentPointerMove),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerCancel),!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&=(document.removeEventListener(`pointermove`,this.handleDocumentPointerMove),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerCancel),!1)}clearPointerSession(){this.pointerSession={mode:`idle`}}clearPendingSingleLineState(){this.pointerSession.mode===`pendingSingleLineUnselect`&&(this.pointerSession={mode:`idle`})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(w3(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode===`diff`?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionInfoFromPath(n,t.requireNumberColumn)}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(w3(t))return{lineNumber:t.lineNumber,side:this.mode===`diff`?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionPointFromPath(n)}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case`event-path`:return this.pathFromEventPath(e.composedPath(),n);case`coordinates-first`:{let t=this.pathFromCoordinates(e,n);return t===void 0?this.pathFromEventPath(e.composedPath(),n):t??void 0}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&E4(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=O3(e);if(t&&E4(n))return;let r=Ott(e);return r==null?this.pathFromAnnotationSlot(e):O3(r)}pathFromAnnotationSlot(e){let t=Att(ktt(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:O3(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=k3(t)?t:k3(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n==null?[e-1,e-1]:n(e,t)}getCurrentSelectionRange(){return this.proposedSelectedRange===void 0?this.selectedRange:this.proposedSelectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let r=this.getCurrentSelectionRange(),i;if(e==null)i=null;else{let n=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;i=this.buildSelectionRange(r,e,n,t)}Z2(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,G2(this.renderSelection)),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),r=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&r!=null?{start:t?n[1]:n[0],end:t?r[1]:r[0]}:void 0}getSelectionRenderState(){return{selectedLines:{range:this.selectedRange,highlightSide:this.selectedRangeHighlightSide,lineNumberOnly:this.selectedRangeLineNumberOnly},editorActiveLine:{range:this.editorActiveLine==null?null:{start:this.editorActiveLine,end:this.editorActiveLine,side:this.editorActiveLineSide},highlightSide:this.editorActiveLineSide,lineNumberOnly:this.editorLineNumberOnly}}}resolveLineRenderRange(e,t,n){if(e.range==null)return;let r=this.getIndexesFromSelection(e.range,t);if(r==null)throw console.error({rowRange:r,range:e.range}),Error(`InteractionManager.renderSelection: No valid ${n} rowRange`);return r}getLineRenderColumns(e,t,n,r){if(this.pre==null||t==null&&r==null)return[];let{children:i}=this.pre;if(i.length>2)throw console.error(i),Error(`InteractionManager.renderSelection: Somehow there are more than 2 code elements...`);let a=[];for(let o of i){let i=o.hasAttribute(`data-deletions`)?`deletions`:o.hasAttribute(`data-additions`)?`additions`:void 0,s=e!=null&&t!=null&&(e.highlightSide==null||i==null||e.highlightSide===i),c=n!=null&&r!=null&&(n.highlightSide==null||i==null||n.highlightSide===i);if(!s&&!c)continue;let[l,u]=o.children;if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))throw Error(`InteractionManager.renderSelection: missing gutter or content element`);if(u.children.length!==l.children.length)throw Error(`InteractionManager.renderSelection: gutter and content children dont match, something is wrong`);a.push({content:u,gutter:l,renderEditorActiveLine:c,renderSelectedLines:s})}return a}renderSelection=()=>{K2(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!A3(this.renderedSelectedLinesState,n),i=!A3(this.renderedEditorActiveLineState,t);if(!r&&!i)return;r&&(this.renderedSelectedLinesState=void 0),i&&(this.renderedEditorActiveLineState=void 0);let a=this.pre.getAttribute(`data-diff-type`)===`split`,o=r?this.resolveLineRenderRange(n,a,`selected-lines`):void 0,s=i?this.resolveLineRenderRange(t,a,`editor-active-line`):void 0,c=this.getLineRenderColumns(r?n:void 0,o,i?t:void 0,s),l=n.range==null||c.some(e=>e.renderSelectedLines),u=t.range==null||c.some(e=>e.renderEditorActiveLine);if(r)for(let e of this.pre.querySelectorAll(`[data-selected-line]`))e.removeAttribute(`data-selected-line`);if(i)for(let e of this.pre.querySelectorAll(`[data-editor-active-line]`))e.removeAttribute(`data-editor-active-line`);let d=o==null?void 0:Math.min(o.start,o.end),f=o==null?void 0:Math.max(o.start,o.end),p=d===f,m=s?.start;for(let e of c){let{content:r,gutter:i,renderEditorActiveLine:o,renderSelectedLines:s}=e,c=Math.max(s?f??-1/0:-1/0,o?m??-1/0:-1/0),l=r.children.length;for(let e=0;e<l;e++){let l=r.children[e],u=i.children[e];if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))continue;let h=this.parseLineIndex(l,a);if((h??0)>c)break;if(h!=null){if(s&&d!=null&&f!=null&&h>=d&&h<=f){let e=p?`single`:h===d?`first`:h===f?`last`:``;u.setAttribute(`data-selected-line`,e),n.lineNumberOnly||(l.setAttribute(`data-selected-line`,e),u.nextSibling instanceof HTMLElement&&l.nextSibling instanceof HTMLElement&&(l.nextSibling.hasAttribute(`data-line-annotation`)||l.nextSibling.hasAttribute(`data-merge-conflict-actions`))&&(p?(e=`last`,l.setAttribute(`data-selected-line`,`first`)):h===d?e=``:h===f&&l.setAttribute(`data-selected-line`,``),l.nextSibling.setAttribute(`data-selected-line`,e),u.nextSibling.setAttribute(`data-selected-line`,e)))}o&&h===m&&(u.setAttribute(`data-editor-active-line`,``),t.lineNumberOnly||l.setAttribute(`data-editor-active-line`,``))}}}r&&l&&(this.renderedSelectedLinesState=n),i&&u&&(this.renderedEditorActiveLineState=t)};notifySelectionCommitted(e){this.options.onLineSelected?.(e)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode===`file`?{type:`line`,lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:`diff-line`,annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}){return this.mode===`file`?{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:i,tokenText:a}:{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,r){return{start:e,end:t,...n==null?{}:{side:n},...n!==r&&r!=null?{endSide:r}:{}}}resolvePointerTarget(e){let t=!1,n,r,i,a,o,s,c,l,u,d;for(let f of e){if(!(f instanceof HTMLElement))continue;if(d==null&&f.hasAttribute(`data-merge-conflict-action`)){let e=f.getAttribute(`data-merge-conflict-action`)??void 0,t=f.getAttribute(`data-merge-conflict-conflict-index`)??void 0,n=t==null?NaN:Number.parseInt(t,10);Dtt(e)&&Number.isFinite(n)&&(d={kind:`merge-conflict-action`,resolution:e,conflictIndex:n})}if(s==null&&f.hasAttribute(`data-char`)){s=f;let e=f.getAttribute(`data-char`);if(e!=null){let t=Number.parseInt(e,10);if(!Number.isNaN(t)){let e=f.textContent??``,n=t+e.length;(e.trim()!==``||this.options.enableTokenInteractionsOnWhitespace===!0)&&(c={tokenElement:s,lineCharStart:t,lineCharEnd:n,tokenText:e});continue}}}let e=o==null?f.getAttribute(`data-column-number`)??void 0:void 0;if(e!=null){o=f,u=Number.parseInt(e,10),t=!0,n=M3(f),a=f.getAttribute(`data-line-index`)??void 0;continue}let p=i==null?f.getAttribute(`data-line`)??void 0:void 0;if(p!=null){i=f,u=Number.parseInt(p,10),n=M3(f),a=f.getAttribute(`data-line-index`)??void 0;continue}if(l==null&&(f.hasAttribute(`data-expand-button`)||f.hasAttribute(`data-unmodified-lines`))){l={hunkIndex:void 0,direction:f.hasAttribute(`data-expand-up`)?`up`:f.hasAttribute(`data-expand-down`)?`down`:`both`,all:f.hasAttribute(`data-expand-all-button`)};continue}let m=l==null?void 0:f.getAttribute(`data-expand-index`)??void 0;if(l!=null&&m!=null){let e=Number.parseInt(m,10);Number.isNaN(e)||(l.hunkIndex=e);continue}if(r==null&&f.hasAttribute(`data-code`)){r=f;break}}if(d!=null)return d;if(l?.hunkIndex!=null)return{type:`line-info`,hunkIndex:l.hunkIndex,direction:l.direction,all:l.all};if(i??=a==null?void 0:D3(r,`[data-line][data-line-index="${a}"]`),o??=a==null?void 0:D3(r,`[data-column-number][data-line-index="${a}"]`),r==null||i==null||o==null||n==null||u==null||Number.isNaN(u))return;let f=this.parseLineIndex(i,this.isSplitDiff());return c==null?this.mode===`file`?{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f}:{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:j3(n,r),splitLineIndex:f}:this.mode===`file`?{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f,...c}:{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:j3(n,r),splitLineIndex:f,...c}}isSplitDiff(){return this.pre?.getAttribute(`data-diff-type`)===`split`}parseLineIndex(e,t){let n=(e.getAttribute(`data-line-index`)??``).split(`,`).map(e=>Number.parseInt(e,10)).filter(e=>!Number.isNaN(e));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function Ctt({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:r,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,renderGutterUtility:d,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v},y,b,x){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:wtt({enableGutterUtility:t,renderGutterUtility:d,onGutterUtilityClick:r}),usesCustomGutterUtility:d!=null,lineHoverHighlight:n,onGutterUtilityClick:r,onHunkExpand:y,onMergeConflictActionClick:x,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v,getLineIndex:b}}function wtt({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw Error(`Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.`);return e??!1}function w3(e){return e!=null&&`kind`in e&&e.kind===`line`}function T3(e){return e!=null&&`kind`in e&&e.kind===`token`}function E3(e){return w3(e)||T3(e)}function Ttt(e){return`type`in e&&e.type===`line-info`}function Ett(e){return`kind`in e&&e.kind===`merge-conflict-action`}function Dtt(e){return e===`current`||e===`incoming`||e===`both`}function D3(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function O3(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function Ott(e){let t=e.closest(`[data-line], [data-column-number]`);if(t instanceof HTMLElement)return t;let n=e.closest(`[data-line-annotation], [data-gutter-buffer="annotation"]`);if(!(n instanceof HTMLElement))return;let r=n.previousElementSibling;return r instanceof HTMLElement&&(r.hasAttribute(`data-line`)||r.hasAttribute(`data-column-number`))?r:void 0}function ktt(e){let t=e.closest(`[slot^="annotation-"]`);if(t instanceof HTMLElement)return t.getAttribute(`slot`)??void 0;if(e instanceof HTMLElement){let t=e.getAttribute(`name`)??void 0;return t!=null&&t.startsWith(`annotation-`)?t:void 0}}function Att(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(!(!Number.isFinite(n)||n<=0))return{lineNumber:n,side:t[1]}}function k3(e){return e!=null&&typeof e.elementFromPoint==`function`}function jtt(e,t){return e===t||Z2(e??void 0,t??void 0)}function A3(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&jtt(e?.range??null,t.range)}function j3(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function M3(e){let t=e.getAttribute(`data-line-type`);if(t!=null)switch(t){case`change-deletion`:case`change-addition`:case`context`:case`context-expanded`:return t;default:return}}function N3(e=`none`,t,...n){switch(e){case`none`:return;case`both`:break;case`click`:if(t!==`click`)return;break;case`move`:if(t!==`move`)return}console.log(...n)}var Mtt=class e{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){let t=e.resizeObserver??new ResizeObserver(e.handleSharedResizeEntries);return e.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let r of t){let t=e.managersByElement.get(r.target);if(t==null)continue;let i=n.get(t);i==null?n.set(t,[r]):i.push(r)}for(let[e,t]of n)e.handleResizeEntries(t)}observedNodes=new Map;setup(e,{disableAnnotations:t,columnVariables:n=`apply`}){let r=new Set,i=n===`apply`,a=0,o=new Map(this.observedNodes);this.observedNodes.clear();for(let t of e.children){if(a===2)break;let e=(()=>{if(t instanceof HTMLElement&&t.tagName===`CODE`)return t})();if(e==null)continue;a++;let n=o.get(e);if(n!=null&&n.type!==`code`)throw Error(`ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible`);let r=e.firstElementChild;r instanceof HTMLElement||(r=null),n==null?(n={type:`code`,codeElement:e,numberElement:r,codeWidth:`auto`,numberWidth:0,applyColumnVariables:i},this.observedNodes.set(e,n),this.observe(e),r!=null&&(this.observedNodes.set(r,n),this.observe(r))):(this.observedNodes.set(e,n),o.delete(e),n.numberElement===r?n.numberElement==null?n.numberWidth=0:(o.delete(n.numberElement),this.observedNodes.set(n.numberElement,n)):(n.numberElement!=null&&(this.unobserve(n.numberElement),o.delete(n.numberElement)),r!=null&&(this.observe(r),o.delete(r),this.observedNodes.set(r,n)),n.numberElement=r,n.numberWidth=0),Ftt(n,i))}if(a>1&&!t){let t=e.querySelectorAll(`[data-line-annotation*=","]`),n=new Map;for(let e of t){if(!(e instanceof HTMLElement))continue;let t=e.getAttribute(`data-line-annotation`)??``;if(!/^-?\d+,-?\d+$/.test(t)){console.error(`DiffFileRenderer.setupResizeObserver: Invalid element or annotation`,{lineAnnotation:t,element:e});continue}let r=n.get(t);r??(r=[],n.set(t,r)),r.push(e)}for(let[e,t]of n){if(t.length!==2){console.error(`DiffFileRenderer.setupResizeObserver: Bad Pair`,e,t);continue}let[n,i]=t,a=n.firstElementChild,s=i.firstElementChild;if(!(n instanceof HTMLElement)||!(i instanceof HTMLElement)||!(a instanceof HTMLElement)||!(s instanceof HTMLElement))continue;let c=o.get(a);if(c!=null){this.observedNodes.set(a,c),this.observedNodes.set(s,c),o.delete(a),o.delete(s);continue}let l=a.getBoundingClientRect().height,u=s.getBoundingClientRect().height;c={type:`annotations`,column1:{container:n,child:a,childHeight:l},column2:{container:i,child:s,childHeight:u},currentHeight:`auto`},r.add({child1:a,child2:s,item:c,newHeight:Math.max(l,u)})}for(let e of r)this.applyNewHeight(e.item,e.newHeight),this.observedNodes.set(e.child1,e.item),this.observedNodes.set(e.child2,e.item),this.observe(e.child1),this.observe(e.child2);r.clear()}for(let[e,t]of o)this.unobserve(e),t.type===`code`?Itt(t):Ltt(t);o.clear()}cleanUp(){for(let e of this.observedNodes.keys())this.unobserve(e);this.observedNodes.clear()}observe(t){let{managersByElement:n}=e,r=n.get(t);if(r!==this){if(r!=null&&r!==this)throw Error(`ResizeManager.observe: element is already owned by another ResizeManager`);n.set(t,this),e.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:r}=e,i=n.get(t);if(i!=null){if(i!==this)throw Error(`ResizeManager.unobserve: element is owned by another ResizeManager`);n.delete(t),r?.unobserve(t),r!=null&&n.size===0&&(r.disconnect(),e.resizeObserver=void 0)}}handleResizeEntries(e){let t=new Map,n=new Set;for(let r of e){let{target:e,borderBoxSize:i,contentBoxSize:a}=r;if(!(e instanceof HTMLElement)){console.error(`ResizeManager.handleResizeEntries: Invalid element for ResizeObserver`,r);continue}let o=this.observedNodes.get(e);if(o==null){console.error(`ResizeManager.handleResizeEntries: Not a valid observed node`,r);continue}if(o.type===`annotations`){let t=(()=>{if(e===o.column1.child)return o.column1;if(e===o.column2.child)return o.column2})();if(t==null){console.error(`ResizeManager.handleResizeEntries: Couldn't find a column for`,{item:o,target:e});continue}t.childHeight=i[0].blockSize,n.add(o)}else if(o.type===`code`){let n=t.get(o)??{},r=a[0].inlineSize;e===o.codeElement?n.codeInlineSize=r:e===o.numberElement&&(n.numberInlineSize=r),t.set(o,n)}}this.applyAnnotationUpdates(n),n.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(e){for(let t of e)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=e=>{for(let[t,n]of e){let e=n.codeInlineSize==null?t.codeWidth:Ntt(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:Ptt(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&P3(t,{codeWidthChanged:i,numberWidthChanged:a}))}};applyNewHeight(e,t){t!==e.currentHeight&&(e.currentHeight=Math.max(t,0),e.column1.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`),e.column2.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`))}};function Ntt(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function Ptt(e){return Math.max(Math.ceil(e),0)}function Ftt(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?P3(e,{codeWidthChanged:!0,numberWidthChanged:!0}):F3(e))}function P3(e,{codeWidthChanged:t,numberWidthChanged:n}){let{codeElement:r,codeWidth:i,numberWidth:a}=e;if(t&&r.style.setProperty(`--diffs-column-width`,`${typeof i==`number`?`${i}px`:`auto`}`),n&&r.style.setProperty(`--diffs-column-number-width`,`${a===0?`auto`:`${a}px`}`),t||n&&i!==`auto`){let e=typeof i==`number`?Math.max(i-a,0):0;r.style.setProperty(`--diffs-column-content-width`,`${e>0?`${e}px`:`auto`}`)}}function F3(e){e.codeElement.style.removeProperty(`--diffs-column-content-width`),e.codeElement.style.removeProperty(`--diffs-column-number-width`),e.codeElement.style.removeProperty(`--diffs-column-width`)}function Itt(e){e.codeElement.isConnected&&F3(e)}function Ltt(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty(`--diffs-annotation-min-height`),e.column2.container.isConnected&&e.column2.container.style.removeProperty(`--diffs-annotation-min-height`)}var I3=new Map,L3=new Map,Rtt=new Map,R3=new Set;function ztt(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!R3.has(t))return!1;return!0}function z3(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(R3.has(n.name))continue;let e=I3.get(n.name);e??(e=n,I3.set(n.name,e)),R3.add(e.name),t.loadLanguageSync(e.data)}}function B3(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var V3=Object.defineProperty,Btt=Object.getOwnPropertyDescriptor,Vtt=Object.getOwnPropertyNames,Htt=Object.prototype.hasOwnProperty,Utt=(e,t)=>{let n={};for(var r in e)V3(n,r,{get:e[r],enumerable:!0});return t||V3(n,Symbol.toStringTag,{value:`Module`}),n},H3=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Vtt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Htt.call(e,s)&&s!==n&&V3(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Btt(t,s))||r.enumerable});return e},Wtt=(e,t,n)=>(H3(e,t,`default`),n&&H3(n,t,`default`)),U3=[{id:`abap`,name:`ABAP`,import:(()=>N(()=>import(`./abap-CLvhMVsD.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>N(()=>import(`./actionscript-3--17pq3dv.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>N(()=>import(`./ada-C5qYipkI.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>N(()=>import(`./angular-html-B8mrqUL5.js`).then(e=>e.n),__vite__mapDeps([6,1,7,8,9])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>N(()=>import(`./angular-ts-Bzix210W.js`),__vite__mapDeps([10,6,1,7,8,9,11])))},{id:`apache`,name:`Apache Conf`,import:(()=>N(()=>import(`./apache-U0d_L8uA.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>N(()=>import(`./apex-CGTLDQj6.js`),[]))},{id:`apl`,name:`APL`,import:(()=>N(()=>import(`./apl-Dhin1L29.js`),__vite__mapDeps([12,8,1,9,7,13,14,15])))},{id:`applescript`,name:`AppleScript`,import:(()=>N(()=>import(`./applescript-CCn79oCD.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>N(()=>import(`./ara-4CJ0cIlV.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>N(()=>import(`./asciidoc-DE70LPWp.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>N(()=>import(`./asm-Cmm7eHzH.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>N(()=>import(`./astro-B-4NNgOP.js`),__vite__mapDeps([16,8,1,9,15,17,18,19])))},{id:`awk`,name:`AWK`,import:(()=>N(()=>import(`./awk-BWXHIvNe.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>N(()=>import(`./ballerina-B7ZEbQpA.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>N(()=>import(`./bat-Bo4NYOV-.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>N(()=>import(`./beancount-D-usSTwE.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>N(()=>import(`./berry-DKpUyyne.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>N(()=>import(`./bibtex-Ci_nEsc7.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>N(()=>import(`./bicep-CUHmPFLl.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>N(()=>import(`./bird2-C6vDhewU.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>N(()=>import(`./blade-Wr94ul2N.js`),__vite__mapDeps([20,8,1,9,7,13,14,15,21,22])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>N(()=>import(`./bsl-BkkzgIyY.js`),__vite__mapDeps([23,24])))},{id:`c`,name:`C`,import:(()=>N(()=>import(`./c-iCihek07.js`).then(e=>e.n),__vite__mapDeps([25,1])))},{id:`c3`,name:`C3`,import:(()=>N(()=>import(`./c3-CnJL0r0V.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>N(()=>import(`./cadence-CQ2zXKGN.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>N(()=>import(`./cairo-DLTphjLi.js`),__vite__mapDeps([26,27])))},{id:`clarity`,name:`Clarity`,import:(()=>N(()=>import(`./clarity-SemFz856.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>N(()=>import(`./clojure-DqKBuwfJ.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>N(()=>import(`./cmake-Bj61d0ZC.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>N(()=>import(`./cobol-Cw2-KvLW.js`),__vite__mapDeps([28,7,1,8,9,14])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>N(()=>import(`./codeowners-C8r90Shi.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>N(()=>import(`./codeql-oeQT6MSM.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>N(()=>import(`./coffee-CiiSLhB6.js`),__vite__mapDeps([29,8,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>N(()=>import(`./common-lisp-Cv5bFMCO.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>N(()=>import(`./coq-BrsZFFmf.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>N(()=>import(`./cpp-DjoE5qBx.js`).then(e=>e.n),__vite__mapDeps([30,1,22,31,32,25])))},{id:`crystal`,name:`Crystal`,import:(()=>N(()=>import(`./crystal-wCJpIkgB.js`),__vite__mapDeps([33,8,1,9,7,22,25,34])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>N(()=>import(`./csharp-Ct8U2NOr.js`),[]))},{id:`css`,name:`CSS`,import:(()=>N(()=>import(`./css-CNuuLpMC.js`).then(e=>e.n),__vite__mapDeps([9,1])))},{id:`csv`,name:`CSV`,import:(()=>N(()=>import(`./csv-Dx-8-gkx.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>N(()=>import(`./cue-CE9AQfxI.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>N(()=>import(`./cypher-ClKdZ_lG.js`),[]))},{id:`d`,name:`D`,import:(()=>N(()=>import(`./d-qD-0Kul2.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>N(()=>import(`./dart-CnvKMtbv.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>N(()=>import(`./dax-BkyTk9wS.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>N(()=>import(`./desktop-Dlh5hvp9.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>N(()=>import(`./diff-woXpYk--.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>N(()=>import(`./docker-IyjqRm3v.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>N(()=>import(`./dotenv-_5a1GRtc.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>N(()=>import(`./dream-maker-DW3nJb8Q.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>N(()=>import(`./edge-DCY0a-ow.js`),__vite__mapDeps([35,7,1,8,9,17,21])))},{id:`elixir`,name:`Elixir`,import:(()=>N(()=>import(`./elixir-DP304Xio.js`),__vite__mapDeps([36,7,1,8,9])))},{id:`elm`,name:`Elm`,import:(()=>N(()=>import(`./elm-o4NJxfws.js`),__vite__mapDeps([37,32,1,25])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>N(()=>import(`./emacs-lisp-B4R74twV.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>N(()=>import(`./erb-BcNYoZVd.js`),__vite__mapDeps([38,7,1,8,9,39,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>N(()=>import(`./erlang-Cphh6RMH.js`),__vite__mapDeps([45,46])))},{id:`fennel`,name:`Fennel`,import:(()=>N(()=>import(`./fennel-DQxkIbk2.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>N(()=>import(`./fish-BJitypiv.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>N(()=>import(`./fluent-C03EYrpw.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>N(()=>import(`./fortran-fixed-form-DEKoE2YW.js`),__vite__mapDeps([47,48])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>N(()=>import(`./fortran-free-form-CYNrtFtB.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>N(()=>import(`./fsharp-D13ZGOAj.js`),__vite__mapDeps([49,46])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>N(()=>import(`./gdresource-C0sCabJj.js`),__vite__mapDeps([50,51,52])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>N(()=>import(`./gdscript-Cp2uCuqX.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>N(()=>import(`./gdshader-CBce3t8t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>N(()=>import(`./genie-CV2tkWYe.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>N(()=>import(`./gherkin-DExj1W_8.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>N(()=>import(`./git-commit-BSykSTBG.js`),__vite__mapDeps([53,54])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>N(()=>import(`./git-rebase-BDPpS8w6.js`),__vite__mapDeps([55,34,1])))},{id:`gleam`,name:`Gleam`,import:(()=>N(()=>import(`./gleam-CSRkHgEL.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>N(()=>import(`./glimmer-js-BONyzAsu.js`),__vite__mapDeps([56,8,1,9,7,17])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>N(()=>import(`./glimmer-ts-f9c0GCOe.js`),__vite__mapDeps([57,8,1,9,7,17])))},{id:`glsl`,name:`GLSL`,import:(()=>N(()=>import(`./glsl-D5MA2a_X.js`).then(e=>e.n),__vite__mapDeps([32,1,25])))},{id:`gn`,name:`GN`,import:(()=>N(()=>import(`./gn-ilITqXS6.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>N(()=>import(`./gnuplot-7GGW24-e.js`),[]))},{id:`go`,name:`Go`,import:(()=>N(()=>import(`./go-rLFTqkRN.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>N(()=>import(`./graphql-Ctjuxyvl.js`).then(e=>e.n),__vite__mapDeps([41,1,8,17,19,42])))},{id:`groovy`,name:`Groovy`,import:(()=>N(()=>import(`./groovy-CacY0gHj.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>N(()=>import(`./hack-7ztQ7Up-.js`),__vite__mapDeps([58,7,1,8,9,22])))},{id:`haml`,name:`Ruby Haml`,import:(()=>N(()=>import(`./haml-CwEpbK1d.js`).then(e=>e.n),__vite__mapDeps([40,1,8,9])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>N(()=>import(`./handlebars-ryMP1rBR.js`),__vite__mapDeps([59,8,1,9,7,44])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>N(()=>import(`./haskell-D8IpX4py.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>N(()=>import(`./haxe-OTjmBuCE.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>N(()=>import(`./hcl-Dh228itO.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>N(()=>import(`./hjson-CxZEssPk.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>N(()=>import(`./hlsl-Cvrh5tZx.js`),[]))},{id:`html`,name:`HTML`,import:(()=>N(()=>import(`./html-XwrE-1r6.js`).then(e=>e.n),__vite__mapDeps([7,1,8,9])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>N(()=>import(`./html-derivative-i4STDFnl.js`),__vite__mapDeps([21,7,1,8,9])))},{id:`http`,name:`HTTP`,import:(()=>N(()=>import(`./http-kmH8AyfE.js`),__vite__mapDeps([60,13,1,14,15,34,41,8,17,19,42])))},{id:`hurl`,name:`Hurl`,import:(()=>N(()=>import(`./hurl-DCZHXKU4.js`),__vite__mapDeps([61,13,1,14,62,41,8,17,19,42])))},{id:`hxml`,name:`HXML`,import:(()=>N(()=>import(`./hxml-B0Qn7Nwc.js`),__vite__mapDeps([63,64])))},{id:`hy`,name:`Hy`,import:(()=>N(()=>import(`./hy-CZbG8q4J.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>N(()=>import(`./imba-DsUTQ-LC.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>N(()=>import(`./ini-B5eOa1yu.js`),[]))},{id:`java`,name:`Java`,import:(()=>N(()=>import(`./java-DdHNQ9hk.js`).then(e=>e.n),__vite__mapDeps([14,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>N(()=>import(`./javascript-obGGvMPs.js`).then(e=>e.n),__vite__mapDeps([8,1])))},{id:`jinja`,name:`Jinja`,import:(()=>N(()=>import(`./jinja-B-tLrNsM.js`),__vite__mapDeps([65,7,1,8,9])))},{id:`jison`,name:`Jison`,import:(()=>N(()=>import(`./jison-CBjhYtSs.js`),__vite__mapDeps([66,8,1])))},{id:`json`,name:`JSON`,import:(()=>N(()=>import(`./json-DAgxKhMr.js`).then(e=>e.n),__vite__mapDeps([15,1])))},{id:`json5`,name:`JSON5`,import:(()=>N(()=>import(`./json5-BR5RXkoi.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>N(()=>import(`./jsonc-CYpm1nAK.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>N(()=>import(`./jsonl-CmCQp5Yx.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>N(()=>import(`./jsonnet-CJTPZ8u_.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>N(()=>import(`./jssm-DXw9l8Rf.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>N(()=>import(`./jsx-gTgmArGx.js`).then(e=>e.n),__vite__mapDeps([42,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>N(()=>import(`./julia-CjHxn3vf.js`),__vite__mapDeps([67,8,1,22,27,30,31,32,25,68])))},{id:`just`,name:`Just`,import:(()=>N(()=>import(`./just-CZ9bduw9.js`),__vite__mapDeps([69,8,1,17,27,34,39,9,7,13,14,22,25,30,31,32,40,41,19,42,43,44,70])))},{id:`kdl`,name:`KDL`,import:(()=>N(()=>import(`./kdl-CsD5j6eV.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>N(()=>import(`./kotlin-DhhofPvG.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>N(()=>import(`./kusto-C7mF5XQf.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>N(()=>import(`./latex-D9bvcAJr.js`),__vite__mapDeps([71,72,68,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>N(()=>import(`./lean-CewbzKMR.js`),[]))},{id:`less`,name:`Less`,import:(()=>N(()=>import(`./less-DVTAwKKz.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>N(()=>import(`./liquid-G0MH4h_m.js`),__vite__mapDeps([73,8,1,9,7,15])))},{id:`llvm`,name:`LLVM IR`,import:(()=>N(()=>import(`./llvm-Cm23YOpf.js`),[]))},{id:`log`,name:`Log file`,import:(()=>N(()=>import(`./log-BNLmms1o.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>N(()=>import(`./logo-Cluzi2Zq.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>N(()=>import(`./lua-FONpmTUP.js`).then(e=>e.n),__vite__mapDeps([43,1,25])))},{id:`luau`,name:`Luau`,import:(()=>N(()=>import(`./luau-CNKltnaQ.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>N(()=>import(`./make-Dixweg8N.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>N(()=>import(`./markdown-BYOwaDjH.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>N(()=>import(`./marko-DV5GrDmo.js`),__vite__mapDeps([74,9,1,11,17,75])))},{id:`matlab`,name:`MATLAB`,import:(()=>N(()=>import(`./matlab-D7qyCx1q.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>N(()=>import(`./mdc-cg1lnqpW.js`),__vite__mapDeps([76,21,7,1,8,9,44,46])))},{id:`mdx`,name:`MDX`,import:(()=>N(()=>import(`./mdx-DQZ5AkYe.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>N(()=>import(`./mermaid-Bk4SNUv9.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>N(()=>import(`./mipsasm-BMqwQI7S.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>N(()=>import(`./mojo-BgCJLMeH.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>N(()=>import(`./moonbit-CaWjb8XO.js`),[]))},{id:`move`,name:`Move`,import:(()=>N(()=>import(`./move-B1IS1UjX.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>N(()=>import(`./narrat-_X_XdTYD.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>N(()=>import(`./nextflow-BJtWHP5T.js`),__vite__mapDeps([77,78])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>N(()=>import(`./nextflow-groovy-DJMQeKeT.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>N(()=>import(`./nginx-BTMw9COX.js`),__vite__mapDeps([79,43,1,25])))},{id:`nim`,name:`Nim`,import:(()=>N(()=>import(`./nim-B6yJ_yaC.js`),__vite__mapDeps([80,8,1,9,7,13,14,25,32,46])))},{id:`nix`,name:`Nix`,import:(()=>N(()=>import(`./nix-IvuFDN5E.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>N(()=>import(`./nushell-DcLAeLz5.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>N(()=>import(`./objective-c-D1A_Heim.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>N(()=>import(`./objective-cpp-BsSzOQcm.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>N(()=>import(`./ocaml-O90oeIOV.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>N(()=>import(`./odin-B1RWQWA5.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>N(()=>import(`./openscad-BUDT5pXO.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>N(()=>import(`./pascal-4ZHwLPI5.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>N(()=>import(`./perl-BAov3eih.js`),__vite__mapDeps([70,8,1,9,7,13,14,22])))},{id:`php`,name:`PHP`,import:(()=>N(()=>import(`./php-Cg76ANFt.js`),__vite__mapDeps([81,8,1,9,7,13,14,15,22])))},{id:`pkl`,name:`Pkl`,import:(()=>N(()=>import(`./pkl-ot-7Btpt.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>N(()=>import(`./plsql-DGHpHOYJ.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>N(()=>import(`./po-BiJDBrnU.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>N(()=>import(`./polar-C7UOKdEL.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>N(()=>import(`./postcss-BXeXVLqQ.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>N(()=>import(`./powerquery-DNMTfnFr.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>N(()=>import(`./powershell-DshXNtvi.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>N(()=>import(`./prisma-BsRQq5mF.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>N(()=>import(`./prolog-iXnhIJG7.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>N(()=>import(`./proto-DB4EqR-F.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>N(()=>import(`./pug-DkgDHZci.js`),__vite__mapDeps([82,8,1,9,7])))},{id:`puppet`,name:`Puppet`,import:(()=>N(()=>import(`./puppet-CDv2pdJW.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>N(()=>import(`./purescript-9MfHhQsQ.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>N(()=>import(`./python-gzcpVVnB.js`),[]))},{id:`qml`,name:`QML`,import:(()=>N(()=>import(`./qml-_a-QhfPD.js`),__vite__mapDeps([83,8,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>N(()=>import(`./qmldir-DCQb3MpD.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>N(()=>import(`./qss-Fe1Jh2GI.js`),[]))},{id:`r`,name:`R`,import:(()=>N(()=>import(`./r-D6UWEOL2.js`).then(e=>e.n),__vite__mapDeps([68,1])))},{id:`racket`,name:`Racket`,import:(()=>N(()=>import(`./racket-DcIDlBhZ.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>N(()=>import(`./raku-B3gFvitq.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>N(()=>import(`./razor-D3EoCAik.js`),__vite__mapDeps([84,7,1,8,9,85])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>N(()=>import(`./reg-CRGYupPL.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>N(()=>import(`./regexp-DR20uMnK.js`).then(e=>e.n),__vite__mapDeps([31,1])))},{id:`rel`,name:`Rel`,import:(()=>N(()=>import(`./rel-BtDbiS_P.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>N(()=>import(`./riscv-Ckw8ddFX.js`),[]))},{id:`ron`,name:`RON`,import:(()=>N(()=>import(`./ron-VUp2lXgN.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>N(()=>import(`./rosmsg-CAekHB0j.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>N(()=>import(`./rst-YTmaoyaq.js`),__vite__mapDeps([86,8,1,21,7,9,27,87,30,22,31,32,25,34,44,39,13,14,40,41,17,19,42,43])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>N(()=>import(`./ruby-2bd251b9.js`),__vite__mapDeps([39,8,1,9,7,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>N(()=>import(`./rust-Cfkwpbl8.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>N(()=>import(`./sas-B6p8-ynO.js`),__vite__mapDeps([88,22,1])))},{id:`sass`,name:`Sass`,import:(()=>N(()=>import(`./sass-DXrisJhu.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>N(()=>import(`./scala-DKOlJaKm.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>N(()=>import(`./scheme-DQCgrYNe.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>N(()=>import(`./scss-YesllqfO.js`).then(e=>e.n),__vite__mapDeps([11,1,9])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>N(()=>import(`./sdbl-bTVj8UrX.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>N(()=>import(`./shaderlab-TOUzSsQk.js`),__vite__mapDeps([89,90])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>N(()=>import(`./shellscript-Da78Ox-3.js`).then(e=>e.n),__vite__mapDeps([34,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>N(()=>import(`./shellsession-CVsQGYfZ.js`),__vite__mapDeps([91,34,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>N(()=>import(`./smalltalk-B16xEiuN.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>N(()=>import(`./solidity-CKzVLygQ.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>N(()=>import(`./soy-DEd-qcad.js`),__vite__mapDeps([92,7,1,8,9])))},{id:`sparql`,name:`SPARQL`,import:(()=>N(()=>import(`./sparql-D_iOobhT.js`),__vite__mapDeps([93,94])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>N(()=>import(`./splunk-BC2Px7Mm.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>N(()=>import(`./sql-ClgswhA6.js`).then(e=>e.n),__vite__mapDeps([22,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>N(()=>import(`./ssh-config-BgfXC-Er.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>N(()=>import(`./stata-RoaAgbqU.js`),__vite__mapDeps([95,22,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>N(()=>import(`./stylus-B6D30XZt.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>N(()=>import(`./surrealql-DIn4NJsS.js`),__vite__mapDeps([96,8,1])))},{id:`svelte`,name:`Svelte`,import:(()=>N(()=>import(`./svelte-Bj3Hmc9F.js`),__vite__mapDeps([97,8,1,9,17,18])))},{id:`swift`,name:`Swift`,import:(()=>N(()=>import(`./swift-DonLKvLd.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>N(()=>import(`./system-verilog-DJ5XKQeo.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>N(()=>import(`./systemd-BxMlprV5.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>N(()=>import(`./talonscript-CohzipZa.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>N(()=>import(`./tasl-DMoTqEGO.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>N(()=>import(`./tcl-CZd0xW_V.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>N(()=>import(`./templ-TjxbArHn.js`),__vite__mapDeps([98,8,1,9,99])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>N(()=>import(`./terraform-DswuEJGm.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>N(()=>import(`./tex-0w6-Dtgt.js`),__vite__mapDeps([72,68,1])))},{id:`toml`,name:`TOML`,import:(()=>N(()=>import(`./toml-CcmNWLt0.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>N(()=>import(`./ts-tags-DFwAVxhO.js`),__vite__mapDeps([100,8,1,9,7,13,14,17,22,32,25])))},{id:`tsv`,name:`TSV`,import:(()=>N(()=>import(`./tsv-sltzmVWM.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>N(()=>import(`./tsx-CUOciP0b.js`).then(e=>e.n),__vite__mapDeps([19,1])))},{id:`turtle`,name:`Turtle`,import:(()=>N(()=>import(`./turtle-ByJddavk.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>N(()=>import(`./twig-BbcH-NR0.js`),__vite__mapDeps([101,8,1,9,11,27,39,7,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44,81,15])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>N(()=>import(`./typescript-BydbNFcO.js`).then(e=>e.n),__vite__mapDeps([17,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>N(()=>import(`./typespec-BRdr0IET.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>N(()=>import(`./typst-DI99ib-x.js`),[]))},{id:`v`,name:`V`,import:(()=>N(()=>import(`./v-DETTlOr0.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>N(()=>import(`./vala-zf12oZj6.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>N(()=>import(`./vb-Djn5o6TS.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>N(()=>import(`./verilog-CiiDBU1e.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>N(()=>import(`./vhdl-BroJfC0k.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>N(()=>import(`./viml-DvXPmvsu.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>N(()=>import(`./vue-BNi0qJZP.js`),__vite__mapDeps([102,8,1,9,7,15,17,21])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>N(()=>import(`./vue-html-DkKkQnZL.js`),__vite__mapDeps([103,8,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>N(()=>import(`./vue-vine-DFaKYU4X.js`),__vite__mapDeps([104,8,1,9,11,18,75,105])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>N(()=>import(`./vyper-CgoNMtux.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>N(()=>import(`./wasm-ByWQv1Qj.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>N(()=>import(`./wenyan-C8pVoKbM.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>N(()=>import(`./wgsl-BsKzXJz4.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>N(()=>import(`./wikitext-ClFFjSW2.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>N(()=>import(`./wit-DdvCle-K.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>N(()=>import(`./wolfram-DLL8P-h_.js`),[]))},{id:`xml`,name:`XML`,import:(()=>N(()=>import(`./xml-BlnrEAEy.js`).then(e=>e.n),__vite__mapDeps([13,1,14])))},{id:`xsl`,name:`XSL`,import:(()=>N(()=>import(`./xsl-BOPS8gLt.js`),__vite__mapDeps([106,13,1,14])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>N(()=>import(`./yaml-Du_6cdrH.js`).then(e=>e.n),__vite__mapDeps([44,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>N(()=>import(`./zenscript-BnlCZFoB.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>N(()=>import(`./zig-CMLA9XwU.js`),[]))}],Gtt=Object.fromEntries(U3.map(e=>[e.id,e.import])),Ktt=Object.fromEntries(U3.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),W3={...Gtt,...Ktt},qtt=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>N(()=>import(`./andromeeda-WkhI09AS.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>N(()=>import(`./aurora-x-C7CFqhAd.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>N(()=>import(`./ayu-dark-CRu61w6_.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>N(()=>import(`./ayu-light-Dn6O_aYR.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>N(()=>import(`./ayu-mirage-CTjYAbs-.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-frappe-DFlFW5gh.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>N(()=>import(`./catppuccin-latte-CpxdcXpJ.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-macchiato-DIdIQ04K.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-mocha-Co3Xjl64.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>N(()=>import(`./dark-plus-GAt2ZgX8.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>N(()=>import(`./dracula-C2uKkzgK.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>N(()=>import(`./dracula-soft-D1bVjxWZ.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>N(()=>import(`./everforest-dark-D-DlICQR.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>N(()=>import(`./everforest-light-CeVdGHYG.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>N(()=>import(`./github-dark-DwbbXv51.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>N(()=>import(`./github-dark-default-CxjRwzl6.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>N(()=>import(`./github-dark-dimmed-Cr1oaoul.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>N(()=>import(`./github-dark-high-contrast-B4qJZLZa.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>N(()=>import(`./github-light-CsVXhIlR.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>N(()=>import(`./github-light-default-DB_IwZa6.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>N(()=>import(`./github-light-high-contrast-DLgVeSB-.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-hard-DXm60lX3.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-medium-GE2thSmD.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-soft-04Cj-4VZ.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-hard-K6wSn29D.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-medium-CVy3aSlc.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-soft-DNgJjaY0.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>N(()=>import(`./horizon-0-RkHfro.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>N(()=>import(`./horizon-bright-BgL2X9oq.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>N(()=>import(`./houston-KyjWKfuY.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-dragon-7TqgsUPC.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>N(()=>import(`./kanagawa-lotus-CqxMQulh.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-wave-D8CNn6T_.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>N(()=>import(`./laserwave-CQkdhozh.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>N(()=>import(`./light-plus-CNQ8_7Y0.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>N(()=>import(`./material-theme-CAtLaHa3.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>N(()=>import(`./material-theme-darker-k-s5Bc6K.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>N(()=>import(`./material-theme-lighter-CD6a-c4d.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>N(()=>import(`./material-theme-ocean-B3mraInd.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>N(()=>import(`./material-theme-palenight-DEhAARHw.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>N(()=>import(`./min-dark-BFqTAwCr.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>N(()=>import(`./min-light-O7UdaaxX.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>N(()=>import(`./monokai-C0p7Qecz.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>N(()=>import(`./night-owl-BsnCLAKc.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>N(()=>import(`./night-owl-light-BODRhcTU.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>N(()=>import(`./nord-Cd-F4txO.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>N(()=>import(`./one-dark-pro-DUS_IGRK.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>N(()=>import(`./one-light-CVUd7yD5.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>N(()=>import(`./plastic-CF8VZTnn.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>N(()=>import(`./poimandres-BX2TyY6j.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>N(()=>import(`./red-7ga_dcKu.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-rh6ipraJ.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>N(()=>import(`./rose-pine-dawn-DSuRaP6u.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-moon-DdHjCvFQ.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>N(()=>import(`./slack-dark-DYvUXyrP.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>N(()=>import(`./slack-ochin-bqtMVDfH.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>N(()=>import(`./snazzy-light-D8dzFmq5.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>N(()=>import(`./solarized-dark-BQwPDzxK.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>N(()=>import(`./solarized-light-BLaijb3X.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>N(()=>import(`./synthwave-84-CIknw8y7.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>N(()=>import(`./tokyo-night-iIspnLcq.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>N(()=>import(`./vesper-D5bVUKB1.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>N(()=>import(`./vitesse-black-D082JcaE.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>N(()=>import(`./vitesse-dark-z-nr_5O8.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>N(()=>import(`./vitesse-light-ojz42ZLy.js`),[]))}].map(e=>[e.id,e.import])),Jtt=e({createOnigurumaEngine:()=>t6,getDefaultWasmLoader:()=>dnt,loadWasm:()=>Q3,setDefaultWasmLoader:()=>unt}),G3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Ytt(){return 2147483648}function Xtt(){return typeof performance<`u`?performance.now():Date.now()}var Ztt=(e,t)=>e+(t-e%t)%t;async function Qtt(e){let t,n,r={};function i(e){n=e,r.HEAPU8=new Uint8Array(e),r.HEAPU32=new Uint32Array(e)}function a(e,t,n){r.HEAPU8.copyWithin(e,t,t+n)}function o(e){try{return t.grow(e-n.byteLength+65535>>>16),i(t.buffer),1}catch{}}function s(e){let t=r.HEAPU8.length;e>>>=0;let n=Ytt();if(e>n)return!1;for(let r=1;r<=4;r*=2){let i=t*(1+.2/r);if(i=Math.min(i,e+100663296),o(Math.min(n,Ztt(Math.max(e,i),65536))))return!0}return!1}let c=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0;function l(e,t,n=1024){let r=t+n,i=t;for(;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&c)return c.decode(e.subarray(t,i));let a=``;for(;t<i;){let n=e[t++];if(!(n&128)){a+=String.fromCharCode(n);continue}let r=e[t++]&63;if((n&224)==192){a+=String.fromCharCode((n&31)<<6|r);continue}let i=e[t++]&63;if(n=(n&240)==224?(n&15)<<12|r<<6|i:(n&7)<<18|r<<12|i<<6|e[t++]&63,n<65536)a+=String.fromCharCode(n);else{let e=n-65536;a+=String.fromCharCode(55296|e>>10,56320|e&1023)}}return a}function u(e,t){return e?l(r.HEAPU8,e,t):``}let d={emscripten_get_now:Xtt,emscripten_memcpy_big:a,emscripten_resize_heap:s,fd_write:()=>0};async function f(){let n=await e({env:d,wasi_snapshot_preview1:d});t=n.memory,i(t.buffer),Object.assign(r,n),r.UTF8ToString=u}return await f(),r}var $tt=Object.defineProperty,ent=(e,t,n)=>t in e?$tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K3=(e,t,n)=>ent(e,typeof t==`symbol`?t:t+``,n),q3=null;function tnt(e){throw new G3(e.UTF8ToString(e.getLastOnigError()))}var J3=class e{constructor(t){K3(this,`utf16Length`),K3(this,`utf8Length`),K3(this,`utf16Value`),K3(this,`utf8Value`),K3(this,`utf16OffsetToUtf8`),K3(this,`utf8OffsetToUtf16`);let n=t.length,r=e._utf8ByteLength(t),i=r!==n,a=i?new Uint32Array(n+1):null;i&&(a[n]=r);let o=i?new Uint32Array(r+1):null;i&&(o[r]=n);let s=new Uint8Array(r),c=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e),l=r,u=!1;if(r>=55296&&r<=56319&&e+1<n){let n=t.charCodeAt(e+1);n>=56320&&n<=57343&&(l=(r-55296<<10)+65536|n-56320,u=!0)}i&&(a[e]=c,u&&(a[e+1]=c),l<=127?o[c+0]=e:l<=2047?(o[c+0]=e,o[c+1]=e):l<=65535?(o[c+0]=e,o[c+1]=e,o[c+2]=e):(o[c+0]=e,o[c+1]=e,o[c+2]=e,o[c+3]=e)),l<=127?s[c++]=l:l<=2047?(s[c++]=192|(l&1984)>>>6,s[c++]=128|(l&63)>>>0):l<=65535?(s[c++]=224|(l&61440)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0):(s[c++]=240|(l&1835008)>>>18,s[c++]=128|(l&258048)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0),u&&e++}this.utf16Length=n,this.utf8Length=r,this.utf16Value=t,this.utf8Value=s,this.utf16OffsetToUtf8=a,this.utf8OffsetToUtf16=o}static _utf8ByteLength(e){let t=0;for(let n=0,r=e.length;n<r;n++){let i=e.charCodeAt(n),a=i,o=!1;if(i>=55296&&i<=56319&&n+1<r){let t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(a=(i-55296<<10)+65536|t-56320,o=!0)}t+=a<=127?1:a<=2047?2:a<=65535?3:4,o&&n++}return t}createString(e){let t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}},Y3=class e{constructor(t){if(K3(this,`id`,++e.LAST_ID),K3(this,`_onigBinding`),K3(this,`content`),K3(this,`utf16Length`),K3(this,`utf8Length`),K3(this,`utf16OffsetToUtf8`),K3(this,`utf8OffsetToUtf16`),K3(this,`ptr`),!q3)throw new G3(`Must invoke loadWasm first.`);this._onigBinding=q3,this.content=t;let n=new J3(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=q3.omalloc(1e4),e._sharedPtrInUse=!0,q3.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(q3)}convertUtf8OffsetToUtf16(e){return this.utf8OffsetToUtf16?e<0?0:e>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[e]:e}convertUtf16OffsetToUtf8(e){return this.utf16OffsetToUtf8?e<0?0:e>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[e]:e}dispose(){this.ptr===e._sharedPtr?e._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};K3(Y3,`LAST_ID`,0),K3(Y3,`_sharedPtr`,0),K3(Y3,`_sharedPtrInUse`,!1);var X3=Y3,nnt=class{constructor(e){if(K3(this,`_onigBinding`),K3(this,`_ptr`),!q3)throw new G3(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new J3(e[r]);t[r]=i.createString(q3),n[r]=i.utf8Length}let r=q3.omalloc(4*e.length);q3.HEAPU32.set(t,r/4);let i=q3.omalloc(4*e.length);q3.HEAPU32.set(n,i/4);let a=q3.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)q3.ofree(t[n]);q3.ofree(i),q3.ofree(r),a===0&&tnt(q3),this._onigBinding=q3,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,n){let r=0;if(typeof n==`number`&&(r=n),typeof e==`string`){e=new X3(e);let n=this._findNextMatchSync(e,t,!1,r);return e.dispose(),n}return this._findNextMatchSync(e,t,!1,r)}_findNextMatchSync(e,t,n,r){let i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),r);if(a===0)return null;let o=i.HEAPU32,s=a/4,c=o[s++],l=o[s++],u=[];for(let t=0;t<l;t++){let n=e.convertUtf8OffsetToUtf16(o[s++]),r=e.convertUtf8OffsetToUtf16(o[s++]);u[t]={start:n,end:r,length:r-n}}return{index:c,captureIndices:u}}};function rnt(e){return typeof e.instantiator==`function`}function int(e){return typeof e.default==`function`}function ant(e){return e.data!==void 0}function ont(e){return typeof Response<`u`&&e instanceof Response}function snt(e){return typeof ArrayBuffer<`u`&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<`u`&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||typeof Uint32Array<`u`&&e instanceof Uint32Array}var Z3;function Q3(e){if(Z3)return Z3;async function t(){q3=await Qtt(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),rnt(n)?n=await n.instantiator(t):int(n)?n=await n.default(t):(ant(n)&&(n=n.data),ont(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await cnt(n)(t):await lnt(n)(t):snt(n)||n instanceof WebAssembly.Module?n=await $3(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await $3(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return Z3=t(),Z3}function $3(e){return t=>WebAssembly.instantiate(e,t)}function cnt(e){return t=>WebAssembly.instantiateStreaming(e,t)}function lnt(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var e6;function unt(e){e6=e}function dnt(){return e6}async function t6(e){return e&&await Q3(e),{createScanner(e){return new nnt(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new X3(e)}}}var n6=Utt({});Wtt(n6,Jtt);var r6=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function fnt(e){return i6(e)}function i6(e){return Array.isArray(e)?pnt(e):e instanceof RegExp?e:typeof e==`object`?mnt(e):e}function pnt(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=i6(e[n]);return t}function mnt(e){let t={};for(let n in e)t[n]=i6(e[n]);return t}function a6(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function o6(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?o6(e.substring(0,e.length-1)):e.substr(~t+1)}var s6=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,c6=class{static hasCaptures(e){return e!==null&&(s6.lastIndex=0,s6.test(e))}static replaceCaptures(e,t,n){return e.replace(s6,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function l6(e,t){return e<t?-1:+(e>t)}function u6(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=l6(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function d6(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function f6(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var p6=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},m6=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(_nt(e),t)}static createFromParsedTheme(e,t){return ynt(e,t)}_cachedMatchRoot=new p6(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>hnt(e.parent,t.parentScopes));return n?new g6(n.fontStyle,n.foreground,n.background):null}},h6=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function hnt(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!gnt(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function gnt(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var g6=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function _nt(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&d6(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&d6(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new vnt(l,u,e,o,s,c)}}return n}var vnt=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},_6=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(_6||{});function ynt(e,t){e.sort((e,t)=>{let n=l6(e.scope,t.scope);return n!==0||(n=u6(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new bnt(t),o=new g6(n,a.getId(r),a.getId(i)),s=new Snt(new v6(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new m6(a,o,s)}var bnt=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},xnt=Object.freeze([]),v6=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||xnt,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},Snt=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),v6.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null){this._mainRule.acceptOverwrite(e,n,r,i);return}for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(u6(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new v6(e,t,n,r,i))}},y6=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=wnt(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c<<0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function Cnt(e){return e}function wnt(e){return e}function b6(e,t){let n=[],r=Tnt(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(x6(i)){let e=[];do e.push(i),i=r.next();while(x6(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function x6(e){return!!e&&!!e.match(/[\w\.:]+/)}function Tnt(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function S6(e){typeof e.dispose==`function`&&e.dispose()}var C6=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},Ent=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},Dnt=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},Ont=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new C6(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new Dnt;for(let n of e)knt(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof C6){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function knt(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof C6?T6({baseGrammar:a,selfGrammar:i},r):w6(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new C6(e))}function w6(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];E6([r],t,n)}}function T6(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&E6(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&E6(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function E6(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?a6({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&E6(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=D6(i);switch(a.kind){case 0:T6({...t,selfGrammar:t.baseGrammar},n);break;case 1:T6(t,n);break;case 2:w6(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?w6(a.ruleName,i,n):T6(i,n)}else a.kind===4?n.add(new Ent(a.scopeName,a.ruleName)):n.add(new C6(a.scopeName))}}}var Ant=class{kind=0},jnt=class{kind=1},Mnt=class{constructor(e){this.ruleName=e}kind=2},Nnt=class{constructor(e){this.scopeName=e}kind=3},Pnt=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function D6(e){if(e===`$base`)return new Ant;if(e===`$self`)return new jnt;let t=e.indexOf(`#`);return t===-1?new Nnt(e):t===0?new Mnt(e.substring(1)):new Pnt(e.substring(0,t),e.substring(t+1))}var Fnt=/\\(\d+)/,O6=/\\(\d+)/g,Int=-1,k6=-2;function A6(e){return e}function j6(e){return e}var M6=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=c6.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=c6.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${o6(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:c6.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:c6.replaceCaptures(this._contentName,e,t)}},Lnt=class extends M6{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},Rnt=class extends M6{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new L6(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new R6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},N6=class extends M6{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new R6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},P6=class extends M6{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new L6(i,this.id),this.beginCaptures=a,this._end=new L6(o||`￿`,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new R6;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},F6=class extends M6{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new L6(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new L6(o,k6),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new R6;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new R6,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},I6=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new Lnt(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new Rnt(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=a6({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new N6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new F6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new P6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=D6(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l)if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof N6||e instanceof P6||e instanceof F6)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},L6=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&Fnt.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return O6.lastIndex=0,this.source.replace(O6,(e,t)=>f6(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=`￿`,t[i+1]=`￿`,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=`￿`,t[i+1]=`G`,n[i+1]=`￿`,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},R6=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new z6(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new z6(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},z6=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
1042
- `)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},B6=class{constructor(e,t){this.languageId=e,this.tokenType=t}},znt=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new B6(e,8),this._embeddedLanguagesMatcher=new Bnt(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new B6(0,0);_getBasicScopeAttributes=new p6(e=>new B6(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},Bnt=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>f6(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var V6=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function H6(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Vnt(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new V6(i,!0);f()}return new V6(i,!1);function f(){let o=Hnt(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===Int){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),W6(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof P6){let r=o;W6(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof F6){let r=o;W6(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(W6(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function Vnt(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof F6&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Gnt(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==k6){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),W6(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function Hnt(e,t,n,r,i,a){let o=Unt(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Wnt(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function Unt(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=U6(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Wnt(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=U6(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function U6(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Gnt(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function W6(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a.length,o.length),l=[],u=o[0].end;for(let t=0;t<c;t++){let c=a[t];if(c===null)continue;let d=o[t];if(d.length===0)continue;if(d.start>u)break;for(;l.length>0&&l[l.length-1].endPos<=d.start;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop();if(l.length>0?i.produceFromScopes(l[l.length-1].scopes,d.start):i.produce(r,d.start),c.retokenizeCapturedWithRuleId){let t=c.getName(s,o),a=r.contentNameScopesList.pushAttributed(t,e),l=c.getContentName(s,o),u=a.pushAttributed(l,e),f=r.push(c.retokenizeCapturedWithRuleId,d.start,-1,!1,null,a,u),p=e.createOnigString(s.substring(0,d.end));H6(e,p,n&&d.start===0,d.start,f,i,!1,0),S6(p);continue}let f=c.getName(s,o);if(f!==null){let t=(l.length>0?l[l.length-1].scopes:r.contentNameScopesList).pushAttributed(f,e);l.push(new Knt(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var Knt=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function qnt(e,t,n,r,i,a,o,s){return new Ynt(e,t,n,r,i,a,o,s)}function G6(e,t,n,r,i){let a=b6(t,K6),o=I6.getCompiledRuleId(n,r,i.repository);for(let n of a)e.push({debugSelector:t,matcher:n.matcher,ruleId:o,grammar:i,priority:n.priority})}function K6(e,t){if(t.length<e.length)return!1;let n=0;return e.every(e=>{for(let r=n;r<t.length;r++)if(Jnt(t[r],e))return n=r+1,!0;return!1})}function Jnt(e,t){if(!e)return!1;if(e===t)return!0;let n=t.length;return e.length>n&&e.substr(0,n)===t&&e[n]===`.`}var Ynt=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new znt(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=q6(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=b6(e,K6);for(let n of t)this._tokenTypeMatchers.push({matcher:n.matcher,type:i[e]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:e=>e===this._rootScopeName?this._grammar:this.getExternalGrammar(e),injections:e=>this._grammarRepository.injections(e)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let e=r.injections;if(e)for(let n in e)G6(t,n,e[n],this,r);let i=this._grammarRepository.injections(n);i&&i.forEach(e=>{let n=this.getExternalGrammar(e);if(n){let e=n.injectionSelector;e&&G6(t,e,n,this,n)}})}return t.sort((e,t)=>e.priority-t.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(A6(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[j6(e)]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=q6(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=I6.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===Y6.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=y6.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?J6.createRootAndLookUpScopeName(a,r,this):J6.createRoot(`unknown`,r),t=new Y6(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
1043
- `;let a=this.createOnigString(e),o=a.content.length,s=new Znt(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=H6(this,a,i,0,t,s,!0,r);return S6(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function q6(e,t){return e=fnt(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var J6=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=h6.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new h6(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new h6(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(!0)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),y6.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},Y6=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?J6.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:j6(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=J6.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,A6(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,J6.fromExtension(r,n.contentNameScopesList))}},Xnt=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):b6(e,K6).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>b6(e,K6).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Znt=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=y6.set(n,0,Cnt(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=y6.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},Qnt=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,qnt(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},$nt=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new Qnt(m6.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(m6.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new Xnt(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new Ont(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},X6=Y6.NULL;function Z6(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function Q6(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function ert(e){return Array.isArray(e)?e:[e]}async function $6(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function e8(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function t8(e){return e===`ansi`||e8(e)}function n8(e){return e===`none`}function r8(e){return n8(e)}function i8(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(/(\r?\n)/g),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var a8={light:`#333333`,dark:`#bbbbbb`},o8={light:`#fffffe`,dark:`#1e1e1e`},s8=`__shiki_resolved`;function c8(e){if(e?.[s8])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?a8.light:a8.dark,n||=t.type===`light`?o8.light:o8.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,s8,{enumerable:!1,writable:!1,value:!0}),t}async function l8(e){return Array.from(new Set((await Promise.all(e.filter(e=>!t8(e)).map(async e=>await $6(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function u8(e){return(await Promise.all(e.map(async e=>r8(e)?null:c8(await $6(e))))).filter(e=>!!e)}function d8(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new r6(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var trt=class extends $nt{_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=c8(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=m6.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=d8(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=Array.from(this._langGraph.entries()),n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new r6(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},nrt=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},f8=0;function rrt(e){f8+=1,e.warnings!==!1&&f8>=10&&f8%10==0&&console.warn(`[Shiki] ${f8} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new r6("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(c8),i=new trt(new nrt(e.engine,n),r,n,e.langAlias),a;function o(t){return d8(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new r6(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new r6(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await l8(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await u8(e))}function g(){if(t)throw new r6(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--f8)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function irt(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([u8(e.themes||[]),l8(e.langs||[]),e.engine]);return rrt({...e,themes:t,langs:n,engine:r})}var p8=new WeakMap;function m8(e,t){p8.set(e,t)}function h8(e){return p8.get(e)}var g8=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(ert(n).map(e=>[e,X6])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return art(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function art(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function ort(e,t){if(!(e instanceof g8))throw new r6(`Invalid grammar state`);return e.getInternalStack(t)}function _8(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(e8(e.resolveLangAlias(n.lang||`text`))||n8(r))return i8(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new r6(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new r6(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return crt(t,o,i,a,n)}function srt(...e){if(e.length===2)return h8(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(e8(i)||n8(a))throw new r6(`Plain language does not have grammar state`);if(i===`ansi`)throw new r6(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new g8(v8(n,c,o,s,r).stateStack,c.name,o.name)}function crt(e,t,n,r,i){let a=v8(e,t,n,r,i),o=new g8(a.stateStack,t.name,n.name);return m8(a.tokens,o),a.tokens}function v8(e,t,n,r,i){let a=Z6(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=i8(e),l=i.grammarState?ort(i.grammarState,n.name)??X6:i.grammarContextCode==null?X6:v8(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,u=[],d=[];for(let e=0,f=c.length;e<f;e++){let[f,p]=c[e];if(f===``){u=[],d.push([]);continue}if(o>0&&f.length>=o){u=[],d.push([{content:f,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;i.includeExplanation&&(m=t.tokenizeLine(f,l,s),h=m.tokens,g=0);let _=t.tokenizeLine2(f,l,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:f.length;if(t===o)continue;let s=_.tokens[2*e+1],c=Q6(r[y6.getForeground(s)],a),l=y6.getFontStyle(s),d={content:f.substring(t,o),offset:p+t,color:c,fontStyle:l};if(i.includeExplanation){let e=[];if(i.includeExplanation!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(/,/).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(/ /))})}d.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=f.substring(t.startIndex,t.endIndex);r+=n.length,d.explanation.push({content:n,scopes:i.includeExplanation===`scopeName`?lrt(t.scopes):urt(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function lrt(e){return e.map(e=>({scopeName:e}))}function urt(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:frt(e,i,t.slice(0,r))}}return n}function y8(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function drt(e,t,n){if(!y8(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)y8(e[r],n[i])&&--r,--i;return r===-1}function frt(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(drt(e,t,n)){r.push(a);break}return r}function b8(e,t,n,r=_8){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:h8(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=prt(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new g8(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&m8(s,c),s}function prt(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}function x8(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function mrt(e){let t=i8(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t[t.length-1].length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}function hrt(e,t,n){let r=new Set;for(let t of e.matchAll(/:?lang=["']([^"']+)["']/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/\\begin\{([\w-]+)\}/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let e=t[1].toLowerCase().trim(),n=e.includes(`/`)?e.split(`/`).pop():e;n&&r.add(n)}if(!n)return Array.from(r);let i=n.getBundledLanguages();return Array.from(r).filter(e=>e&&i[e])}var S8=`light-dark()`,grt=[`color`,`background-color`];function _rt(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function vrt(e,t){let n=Array.from(t instanceof Set?t:new Set(t)).sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=n.filter(t=>e.offset<t&&t<e.offset+e.content.length).map(t=>t-e.offset).sort((e,t)=>e-t);return t.length?_rt(e,t):e})):e}function yrt(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>C8(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&grt.includes(a))if(r===S8&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new r6('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');c[a]=`light-dark(${o[e][a]||`inherit`}, ${o[r][a]||`inherit`})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s;else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function C8(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&_6.Italic&&(t[`font-style`]=`italic`),e.fontStyle&_6.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&_6.Underline&&n.push(`underline`),e.fontStyle&_6.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function w8(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function brt(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=mrt(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new r6(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new r6(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new r6(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));xrt(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return vrt(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=Array.from(e.children).filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new r6(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=T8(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new r6(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new r6(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&x8(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function xrt(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new r6(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new r6(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function T8(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(T8).join(``):``}var Srt=[brt()];function E8(e){let t=Crt(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...Srt]}function Crt(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var D8=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],O8={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function wrt(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function k8(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function Trt(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:`resetAll`});else if(r<=9)O8[r]&&t.push({type:`setDecoration`,value:O8[r]});else if(r<=29){let e=O8[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:D8[r-30]}});else if(r===38){let n=k8(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:D8[r-40]}});else if(r===48){let n=k8(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:D8[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:D8[r-100+8]}})}return t}function Ert(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=wrt(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=Trt(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var Drt={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function Ort(e=Drt){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<D8.length;e++)r.push(t(D8[e]));let e=[0,95,135,175,215,255];for(let t=0;t<6;t++)for(let i=0;i<6;i++)for(let a=0;a<6;a++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var krt={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function Art(e,t,n){let r=Z6(e,n),i=i8(t),a=Ort(Object.fromEntries(D8.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||krt[t]]}))),o=Ert();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=Q6(i,r),o=Q6(o,r),n.decorations.has(`dim`)&&(i=jrt(i));let s=_6.None;return n.decorations.has(`bold`)&&(s|=_6.Bold),n.decorations.has(`italic`)&&(s|=_6.Italic),n.decorations.has(`underline`)&&(s|=_6.Underline),n.decorations.has(`strikethrough`)&&(s|=_6.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function jrt(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function A8(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!e8(r)&&!n8(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return Art(r,t,n)}return _8(e,t,n)}function j8(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new r6("`themes` option must not be empty");let p=b8(e,t,n,A8);if(c=h8(p),l&&S8!==l&&!f.find(e=>e.color===l))throw new r6(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>yrt(e,h,u,l,d))),c&&m8(a,c);let g=f.map(e=>Z6(e.theme,n));i=M8(f,m,g,u,l,`fg`,d),r=M8(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=Z6(n.theme,n);a=A8(e,t,n);let l=e.getTheme(n.theme);r=Q6(l.bg,s),i=Q6(l.fg,s),o=l.name,c=h8(a)}else throw new r6("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function M8(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=Q6(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===S8&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new r6('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${Q6(t[r][a],n[r])||`inherit`}, ${Q6(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function N8(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>N8(e,t,n),codeToTokens:(t,n)=>j8(e,t,n)}){let i=t;for(let e of E8(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=j8(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=Nrt(a):d===`never`&&(a=Prt(a)),f&&(a=Frt(a));let p={...r,get source(){return i}};for(let e of E8(n))a=e.tokens?.call(p,a)||a;return Mrt(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function Mrt(e,t,n,r=h8(e)){let i=E8(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:x8,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
1044
- `}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=w8(a.htmlStyle||C8(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&m8(m,r),m}function Nrt(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&_6.Underline||i.fontStyle&_6.Strikethrough));o&&i.content.match(/^\s+$/)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function Prt(e){return e.map(e=>e.flatMap(e=>{if(e.content.match(/^\s+$/))return e;let t=e.content.match(/^(\s*)(.*?)(\s*)$/);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function Frt(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t[t.length-1],r=w8(e.htmlStyle||C8(e)),i=w8(n.htmlStyle||C8(n)),a=e.fontStyle&&(e.fontStyle&_6.Underline||e.fontStyle&_6.Strikethrough),o=n.fontStyle&&(n.fontStyle&_6.Underline||n.fontStyle&_6.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var Irt=C3;function Lrt(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>N8(e,t,n),codeToTokens:(t,n)=>j8(e,t,n)},i=Irt(N8(e,t,n,r));for(let e of E8(n))i=e.postprocess?.call(r,i,n)||i;return i}async function Rrt(e){let t=await irt(e);return{getLastGrammarState:(...e)=>srt(t,...e),codeToTokensBase:(e,n)=>A8(t,e,n),codeToTokensWithThemes:(e,n)=>b8(t,e,n),codeToTokens:(e,n)=>j8(t,e,n),codeToHast:(e,n)=>N8(t,e,n),codeToHtml:(e,n)=>Lrt(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function zrt(e){let t=e.langs,n=e.themes,r=e.engine;async function i(e){function i(n){if(typeof n==`string`){if(n=e.langAlias?.[n]||n,t8(n))return[];let r=t[n];if(!r)throw new r6(`Language \`${n}\` is not included in this bundle. You may want to load it from external source.`);return r}return n}function a(e){if(r8(e))return`none`;if(typeof e==`string`){let t=n[e];if(!t)throw new r6(`Theme \`${e}\` is not included in this bundle. You may want to load it from external source.`);return t}return e}let o=(e.themes??[]).map(e=>a(e)),s=(e.langs??[]).map(e=>i(e)),c=await Rrt({engine:e.engine??r(),...e,themes:o,langs:s});return{...c,loadLanguage(...e){return c.loadLanguage(...e.map(i))},loadTheme(...e){return c.loadTheme(...e.map(a))},getBundledLanguages(){return t},getBundledThemes(){return n}}}return i}function Brt(e){let t;async function n(n={}){if(t){let e=await t;return await Promise.all([e.loadTheme(...n.themes||[]),e.loadLanguage(...n.langs||[])]),e}{t=e({...n,themes:[],langs:[]});let r=await t;return await Promise.all([r.loadTheme(...n.themes||[]),r.loadLanguage(...n.langs||[])]),r}}return n}function Vrt(e,t){let n=Brt(e);async function r(e,r){let i=await n({langs:[r.lang],themes:`theme`in r?[r.theme]:Object.values(r.themes)}),a=await t?.guessEmbeddedLanguages?.(e,r.lang,i);return a&&await i.loadLanguage(...a),i}return{getSingletonHighlighter(e){return n(e)},async codeToHtml(e,t){return(await r(e,t)).codeToHtml(e,t)},async codeToHast(e,t){return(await r(e,t)).codeToHast(e,t)},async codeToTokens(e,t){return(await r(e,t)).codeToTokens(e,t)},async codeToTokensBase(e,t){return(await r(e,t)).codeToTokensBase(e,t)},async codeToTokensWithThemes(e,t){return(await r(e,t)).codeToTokensWithThemes(e,t)},async getLastGrammarState(e,t){return(await n({langs:[t.lang],themes:[t.theme]})).getLastGrammarState(e,t)}}}var P8=zrt({langs:W3,themes:qtt,engine:()=>(0,n6.createOnigurumaEngine)(N(()=>import(`./wasm-BnjxR4X6.js`),[]))}),{codeToHtml:Hrt,codeToHast:Urt,codeToTokens:Wrt,codeToTokensBase:Grt,codeToTokensWithThemes:Krt,getSingletonHighlighter:qrt,getLastGrammarState:Jrt}=Vrt(P8,{guessEmbeddedLanguages:hrt}),F8=4294967295,Yrt=class{regexps;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}})}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=[];function a(e,t,n=0){return{index:e,captureIndices:t.indices.map(e=>e==null?{start:F8,end:F8,length:0}:{start:e[0]+n,end:e[1]+n,length:e[1]-e[0]})}}for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{n.lastIndex=t;let o=n.exec(r);if(!o)continue;if(o.index===t)return a(e,o,0);i.push([e,o,0])}catch(e){if(this.options.forgiving)continue;throw e}}if(i.length){let e=Math.min(...i.map(e=>e[1].index));for(let[t,n,r]of i)if(n.index===e)return a(t,n,r)}return null}};function I8(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function Xrt(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var L8=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),R8=String.raw;function z8(e,t){if(e==null)throw Error(t??`Value expected`);return e}var B8=R8`\[\^?`,V8=`c.? | C(?:-.?)?|${R8`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${R8`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${R8`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${R8`o\{[^\}]*\}?`}|${R8`\d{1,3}`}`,H8=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,U8=new RegExp(R8`
1041
+ \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function stt(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=Q4);let l=ctt(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!ttt(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!g3(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function ctt(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=ltt(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function ltt(e,t,n){let r=X4(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=o3(r.attribute,Object.assign({},e.settings.characterReferences,{subset:b3.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?c3:l3)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=o3(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:b3.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&s3(n,o)>s3(n,e.alternative)&&(o=e.alternative),s=o+o3(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?b3.single:b3.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var utt=[`<`,`&`];function x3(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:o3(e.value,Object.assign({},r.settings.characterReferences,{subset:utt}))}function dtt(e,t,n,r){return r.settings.allowDangerousHtml?e.value:x3(e,t,n,r)}function ftt(e,t,n,r){return r.all(e)}var ptt=e3(`type`,{invalid:mtt,unknown:htt,handlers:{comment:Iet,doctype:Let,element:stt,raw:dtt,root:ftt,text:x3}});function mtt(e){throw Error("Expected node, not `"+e+"`")}function htt(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var gtt={},_tt={},vtt=[];function S3(e,t){let n=t||gtt,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:ytt,all:btt,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||E4,characterReferences:n.characterReferences||_tt,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?Q4:Z4,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function ytt(e,t,n){return ptt(e,t,n,this)}function btt(e){let t=[],n=e&&e.children||vtt,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var xtt=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;selectedRangeHighlightSide;selectedRangeLineNumberOnly=!1;editorActiveLine=null;editorActiveLineSide;editorLineNumberOnly=!1;proposedSelectedRange;renderedSelectedLinesState;renderedEditorActiveLineState;selectionAnchor;pointerSession={mode:`idle`};constructor(e,t){this.mode=e,this.options=t}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener(`click`,this.handlePointerClick),this.pre?.removeEventListener(`pointerdown`,this.handlePointerDown),this.pre?.removeEventListener(`pointermove`,this.handlePointerMove),this.pre?.removeEventListener(`pointerleave`,this.handlePointerLeave),this.pre?.removeAttribute(`data-interactive-lines`),this.pre?.removeAttribute(`data-interactive-line-numbers`),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),G2(this.renderSelection),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1,this.setSelectionDirty()}setup(e){this.setSelectionDirty();let{usesCustomGutterUtility:t=!1,enableGutterUtility:n=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),n?this.ensureGutterUtilityNode(t):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode===`gutterSelecting`&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectedLinesState=void 0,this.renderedEditorActiveLineState=void 0}isSelectionDirty(){return this.renderedSelectedLinesState===void 0||this.renderedEditorActiveLineState===void 0}setSelection(e,t){let n=!(e===this.selectedRange||X2(e??void 0,this.selectedRange??void 0)),r=t?.lineNumberOnly??!1,i=t?.activeLineSide!==this.selectedRangeHighlightSide||r!==this.selectedRangeLineNumberOnly;!this.isSelectionDirty()&&!n&&!i||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.selectedRangeHighlightSide=t?.activeLineSide,this.selectedRangeLineNumberOnly=r,this.renderSelection(),this.placeUtility(),n&&t?.notify!==!1&&this.notifySelectionCommitted(e))}setEditorActiveLine(e,{lineNumberOnly:t=!1,side:n}={}){let r=e!==this.editorActiveLine,i=n!==this.editorActiveLineSide||t!==this.editorLineNumberOnly;!this.isSelectionDirty()&&!r&&!i||(this.editorActiveLine=e,this.editorActiveLineSide=n,this.editorLineNumberOnly=t,this.renderSelection())}getSelection(){return this.selectedRange}getHoveredLine=()=>{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode===`diff`&&e.type===`diff-line`)return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode===`file`&&e.type===`line`)return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:r,onTokenClick:i,onMergeConflictActionClick:a}=this.options;(t!=null||n!=null||r!=null||a!=null||i!=null)&&(this.options.onGutterUtilityClick!=null&&T4(e.composedPath())||(M3(this.options.__debugPointerEvents,`click`,`FileDiff.DEBUG.handlePointerClick:`,e),this.handlePointerEvent({eventType:`click`,event:e})))};handlePointerMove=e=>{if(e.pointerType!==`mouse`)return;let{lineHoverHighlight:t=`disabled`,onLineEnter:n,onLineLeave:r,onTokenEnter:i,onTokenLeave:a,enableGutterUtility:o=!1}=this.options;t===`disabled`&&!o&&n==null&&r==null&&i==null&&a==null||(M3(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if(M3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){M3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token`);return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:t}){let{__debugPointerEvents:n}=this.options,r=t.composedPath();M3(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);M3(n,e,`FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:`,i);let{onLineClick:a,onLineNumberClick:o,onLineEnter:s,onLineLeave:c,onTokenClick:l,onTokenEnter:u,onTokenLeave:d,onHunkExpand:f,onMergeConflictActionClick:p}=this.options;switch(e){case`move`:{let e=T3(i)&&this.hoveredLine?.lineElement===i.lineElement;w3(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),w3(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),T3(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(Ttt(i)&&p!=null){p(i);break}if(wtt(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!T3(i))break;w3(i)&&l!=null&&l(this.toTokenEventBaseProps(i),t);let e=this.toEventBaseProps(i);o!=null&&i.numberColumn?o({...e,event:t}):a?.({...e,event:t});break}}}syncPointerListeners(e){let{__debugPointerEvents:t,lineHoverHighlight:n=`disabled`,onLineClick:r,onLineNumberClick:i,onLineEnter:a,onLineLeave:o,onTokenClick:s,onTokenEnter:c,onTokenLeave:l,onHunkExpand:u,onMergeConflictActionClick:d,enableGutterUtility:f=!1,enableLineSelection:p=!1,onGutterUtilityClick:m}=this.options,h=m!=null,g=n!==`disabled`||r!=null||i!=null||a!=null||o!=null||s!=null||c!=null||l!=null||u!=null||d!=null||f||p||h;g&&!this.hasPointerListeners?(e.addEventListener(`click`,this.handlePointerClick),e.addEventListener(`pointerdown`,this.handlePointerDown),e.addEventListener(`pointermove`,this.handlePointerMove),e.addEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!0,M3(t,`click`,`FileDiff.DEBUG.attachEventListeners: Attaching click events for:`,(()=>{let e=[];return(t===`both`||t===`click`)&&(r!=null&&e.push(`onLineClick`),i!=null&&e.push(`onLineNumberClick`),u!=null&&e.push(`expandable hunk separators`),d!=null&&e.push(`merge conflict actions`)),e})()),M3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),M3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event`)):!g&&this.hasPointerListeners&&(e.removeEventListener(`click`,this.handlePointerClick),e.removeEventListener(`pointerdown`,this.handlePointerDown),e.removeEventListener(`pointermove`,this.handlePointerMove),e.removeEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!1);let _=this.pointerSession.mode===`selecting`||this.pointerSession.mode===`pendingSingleLineUnselect`,v=this.pointerSession.mode===`gutterSelecting`;(!p&&_||!h&&v)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,r=e!=null,i=t!=null||n;r&&!this.interactiveLinesAttr?(this.pre.setAttribute(`data-interactive-lines`,``),this.interactiveLinesAttr=!0):!r&&this.interactiveLinesAttr&&(this.pre.removeAttribute(`data-interactive-lines`),this.interactiveLinesAttr=!1),i&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute(`data-interactive-line-numbers`,``),this.interactiveLineNumbersAttr=!0):!i&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute(`data-interactive-line-numbers`),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType===`mouse`&&e.button!==0||this.pre==null||this.pointerSession.mode!==`idle`)return;let t=e.composedPath();T4(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!==`mouse`&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:`event-path`,requireNumberColumn:!0});if(n==null)return;let{pre:r}=this;if(r==null)return;let{lineNumber:i,eventSide:a,lineIndex:o}=n;if(e.shiftKey&&this.selectedRange!=null){let t=this.getIndexesFromSelection(this.selectedRange,r.getAttribute(`data-diff-type`)===`split`);if(t==null)return;let n=t.start<=t.end?o>=t.start:o<=t.end;this.selectionAnchor={lineNumber:n?this.selectedRange.start:this.selectedRange.end,side:n?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===i&&this.selectedRange?.end===i){let t={lineNumber:i,side:a};this.selectionAnchor=t,this.pointerSession={mode:`pendingSingleLineUnselect`,pointerId:e.pointerId,anchor:t,pending:t},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:i,side:a},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{onGutterUtilityClick:t}=this.options;if(t==null)return;let n=this.currentSelectionEnds(),r=n?.bottom??this.resolveSelectionPoint(e,{source:`event-path`,excludeUtility:!1}),i=n?.top??r;r!=null&&i!=null&&(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:`gutterSelecting`,pointerId:e.pointerId,anchor:i,current:r},this.selectionAnchor={lineNumber:i.lineNumber,side:i.side},this.updateSelection(r.lineNumber,r.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionPoint(e,{source:`coordinates-first`});if(t==null)return;this.pointerSession.current=t,this.updateSelection(t.lineNumber,t.side);return}case`selecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case`pendingSingleLineUnselect`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;let n={lineNumber:t.lineNumber,side:t.eventSide};if(set(this.pointerSession.pending,n))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:`selecting`,pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{let{onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{let{pointerSession:n}=this;if(e.pointerId!==n.pointerId)return;e.preventDefault();let r=this.resolveSelectionPoint(e,{source:`coordinates-first`});r!=null&&(n.current=r,this.updateSelection(r.lineNumber,r.side));let i=this.buildSelectedLineRange(n.anchor,n.current);t?.({...i}),this.selectionAnchor=void 0,this.notifySelectionEnd(i),this.notifySelectionCommitted(i),this.clearProposedSelection(),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case`pendingSingleLineUnselect`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection();return;case`selecting`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:case`selecting`:case`pendingSingleLineUnselect`:if(`pointerId`in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute(`data-hovered`),this.hoveredLine.numberElement.removeAttribute(`data-hovered`),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t=`disabled`}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!==`disabled`&&((t===`both`||t===`line`)&&this.hoveredLine.lineElement.setAttribute(`data-hovered`,``),(t===`both`||t===`number`)&&this.hoveredLine.numberElement.setAttribute(`data-hovered`,``))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer??(this.gutterUtilityContainer=document.createElement(`div`),this.gutterUtilityContainer.setAttribute(`data-gutter-utility-slot`,``)),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot??(this.gutterUtilitySlot=document.createElement(`slot`),this.gutterUtilitySlot.name=`gutter-utility-slot`),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let e=document.createElement(`div`);e.innerHTML=S3(oet());let t=e.firstElementChild;if(!(t instanceof HTMLButtonElement))throw Error(`InteractionManager.ensureGutterUtilityNode: Node element should be a button`);t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);C3(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},r=this.selectionPointRowIndex(t),i=this.selectionPointRowIndex(n);if(r!=null&&i!=null)return r>i?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode===`diff`?`${t[0]},${t[1]}`:`${t[0]}`,r=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let t of r){if(!(t instanceof HTMLElement))continue;let n=this.resolvePointerTarget(D3(t));if(C3(n)&&(this.mode!==`diff`||e.side==null||n.side===e.side))return n}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||=(document.addEventListener(`pointermove`,this.handleDocumentPointerMove),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerCancel),!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&=(document.removeEventListener(`pointermove`,this.handleDocumentPointerMove),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerCancel),!1)}clearPointerSession(){this.pointerSession={mode:`idle`}}clearPendingSingleLineState(){this.pointerSession.mode===`pendingSingleLineUnselect`&&(this.pointerSession={mode:`idle`})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(C3(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode===`diff`?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionInfoFromPath(n,t.requireNumberColumn)}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(C3(t))return{lineNumber:t.lineNumber,side:this.mode===`diff`?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionPointFromPath(n)}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case`event-path`:return this.pathFromEventPath(e.composedPath(),n);case`coordinates-first`:{let t=this.pathFromCoordinates(e,n);return t===void 0?this.pathFromEventPath(e.composedPath(),n):t??void 0}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&T4(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=D3(e);if(t&&T4(n))return;let r=Dtt(e);return r==null?this.pathFromAnnotationSlot(e):D3(r)}pathFromAnnotationSlot(e){let t=ktt(Ott(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:D3(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=O3(t)?t:O3(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n==null?[e-1,e-1]:n(e,t)}getCurrentSelectionRange(){return this.proposedSelectedRange===void 0?this.selectedRange:this.proposedSelectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let r=this.getCurrentSelectionRange(),i;if(e==null)i=null;else{let n=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;i=this.buildSelectionRange(r,e,n,t)}X2(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,W2(this.renderSelection)),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),r=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&r!=null?{start:t?n[1]:n[0],end:t?r[1]:r[0]}:void 0}getSelectionRenderState(){return{selectedLines:{range:this.selectedRange,highlightSide:this.selectedRangeHighlightSide,lineNumberOnly:this.selectedRangeLineNumberOnly},editorActiveLine:{range:this.editorActiveLine==null?null:{start:this.editorActiveLine,end:this.editorActiveLine,side:this.editorActiveLineSide},highlightSide:this.editorActiveLineSide,lineNumberOnly:this.editorLineNumberOnly}}}resolveLineRenderRange(e,t,n){if(e.range==null)return;let r=this.getIndexesFromSelection(e.range,t);if(r==null)throw console.error({rowRange:r,range:e.range}),Error(`InteractionManager.renderSelection: No valid ${n} rowRange`);return r}getLineRenderColumns(e,t,n,r){if(this.pre==null||t==null&&r==null)return[];let{children:i}=this.pre;if(i.length>2)throw console.error(i),Error(`InteractionManager.renderSelection: Somehow there are more than 2 code elements...`);let a=[];for(let o of i){let i=o.hasAttribute(`data-deletions`)?`deletions`:o.hasAttribute(`data-additions`)?`additions`:void 0,s=e!=null&&t!=null&&(e.highlightSide==null||i==null||e.highlightSide===i),c=n!=null&&r!=null&&(n.highlightSide==null||i==null||n.highlightSide===i);if(!s&&!c)continue;let[l,u]=o.children;if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))throw Error(`InteractionManager.renderSelection: missing gutter or content element`);if(u.children.length!==l.children.length)throw Error(`InteractionManager.renderSelection: gutter and content children dont match, something is wrong`);a.push({content:u,gutter:l,renderEditorActiveLine:c,renderSelectedLines:s})}return a}renderSelection=()=>{G2(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!k3(this.renderedSelectedLinesState,n),i=!k3(this.renderedEditorActiveLineState,t);if(!r&&!i)return;r&&(this.renderedSelectedLinesState=void 0),i&&(this.renderedEditorActiveLineState=void 0);let a=this.pre.getAttribute(`data-diff-type`)===`split`,o=r?this.resolveLineRenderRange(n,a,`selected-lines`):void 0,s=i?this.resolveLineRenderRange(t,a,`editor-active-line`):void 0,c=this.getLineRenderColumns(r?n:void 0,o,i?t:void 0,s),l=n.range==null||c.some(e=>e.renderSelectedLines),u=t.range==null||c.some(e=>e.renderEditorActiveLine);if(r)for(let e of this.pre.querySelectorAll(`[data-selected-line]`))e.removeAttribute(`data-selected-line`);if(i)for(let e of this.pre.querySelectorAll(`[data-editor-active-line]`))e.removeAttribute(`data-editor-active-line`);let d=o==null?void 0:Math.min(o.start,o.end),f=o==null?void 0:Math.max(o.start,o.end),p=d===f,m=s?.start;for(let e of c){let{content:r,gutter:i,renderEditorActiveLine:o,renderSelectedLines:s}=e,c=Math.max(s?f??-1/0:-1/0,o?m??-1/0:-1/0),l=r.children.length;for(let e=0;e<l;e++){let l=r.children[e],u=i.children[e];if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))continue;let h=this.parseLineIndex(l,a);if((h??0)>c)break;if(h!=null){if(s&&d!=null&&f!=null&&h>=d&&h<=f){let e=p?`single`:h===d?`first`:h===f?`last`:``;u.setAttribute(`data-selected-line`,e),n.lineNumberOnly||(l.setAttribute(`data-selected-line`,e),u.nextSibling instanceof HTMLElement&&l.nextSibling instanceof HTMLElement&&(l.nextSibling.hasAttribute(`data-line-annotation`)||l.nextSibling.hasAttribute(`data-merge-conflict-actions`))&&(p?(e=`last`,l.setAttribute(`data-selected-line`,`first`)):h===d?e=``:h===f&&l.setAttribute(`data-selected-line`,``),l.nextSibling.setAttribute(`data-selected-line`,e),u.nextSibling.setAttribute(`data-selected-line`,e)))}o&&h===m&&(u.setAttribute(`data-editor-active-line`,``),t.lineNumberOnly||l.setAttribute(`data-editor-active-line`,``))}}}r&&l&&(this.renderedSelectedLinesState=n),i&&u&&(this.renderedEditorActiveLineState=t)};notifySelectionCommitted(e){this.options.onLineSelected?.(e)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode===`file`?{type:`line`,lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:`diff-line`,annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}){return this.mode===`file`?{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:i,tokenText:a}:{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,r){return{start:e,end:t,...n==null?{}:{side:n},...n!==r&&r!=null?{endSide:r}:{}}}resolvePointerTarget(e){let t=!1,n,r,i,a,o,s,c,l,u,d;for(let f of e){if(!(f instanceof HTMLElement))continue;if(d==null&&f.hasAttribute(`data-merge-conflict-action`)){let e=f.getAttribute(`data-merge-conflict-action`)??void 0,t=f.getAttribute(`data-merge-conflict-conflict-index`)??void 0,n=t==null?NaN:Number.parseInt(t,10);Ett(e)&&Number.isFinite(n)&&(d={kind:`merge-conflict-action`,resolution:e,conflictIndex:n})}if(s==null&&f.hasAttribute(`data-char`)){s=f;let e=f.getAttribute(`data-char`);if(e!=null){let t=Number.parseInt(e,10);if(!Number.isNaN(t)){let e=f.textContent??``,n=t+e.length;(e.trim()!==``||this.options.enableTokenInteractionsOnWhitespace===!0)&&(c={tokenElement:s,lineCharStart:t,lineCharEnd:n,tokenText:e});continue}}}let e=o==null?f.getAttribute(`data-column-number`)??void 0:void 0;if(e!=null){o=f,u=Number.parseInt(e,10),t=!0,n=j3(f),a=f.getAttribute(`data-line-index`)??void 0;continue}let p=i==null?f.getAttribute(`data-line`)??void 0:void 0;if(p!=null){i=f,u=Number.parseInt(p,10),n=j3(f),a=f.getAttribute(`data-line-index`)??void 0;continue}if(l==null&&(f.hasAttribute(`data-expand-button`)||f.hasAttribute(`data-unmodified-lines`))){l={hunkIndex:void 0,direction:f.hasAttribute(`data-expand-up`)?`up`:f.hasAttribute(`data-expand-down`)?`down`:`both`,all:f.hasAttribute(`data-expand-all-button`)};continue}let m=l==null?void 0:f.getAttribute(`data-expand-index`)??void 0;if(l!=null&&m!=null){let e=Number.parseInt(m,10);Number.isNaN(e)||(l.hunkIndex=e);continue}if(r==null&&f.hasAttribute(`data-code`)){r=f;break}}if(d!=null)return d;if(l?.hunkIndex!=null)return{type:`line-info`,hunkIndex:l.hunkIndex,direction:l.direction,all:l.all};if(i??=a==null?void 0:E3(r,`[data-line][data-line-index="${a}"]`),o??=a==null?void 0:E3(r,`[data-column-number][data-line-index="${a}"]`),r==null||i==null||o==null||n==null||u==null||Number.isNaN(u))return;let f=this.parseLineIndex(i,this.isSplitDiff());return c==null?this.mode===`file`?{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f}:{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:A3(n,r),splitLineIndex:f}:this.mode===`file`?{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f,...c}:{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:A3(n,r),splitLineIndex:f,...c}}isSplitDiff(){return this.pre?.getAttribute(`data-diff-type`)===`split`}parseLineIndex(e,t){let n=(e.getAttribute(`data-line-index`)??``).split(`,`).map(e=>Number.parseInt(e,10)).filter(e=>!Number.isNaN(e));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function Stt({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:r,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,renderGutterUtility:d,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v},y,b,x){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:Ctt({enableGutterUtility:t,renderGutterUtility:d,onGutterUtilityClick:r}),usesCustomGutterUtility:d!=null,lineHoverHighlight:n,onGutterUtilityClick:r,onHunkExpand:y,onMergeConflictActionClick:x,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v,getLineIndex:b}}function Ctt({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw Error(`Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.`);return e??!1}function C3(e){return e!=null&&`kind`in e&&e.kind===`line`}function w3(e){return e!=null&&`kind`in e&&e.kind===`token`}function T3(e){return C3(e)||w3(e)}function wtt(e){return`type`in e&&e.type===`line-info`}function Ttt(e){return`kind`in e&&e.kind===`merge-conflict-action`}function Ett(e){return e===`current`||e===`incoming`||e===`both`}function E3(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function D3(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function Dtt(e){let t=e.closest(`[data-line], [data-column-number]`);if(t instanceof HTMLElement)return t;let n=e.closest(`[data-line-annotation], [data-gutter-buffer="annotation"]`);if(!(n instanceof HTMLElement))return;let r=n.previousElementSibling;return r instanceof HTMLElement&&(r.hasAttribute(`data-line`)||r.hasAttribute(`data-column-number`))?r:void 0}function Ott(e){let t=e.closest(`[slot^="annotation-"]`);if(t instanceof HTMLElement)return t.getAttribute(`slot`)??void 0;if(e instanceof HTMLElement){let t=e.getAttribute(`name`)??void 0;return t!=null&&t.startsWith(`annotation-`)?t:void 0}}function ktt(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(!(!Number.isFinite(n)||n<=0))return{lineNumber:n,side:t[1]}}function O3(e){return e!=null&&typeof e.elementFromPoint==`function`}function Att(e,t){return e===t||X2(e??void 0,t??void 0)}function k3(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&Att(e?.range??null,t.range)}function A3(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function j3(e){let t=e.getAttribute(`data-line-type`);if(t!=null)switch(t){case`change-deletion`:case`change-addition`:case`context`:case`context-expanded`:return t;default:return}}function M3(e=`none`,t,...n){switch(e){case`none`:return;case`both`:break;case`click`:if(t!==`click`)return;break;case`move`:if(t!==`move`)return}console.log(...n)}var jtt=class e{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){let t=e.resizeObserver??new ResizeObserver(e.handleSharedResizeEntries);return e.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let r of t){let t=e.managersByElement.get(r.target);if(t==null)continue;let i=n.get(t);i==null?n.set(t,[r]):i.push(r)}for(let[e,t]of n)e.handleResizeEntries(t)}observedNodes=new Map;setup(e,{disableAnnotations:t,columnVariables:n=`apply`}){let r=new Set,i=n===`apply`,a=0,o=new Map(this.observedNodes);this.observedNodes.clear();for(let t of e.children){if(a===2)break;let e=(()=>{if(t instanceof HTMLElement&&t.tagName===`CODE`)return t})();if(e==null)continue;a++;let n=o.get(e);if(n!=null&&n.type!==`code`)throw Error(`ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible`);let r=e.firstElementChild;r instanceof HTMLElement||(r=null),n==null?(n={type:`code`,codeElement:e,numberElement:r,codeWidth:`auto`,numberWidth:0,applyColumnVariables:i},this.observedNodes.set(e,n),this.observe(e),r!=null&&(this.observedNodes.set(r,n),this.observe(r))):(this.observedNodes.set(e,n),o.delete(e),n.numberElement===r?n.numberElement==null?n.numberWidth=0:(o.delete(n.numberElement),this.observedNodes.set(n.numberElement,n)):(n.numberElement!=null&&(this.unobserve(n.numberElement),o.delete(n.numberElement)),r!=null&&(this.observe(r),o.delete(r),this.observedNodes.set(r,n)),n.numberElement=r,n.numberWidth=0),Ptt(n,i))}if(a>1&&!t){let t=e.querySelectorAll(`[data-line-annotation*=","]`),n=new Map;for(let e of t){if(!(e instanceof HTMLElement))continue;let t=e.getAttribute(`data-line-annotation`)??``;if(!/^-?\d+,-?\d+$/.test(t)){console.error(`DiffFileRenderer.setupResizeObserver: Invalid element or annotation`,{lineAnnotation:t,element:e});continue}let r=n.get(t);r??(r=[],n.set(t,r)),r.push(e)}for(let[e,t]of n){if(t.length!==2){console.error(`DiffFileRenderer.setupResizeObserver: Bad Pair`,e,t);continue}let[n,i]=t,a=n.firstElementChild,s=i.firstElementChild;if(!(n instanceof HTMLElement)||!(i instanceof HTMLElement)||!(a instanceof HTMLElement)||!(s instanceof HTMLElement))continue;let c=o.get(a);if(c!=null){this.observedNodes.set(a,c),this.observedNodes.set(s,c),o.delete(a),o.delete(s);continue}let l=a.getBoundingClientRect().height,u=s.getBoundingClientRect().height;c={type:`annotations`,column1:{container:n,child:a,childHeight:l},column2:{container:i,child:s,childHeight:u},currentHeight:`auto`},r.add({child1:a,child2:s,item:c,newHeight:Math.max(l,u)})}for(let e of r)this.applyNewHeight(e.item,e.newHeight),this.observedNodes.set(e.child1,e.item),this.observedNodes.set(e.child2,e.item),this.observe(e.child1),this.observe(e.child2);r.clear()}for(let[e,t]of o)this.unobserve(e),t.type===`code`?Ftt(t):Itt(t);o.clear()}cleanUp(){for(let e of this.observedNodes.keys())this.unobserve(e);this.observedNodes.clear()}observe(t){let{managersByElement:n}=e,r=n.get(t);if(r!==this){if(r!=null&&r!==this)throw Error(`ResizeManager.observe: element is already owned by another ResizeManager`);n.set(t,this),e.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:r}=e,i=n.get(t);if(i!=null){if(i!==this)throw Error(`ResizeManager.unobserve: element is owned by another ResizeManager`);n.delete(t),r?.unobserve(t),r!=null&&n.size===0&&(r.disconnect(),e.resizeObserver=void 0)}}handleResizeEntries(e){let t=new Map,n=new Set;for(let r of e){let{target:e,borderBoxSize:i,contentBoxSize:a}=r;if(!(e instanceof HTMLElement)){console.error(`ResizeManager.handleResizeEntries: Invalid element for ResizeObserver`,r);continue}let o=this.observedNodes.get(e);if(o==null){console.error(`ResizeManager.handleResizeEntries: Not a valid observed node`,r);continue}if(o.type===`annotations`){let t=(()=>{if(e===o.column1.child)return o.column1;if(e===o.column2.child)return o.column2})();if(t==null){console.error(`ResizeManager.handleResizeEntries: Couldn't find a column for`,{item:o,target:e});continue}t.childHeight=i[0].blockSize,n.add(o)}else if(o.type===`code`){let n=t.get(o)??{},r=a[0].inlineSize;e===o.codeElement?n.codeInlineSize=r:e===o.numberElement&&(n.numberInlineSize=r),t.set(o,n)}}this.applyAnnotationUpdates(n),n.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(e){for(let t of e)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=e=>{for(let[t,n]of e){let e=n.codeInlineSize==null?t.codeWidth:Mtt(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:Ntt(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&N3(t,{codeWidthChanged:i,numberWidthChanged:a}))}};applyNewHeight(e,t){t!==e.currentHeight&&(e.currentHeight=Math.max(t,0),e.column1.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`),e.column2.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`))}};function Mtt(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function Ntt(e){return Math.max(Math.ceil(e),0)}function Ptt(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?N3(e,{codeWidthChanged:!0,numberWidthChanged:!0}):P3(e))}function N3(e,{codeWidthChanged:t,numberWidthChanged:n}){let{codeElement:r,codeWidth:i,numberWidth:a}=e;if(t&&r.style.setProperty(`--diffs-column-width`,`${typeof i==`number`?`${i}px`:`auto`}`),n&&r.style.setProperty(`--diffs-column-number-width`,`${a===0?`auto`:`${a}px`}`),t||n&&i!==`auto`){let e=typeof i==`number`?Math.max(i-a,0):0;r.style.setProperty(`--diffs-column-content-width`,`${e>0?`${e}px`:`auto`}`)}}function P3(e){e.codeElement.style.removeProperty(`--diffs-column-content-width`),e.codeElement.style.removeProperty(`--diffs-column-number-width`),e.codeElement.style.removeProperty(`--diffs-column-width`)}function Ftt(e){e.codeElement.isConnected&&P3(e)}function Itt(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty(`--diffs-annotation-min-height`),e.column2.container.isConnected&&e.column2.container.style.removeProperty(`--diffs-annotation-min-height`)}var F3=new Map,I3=new Map,Ltt=new Map,L3=new Set;function Rtt(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!L3.has(t))return!1;return!0}function R3(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(L3.has(n.name))continue;let e=F3.get(n.name);e??(e=n,F3.set(n.name,e)),L3.add(e.name),t.loadLanguageSync(e.data)}}function z3(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var B3=Object.defineProperty,ztt=Object.getOwnPropertyDescriptor,Btt=Object.getOwnPropertyNames,Vtt=Object.prototype.hasOwnProperty,Htt=(e,t)=>{let n={};for(var r in e)B3(n,r,{get:e[r],enumerable:!0});return t||B3(n,Symbol.toStringTag,{value:`Module`}),n},V3=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Btt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Vtt.call(e,s)&&s!==n&&B3(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ztt(t,s))||r.enumerable});return e},Utt=(e,t,n)=>(V3(e,t,`default`),n&&V3(n,t,`default`)),H3=[{id:`abap`,name:`ABAP`,import:(()=>N(()=>import(`./abap-CLvhMVsD.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>N(()=>import(`./actionscript-3--17pq3dv.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>N(()=>import(`./ada-C5qYipkI.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>N(()=>import(`./angular-html-B8mrqUL5.js`).then(e=>e.n),__vite__mapDeps([6,1,7,8,9])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>N(()=>import(`./angular-ts-Bzix210W.js`),__vite__mapDeps([10,6,1,7,8,9,11])))},{id:`apache`,name:`Apache Conf`,import:(()=>N(()=>import(`./apache-U0d_L8uA.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>N(()=>import(`./apex-CGTLDQj6.js`),[]))},{id:`apl`,name:`APL`,import:(()=>N(()=>import(`./apl-Dhin1L29.js`),__vite__mapDeps([12,8,1,9,7,13,14,15])))},{id:`applescript`,name:`AppleScript`,import:(()=>N(()=>import(`./applescript-CCn79oCD.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>N(()=>import(`./ara-4CJ0cIlV.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>N(()=>import(`./asciidoc-DE70LPWp.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>N(()=>import(`./asm-Cmm7eHzH.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>N(()=>import(`./astro-B-4NNgOP.js`),__vite__mapDeps([16,8,1,9,15,17,18,19])))},{id:`awk`,name:`AWK`,import:(()=>N(()=>import(`./awk-BWXHIvNe.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>N(()=>import(`./ballerina-B7ZEbQpA.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>N(()=>import(`./bat-Bo4NYOV-.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>N(()=>import(`./beancount-D-usSTwE.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>N(()=>import(`./berry-DKpUyyne.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>N(()=>import(`./bibtex-Ci_nEsc7.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>N(()=>import(`./bicep-CUHmPFLl.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>N(()=>import(`./bird2-C6vDhewU.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>N(()=>import(`./blade-Wr94ul2N.js`),__vite__mapDeps([20,8,1,9,7,13,14,15,21,22])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>N(()=>import(`./bsl-BkkzgIyY.js`),__vite__mapDeps([23,24])))},{id:`c`,name:`C`,import:(()=>N(()=>import(`./c-iCihek07.js`).then(e=>e.n),__vite__mapDeps([25,1])))},{id:`c3`,name:`C3`,import:(()=>N(()=>import(`./c3-CnJL0r0V.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>N(()=>import(`./cadence-CQ2zXKGN.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>N(()=>import(`./cairo-DLTphjLi.js`),__vite__mapDeps([26,27])))},{id:`clarity`,name:`Clarity`,import:(()=>N(()=>import(`./clarity-SemFz856.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>N(()=>import(`./clojure-DqKBuwfJ.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>N(()=>import(`./cmake-Bj61d0ZC.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>N(()=>import(`./cobol-Cw2-KvLW.js`),__vite__mapDeps([28,7,1,8,9,14])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>N(()=>import(`./codeowners-C8r90Shi.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>N(()=>import(`./codeql-oeQT6MSM.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>N(()=>import(`./coffee-CiiSLhB6.js`),__vite__mapDeps([29,8,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>N(()=>import(`./common-lisp-Cv5bFMCO.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>N(()=>import(`./coq-BrsZFFmf.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>N(()=>import(`./cpp-DjoE5qBx.js`).then(e=>e.n),__vite__mapDeps([30,1,22,31,32,25])))},{id:`crystal`,name:`Crystal`,import:(()=>N(()=>import(`./crystal-wCJpIkgB.js`),__vite__mapDeps([33,8,1,9,7,22,25,34])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>N(()=>import(`./csharp-Ct8U2NOr.js`),[]))},{id:`css`,name:`CSS`,import:(()=>N(()=>import(`./css-CNuuLpMC.js`).then(e=>e.n),__vite__mapDeps([9,1])))},{id:`csv`,name:`CSV`,import:(()=>N(()=>import(`./csv-Dx-8-gkx.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>N(()=>import(`./cue-CE9AQfxI.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>N(()=>import(`./cypher-ClKdZ_lG.js`),[]))},{id:`d`,name:`D`,import:(()=>N(()=>import(`./d-qD-0Kul2.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>N(()=>import(`./dart-CnvKMtbv.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>N(()=>import(`./dax-BkyTk9wS.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>N(()=>import(`./desktop-Dlh5hvp9.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>N(()=>import(`./diff-woXpYk--.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>N(()=>import(`./docker-IyjqRm3v.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>N(()=>import(`./dotenv-_5a1GRtc.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>N(()=>import(`./dream-maker-DW3nJb8Q.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>N(()=>import(`./edge-DCY0a-ow.js`),__vite__mapDeps([35,7,1,8,9,17,21])))},{id:`elixir`,name:`Elixir`,import:(()=>N(()=>import(`./elixir-DP304Xio.js`),__vite__mapDeps([36,7,1,8,9])))},{id:`elm`,name:`Elm`,import:(()=>N(()=>import(`./elm-o4NJxfws.js`),__vite__mapDeps([37,32,1,25])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>N(()=>import(`./emacs-lisp-B4R74twV.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>N(()=>import(`./erb-BcNYoZVd.js`),__vite__mapDeps([38,7,1,8,9,39,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>N(()=>import(`./erlang-Cphh6RMH.js`),__vite__mapDeps([45,46])))},{id:`fennel`,name:`Fennel`,import:(()=>N(()=>import(`./fennel-DQxkIbk2.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>N(()=>import(`./fish-BJitypiv.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>N(()=>import(`./fluent-C03EYrpw.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>N(()=>import(`./fortran-fixed-form-DEKoE2YW.js`),__vite__mapDeps([47,48])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>N(()=>import(`./fortran-free-form-CYNrtFtB.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>N(()=>import(`./fsharp-D13ZGOAj.js`),__vite__mapDeps([49,46])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>N(()=>import(`./gdresource-C0sCabJj.js`),__vite__mapDeps([50,51,52])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>N(()=>import(`./gdscript-Cp2uCuqX.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>N(()=>import(`./gdshader-CBce3t8t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>N(()=>import(`./genie-CV2tkWYe.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>N(()=>import(`./gherkin-DExj1W_8.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>N(()=>import(`./git-commit-BSykSTBG.js`),__vite__mapDeps([53,54])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>N(()=>import(`./git-rebase-BDPpS8w6.js`),__vite__mapDeps([55,34,1])))},{id:`gleam`,name:`Gleam`,import:(()=>N(()=>import(`./gleam-CSRkHgEL.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>N(()=>import(`./glimmer-js-BONyzAsu.js`),__vite__mapDeps([56,8,1,9,7,17])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>N(()=>import(`./glimmer-ts-f9c0GCOe.js`),__vite__mapDeps([57,8,1,9,7,17])))},{id:`glsl`,name:`GLSL`,import:(()=>N(()=>import(`./glsl-D5MA2a_X.js`).then(e=>e.n),__vite__mapDeps([32,1,25])))},{id:`gn`,name:`GN`,import:(()=>N(()=>import(`./gn-ilITqXS6.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>N(()=>import(`./gnuplot-7GGW24-e.js`),[]))},{id:`go`,name:`Go`,import:(()=>N(()=>import(`./go-rLFTqkRN.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>N(()=>import(`./graphql-Ctjuxyvl.js`).then(e=>e.n),__vite__mapDeps([41,1,8,17,19,42])))},{id:`groovy`,name:`Groovy`,import:(()=>N(()=>import(`./groovy-CacY0gHj.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>N(()=>import(`./hack-7ztQ7Up-.js`),__vite__mapDeps([58,7,1,8,9,22])))},{id:`haml`,name:`Ruby Haml`,import:(()=>N(()=>import(`./haml-CwEpbK1d.js`).then(e=>e.n),__vite__mapDeps([40,1,8,9])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>N(()=>import(`./handlebars-ryMP1rBR.js`),__vite__mapDeps([59,8,1,9,7,44])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>N(()=>import(`./haskell-D8IpX4py.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>N(()=>import(`./haxe-OTjmBuCE.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>N(()=>import(`./hcl-Dh228itO.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>N(()=>import(`./hjson-CxZEssPk.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>N(()=>import(`./hlsl-Cvrh5tZx.js`),[]))},{id:`html`,name:`HTML`,import:(()=>N(()=>import(`./html-XwrE-1r6.js`).then(e=>e.n),__vite__mapDeps([7,1,8,9])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>N(()=>import(`./html-derivative-i4STDFnl.js`),__vite__mapDeps([21,7,1,8,9])))},{id:`http`,name:`HTTP`,import:(()=>N(()=>import(`./http-kmH8AyfE.js`),__vite__mapDeps([60,13,1,14,15,34,41,8,17,19,42])))},{id:`hurl`,name:`Hurl`,import:(()=>N(()=>import(`./hurl-DCZHXKU4.js`),__vite__mapDeps([61,13,1,14,62,41,8,17,19,42])))},{id:`hxml`,name:`HXML`,import:(()=>N(()=>import(`./hxml-B0Qn7Nwc.js`),__vite__mapDeps([63,64])))},{id:`hy`,name:`Hy`,import:(()=>N(()=>import(`./hy-CZbG8q4J.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>N(()=>import(`./imba-DsUTQ-LC.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>N(()=>import(`./ini-B5eOa1yu.js`),[]))},{id:`java`,name:`Java`,import:(()=>N(()=>import(`./java-DdHNQ9hk.js`).then(e=>e.n),__vite__mapDeps([14,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>N(()=>import(`./javascript-obGGvMPs.js`).then(e=>e.n),__vite__mapDeps([8,1])))},{id:`jinja`,name:`Jinja`,import:(()=>N(()=>import(`./jinja-B-tLrNsM.js`),__vite__mapDeps([65,7,1,8,9])))},{id:`jison`,name:`Jison`,import:(()=>N(()=>import(`./jison-CBjhYtSs.js`),__vite__mapDeps([66,8,1])))},{id:`json`,name:`JSON`,import:(()=>N(()=>import(`./json-DAgxKhMr.js`).then(e=>e.n),__vite__mapDeps([15,1])))},{id:`json5`,name:`JSON5`,import:(()=>N(()=>import(`./json5-BR5RXkoi.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>N(()=>import(`./jsonc-CYpm1nAK.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>N(()=>import(`./jsonl-CmCQp5Yx.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>N(()=>import(`./jsonnet-CJTPZ8u_.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>N(()=>import(`./jssm-DXw9l8Rf.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>N(()=>import(`./jsx-gTgmArGx.js`).then(e=>e.n),__vite__mapDeps([42,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>N(()=>import(`./julia-CjHxn3vf.js`),__vite__mapDeps([67,8,1,22,27,30,31,32,25,68])))},{id:`just`,name:`Just`,import:(()=>N(()=>import(`./just-CZ9bduw9.js`),__vite__mapDeps([69,8,1,17,27,34,39,9,7,13,14,22,25,30,31,32,40,41,19,42,43,44,70])))},{id:`kdl`,name:`KDL`,import:(()=>N(()=>import(`./kdl-CsD5j6eV.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>N(()=>import(`./kotlin-DhhofPvG.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>N(()=>import(`./kusto-C7mF5XQf.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>N(()=>import(`./latex-D9bvcAJr.js`),__vite__mapDeps([71,72,68,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>N(()=>import(`./lean-CewbzKMR.js`),[]))},{id:`less`,name:`Less`,import:(()=>N(()=>import(`./less-DVTAwKKz.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>N(()=>import(`./liquid-G0MH4h_m.js`),__vite__mapDeps([73,8,1,9,7,15])))},{id:`llvm`,name:`LLVM IR`,import:(()=>N(()=>import(`./llvm-Cm23YOpf.js`),[]))},{id:`log`,name:`Log file`,import:(()=>N(()=>import(`./log-BNLmms1o.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>N(()=>import(`./logo-Cluzi2Zq.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>N(()=>import(`./lua-FONpmTUP.js`).then(e=>e.n),__vite__mapDeps([43,1,25])))},{id:`luau`,name:`Luau`,import:(()=>N(()=>import(`./luau-CNKltnaQ.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>N(()=>import(`./make-Dixweg8N.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>N(()=>import(`./markdown-BYOwaDjH.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>N(()=>import(`./marko-DV5GrDmo.js`),__vite__mapDeps([74,9,1,11,17,75])))},{id:`matlab`,name:`MATLAB`,import:(()=>N(()=>import(`./matlab-D7qyCx1q.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>N(()=>import(`./mdc-cg1lnqpW.js`),__vite__mapDeps([76,21,7,1,8,9,44,46])))},{id:`mdx`,name:`MDX`,import:(()=>N(()=>import(`./mdx-DQZ5AkYe.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>N(()=>import(`./mermaid-Bk4SNUv9.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>N(()=>import(`./mipsasm-BMqwQI7S.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>N(()=>import(`./mojo-BgCJLMeH.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>N(()=>import(`./moonbit-CaWjb8XO.js`),[]))},{id:`move`,name:`Move`,import:(()=>N(()=>import(`./move-B1IS1UjX.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>N(()=>import(`./narrat-_X_XdTYD.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>N(()=>import(`./nextflow-BJtWHP5T.js`),__vite__mapDeps([77,78])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>N(()=>import(`./nextflow-groovy-DJMQeKeT.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>N(()=>import(`./nginx-BTMw9COX.js`),__vite__mapDeps([79,43,1,25])))},{id:`nim`,name:`Nim`,import:(()=>N(()=>import(`./nim-B6yJ_yaC.js`),__vite__mapDeps([80,8,1,9,7,13,14,25,32,46])))},{id:`nix`,name:`Nix`,import:(()=>N(()=>import(`./nix-IvuFDN5E.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>N(()=>import(`./nushell-DcLAeLz5.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>N(()=>import(`./objective-c-D1A_Heim.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>N(()=>import(`./objective-cpp-BsSzOQcm.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>N(()=>import(`./ocaml-O90oeIOV.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>N(()=>import(`./odin-B1RWQWA5.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>N(()=>import(`./openscad-BUDT5pXO.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>N(()=>import(`./pascal-4ZHwLPI5.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>N(()=>import(`./perl-BAov3eih.js`),__vite__mapDeps([70,8,1,9,7,13,14,22])))},{id:`php`,name:`PHP`,import:(()=>N(()=>import(`./php-Cg76ANFt.js`),__vite__mapDeps([81,8,1,9,7,13,14,15,22])))},{id:`pkl`,name:`Pkl`,import:(()=>N(()=>import(`./pkl-ot-7Btpt.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>N(()=>import(`./plsql-DGHpHOYJ.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>N(()=>import(`./po-BiJDBrnU.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>N(()=>import(`./polar-C7UOKdEL.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>N(()=>import(`./postcss-BXeXVLqQ.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>N(()=>import(`./powerquery-DNMTfnFr.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>N(()=>import(`./powershell-DshXNtvi.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>N(()=>import(`./prisma-BsRQq5mF.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>N(()=>import(`./prolog-iXnhIJG7.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>N(()=>import(`./proto-DB4EqR-F.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>N(()=>import(`./pug-DkgDHZci.js`),__vite__mapDeps([82,8,1,9,7])))},{id:`puppet`,name:`Puppet`,import:(()=>N(()=>import(`./puppet-CDv2pdJW.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>N(()=>import(`./purescript-9MfHhQsQ.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>N(()=>import(`./python-gzcpVVnB.js`),[]))},{id:`qml`,name:`QML`,import:(()=>N(()=>import(`./qml-_a-QhfPD.js`),__vite__mapDeps([83,8,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>N(()=>import(`./qmldir-DCQb3MpD.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>N(()=>import(`./qss-Fe1Jh2GI.js`),[]))},{id:`r`,name:`R`,import:(()=>N(()=>import(`./r-D6UWEOL2.js`).then(e=>e.n),__vite__mapDeps([68,1])))},{id:`racket`,name:`Racket`,import:(()=>N(()=>import(`./racket-DcIDlBhZ.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>N(()=>import(`./raku-B3gFvitq.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>N(()=>import(`./razor-D3EoCAik.js`),__vite__mapDeps([84,7,1,8,9,85])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>N(()=>import(`./reg-CRGYupPL.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>N(()=>import(`./regexp-DR20uMnK.js`).then(e=>e.n),__vite__mapDeps([31,1])))},{id:`rel`,name:`Rel`,import:(()=>N(()=>import(`./rel-BtDbiS_P.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>N(()=>import(`./riscv-Ckw8ddFX.js`),[]))},{id:`ron`,name:`RON`,import:(()=>N(()=>import(`./ron-VUp2lXgN.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>N(()=>import(`./rosmsg-CAekHB0j.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>N(()=>import(`./rst-YTmaoyaq.js`),__vite__mapDeps([86,8,1,21,7,9,27,87,30,22,31,32,25,34,44,39,13,14,40,41,17,19,42,43])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>N(()=>import(`./ruby-2bd251b9.js`),__vite__mapDeps([39,8,1,9,7,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>N(()=>import(`./rust-Cfkwpbl8.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>N(()=>import(`./sas-B6p8-ynO.js`),__vite__mapDeps([88,22,1])))},{id:`sass`,name:`Sass`,import:(()=>N(()=>import(`./sass-DXrisJhu.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>N(()=>import(`./scala-DKOlJaKm.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>N(()=>import(`./scheme-DQCgrYNe.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>N(()=>import(`./scss-YesllqfO.js`).then(e=>e.n),__vite__mapDeps([11,1,9])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>N(()=>import(`./sdbl-bTVj8UrX.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>N(()=>import(`./shaderlab-TOUzSsQk.js`),__vite__mapDeps([89,90])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>N(()=>import(`./shellscript-Da78Ox-3.js`).then(e=>e.n),__vite__mapDeps([34,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>N(()=>import(`./shellsession-CVsQGYfZ.js`),__vite__mapDeps([91,34,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>N(()=>import(`./smalltalk-B16xEiuN.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>N(()=>import(`./solidity-CKzVLygQ.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>N(()=>import(`./soy-DEd-qcad.js`),__vite__mapDeps([92,7,1,8,9])))},{id:`sparql`,name:`SPARQL`,import:(()=>N(()=>import(`./sparql-D_iOobhT.js`),__vite__mapDeps([93,94])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>N(()=>import(`./splunk-BC2Px7Mm.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>N(()=>import(`./sql-ClgswhA6.js`).then(e=>e.n),__vite__mapDeps([22,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>N(()=>import(`./ssh-config-BgfXC-Er.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>N(()=>import(`./stata-RoaAgbqU.js`),__vite__mapDeps([95,22,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>N(()=>import(`./stylus-B6D30XZt.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>N(()=>import(`./surrealql-DIn4NJsS.js`),__vite__mapDeps([96,8,1])))},{id:`svelte`,name:`Svelte`,import:(()=>N(()=>import(`./svelte-Bj3Hmc9F.js`),__vite__mapDeps([97,8,1,9,17,18])))},{id:`swift`,name:`Swift`,import:(()=>N(()=>import(`./swift-DonLKvLd.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>N(()=>import(`./system-verilog-DJ5XKQeo.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>N(()=>import(`./systemd-BxMlprV5.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>N(()=>import(`./talonscript-CohzipZa.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>N(()=>import(`./tasl-DMoTqEGO.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>N(()=>import(`./tcl-CZd0xW_V.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>N(()=>import(`./templ-TjxbArHn.js`),__vite__mapDeps([98,8,1,9,99])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>N(()=>import(`./terraform-DswuEJGm.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>N(()=>import(`./tex-0w6-Dtgt.js`),__vite__mapDeps([72,68,1])))},{id:`toml`,name:`TOML`,import:(()=>N(()=>import(`./toml-CcmNWLt0.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>N(()=>import(`./ts-tags-DFwAVxhO.js`),__vite__mapDeps([100,8,1,9,7,13,14,17,22,32,25])))},{id:`tsv`,name:`TSV`,import:(()=>N(()=>import(`./tsv-sltzmVWM.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>N(()=>import(`./tsx-CUOciP0b.js`).then(e=>e.n),__vite__mapDeps([19,1])))},{id:`turtle`,name:`Turtle`,import:(()=>N(()=>import(`./turtle-ByJddavk.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>N(()=>import(`./twig-BbcH-NR0.js`),__vite__mapDeps([101,8,1,9,11,27,39,7,13,14,22,25,30,31,32,34,40,41,17,19,42,43,44,81,15])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>N(()=>import(`./typescript-BydbNFcO.js`).then(e=>e.n),__vite__mapDeps([17,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>N(()=>import(`./typespec-BRdr0IET.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>N(()=>import(`./typst-DI99ib-x.js`),[]))},{id:`v`,name:`V`,import:(()=>N(()=>import(`./v-DETTlOr0.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>N(()=>import(`./vala-zf12oZj6.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>N(()=>import(`./vb-Djn5o6TS.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>N(()=>import(`./verilog-CiiDBU1e.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>N(()=>import(`./vhdl-BroJfC0k.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>N(()=>import(`./viml-DvXPmvsu.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>N(()=>import(`./vue-BNi0qJZP.js`),__vite__mapDeps([102,8,1,9,7,15,17,21])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>N(()=>import(`./vue-html-DkKkQnZL.js`),__vite__mapDeps([103,8,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>N(()=>import(`./vue-vine-DFaKYU4X.js`),__vite__mapDeps([104,8,1,9,11,18,75,105])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>N(()=>import(`./vyper-CgoNMtux.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>N(()=>import(`./wasm-ByWQv1Qj.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>N(()=>import(`./wenyan-C8pVoKbM.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>N(()=>import(`./wgsl-BsKzXJz4.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>N(()=>import(`./wikitext-ClFFjSW2.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>N(()=>import(`./wit-DdvCle-K.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>N(()=>import(`./wolfram-DLL8P-h_.js`),[]))},{id:`xml`,name:`XML`,import:(()=>N(()=>import(`./xml-BlnrEAEy.js`).then(e=>e.n),__vite__mapDeps([13,1,14])))},{id:`xsl`,name:`XSL`,import:(()=>N(()=>import(`./xsl-BOPS8gLt.js`),__vite__mapDeps([106,13,1,14])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>N(()=>import(`./yaml-Du_6cdrH.js`).then(e=>e.n),__vite__mapDeps([44,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>N(()=>import(`./zenscript-BnlCZFoB.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>N(()=>import(`./zig-CMLA9XwU.js`),[]))}],Wtt=Object.fromEntries(H3.map(e=>[e.id,e.import])),Gtt=Object.fromEntries(H3.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),U3={...Wtt,...Gtt},Ktt=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>N(()=>import(`./andromeeda-WkhI09AS.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>N(()=>import(`./aurora-x-C7CFqhAd.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>N(()=>import(`./ayu-dark-CRu61w6_.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>N(()=>import(`./ayu-light-Dn6O_aYR.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>N(()=>import(`./ayu-mirage-CTjYAbs-.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-frappe-DFlFW5gh.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>N(()=>import(`./catppuccin-latte-CpxdcXpJ.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-macchiato-DIdIQ04K.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-mocha-Co3Xjl64.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>N(()=>import(`./dark-plus-GAt2ZgX8.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>N(()=>import(`./dracula-C2uKkzgK.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>N(()=>import(`./dracula-soft-D1bVjxWZ.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>N(()=>import(`./everforest-dark-D-DlICQR.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>N(()=>import(`./everforest-light-CeVdGHYG.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>N(()=>import(`./github-dark-DwbbXv51.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>N(()=>import(`./github-dark-default-CxjRwzl6.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>N(()=>import(`./github-dark-dimmed-Cr1oaoul.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>N(()=>import(`./github-dark-high-contrast-B4qJZLZa.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>N(()=>import(`./github-light-CsVXhIlR.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>N(()=>import(`./github-light-default-DB_IwZa6.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>N(()=>import(`./github-light-high-contrast-DLgVeSB-.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-hard-DXm60lX3.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-medium-GE2thSmD.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-soft-04Cj-4VZ.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-hard-K6wSn29D.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-medium-CVy3aSlc.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-soft-DNgJjaY0.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>N(()=>import(`./horizon-0-RkHfro.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>N(()=>import(`./horizon-bright-BgL2X9oq.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>N(()=>import(`./houston-KyjWKfuY.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-dragon-7TqgsUPC.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>N(()=>import(`./kanagawa-lotus-CqxMQulh.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-wave-D8CNn6T_.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>N(()=>import(`./laserwave-CQkdhozh.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>N(()=>import(`./light-plus-CNQ8_7Y0.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>N(()=>import(`./material-theme-CAtLaHa3.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>N(()=>import(`./material-theme-darker-k-s5Bc6K.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>N(()=>import(`./material-theme-lighter-CD6a-c4d.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>N(()=>import(`./material-theme-ocean-B3mraInd.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>N(()=>import(`./material-theme-palenight-DEhAARHw.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>N(()=>import(`./min-dark-BFqTAwCr.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>N(()=>import(`./min-light-O7UdaaxX.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>N(()=>import(`./monokai-C0p7Qecz.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>N(()=>import(`./night-owl-BsnCLAKc.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>N(()=>import(`./night-owl-light-BODRhcTU.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>N(()=>import(`./nord-Cd-F4txO.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>N(()=>import(`./one-dark-pro-DUS_IGRK.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>N(()=>import(`./one-light-CVUd7yD5.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>N(()=>import(`./plastic-CF8VZTnn.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>N(()=>import(`./poimandres-BX2TyY6j.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>N(()=>import(`./red-7ga_dcKu.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-rh6ipraJ.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>N(()=>import(`./rose-pine-dawn-DSuRaP6u.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-moon-DdHjCvFQ.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>N(()=>import(`./slack-dark-DYvUXyrP.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>N(()=>import(`./slack-ochin-bqtMVDfH.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>N(()=>import(`./snazzy-light-D8dzFmq5.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>N(()=>import(`./solarized-dark-BQwPDzxK.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>N(()=>import(`./solarized-light-BLaijb3X.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>N(()=>import(`./synthwave-84-CIknw8y7.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>N(()=>import(`./tokyo-night-iIspnLcq.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>N(()=>import(`./vesper-D5bVUKB1.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>N(()=>import(`./vitesse-black-D082JcaE.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>N(()=>import(`./vitesse-dark-z-nr_5O8.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>N(()=>import(`./vitesse-light-ojz42ZLy.js`),[]))}].map(e=>[e.id,e.import])),qtt=e({createOnigurumaEngine:()=>e6,getDefaultWasmLoader:()=>unt,loadWasm:()=>Z3,setDefaultWasmLoader:()=>lnt}),W3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Jtt(){return 2147483648}function Ytt(){return typeof performance<`u`?performance.now():Date.now()}var Xtt=(e,t)=>e+(t-e%t)%t;async function Ztt(e){let t,n,r={};function i(e){n=e,r.HEAPU8=new Uint8Array(e),r.HEAPU32=new Uint32Array(e)}function a(e,t,n){r.HEAPU8.copyWithin(e,t,t+n)}function o(e){try{return t.grow(e-n.byteLength+65535>>>16),i(t.buffer),1}catch{}}function s(e){let t=r.HEAPU8.length;e>>>=0;let n=Jtt();if(e>n)return!1;for(let r=1;r<=4;r*=2){let i=t*(1+.2/r);if(i=Math.min(i,e+100663296),o(Math.min(n,Xtt(Math.max(e,i),65536))))return!0}return!1}let c=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0;function l(e,t,n=1024){let r=t+n,i=t;for(;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&c)return c.decode(e.subarray(t,i));let a=``;for(;t<i;){let n=e[t++];if(!(n&128)){a+=String.fromCharCode(n);continue}let r=e[t++]&63;if((n&224)==192){a+=String.fromCharCode((n&31)<<6|r);continue}let i=e[t++]&63;if(n=(n&240)==224?(n&15)<<12|r<<6|i:(n&7)<<18|r<<12|i<<6|e[t++]&63,n<65536)a+=String.fromCharCode(n);else{let e=n-65536;a+=String.fromCharCode(55296|e>>10,56320|e&1023)}}return a}function u(e,t){return e?l(r.HEAPU8,e,t):``}let d={emscripten_get_now:Ytt,emscripten_memcpy_big:a,emscripten_resize_heap:s,fd_write:()=>0};async function f(){let n=await e({env:d,wasi_snapshot_preview1:d});t=n.memory,i(t.buffer),Object.assign(r,n),r.UTF8ToString=u}return await f(),r}var Qtt=Object.defineProperty,$tt=(e,t,n)=>t in e?Qtt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G3=(e,t,n)=>$tt(e,typeof t==`symbol`?t:t+``,n),K3=null;function ent(e){throw new W3(e.UTF8ToString(e.getLastOnigError()))}var q3=class e{constructor(t){G3(this,`utf16Length`),G3(this,`utf8Length`),G3(this,`utf16Value`),G3(this,`utf8Value`),G3(this,`utf16OffsetToUtf8`),G3(this,`utf8OffsetToUtf16`);let n=t.length,r=e._utf8ByteLength(t),i=r!==n,a=i?new Uint32Array(n+1):null;i&&(a[n]=r);let o=i?new Uint32Array(r+1):null;i&&(o[r]=n);let s=new Uint8Array(r),c=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e),l=r,u=!1;if(r>=55296&&r<=56319&&e+1<n){let n=t.charCodeAt(e+1);n>=56320&&n<=57343&&(l=(r-55296<<10)+65536|n-56320,u=!0)}i&&(a[e]=c,u&&(a[e+1]=c),l<=127?o[c+0]=e:l<=2047?(o[c+0]=e,o[c+1]=e):l<=65535?(o[c+0]=e,o[c+1]=e,o[c+2]=e):(o[c+0]=e,o[c+1]=e,o[c+2]=e,o[c+3]=e)),l<=127?s[c++]=l:l<=2047?(s[c++]=192|(l&1984)>>>6,s[c++]=128|(l&63)>>>0):l<=65535?(s[c++]=224|(l&61440)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0):(s[c++]=240|(l&1835008)>>>18,s[c++]=128|(l&258048)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0),u&&e++}this.utf16Length=n,this.utf8Length=r,this.utf16Value=t,this.utf8Value=s,this.utf16OffsetToUtf8=a,this.utf8OffsetToUtf16=o}static _utf8ByteLength(e){let t=0;for(let n=0,r=e.length;n<r;n++){let i=e.charCodeAt(n),a=i,o=!1;if(i>=55296&&i<=56319&&n+1<r){let t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(a=(i-55296<<10)+65536|t-56320,o=!0)}t+=a<=127?1:a<=2047?2:a<=65535?3:4,o&&n++}return t}createString(e){let t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}},J3=class e{constructor(t){if(G3(this,`id`,++e.LAST_ID),G3(this,`_onigBinding`),G3(this,`content`),G3(this,`utf16Length`),G3(this,`utf8Length`),G3(this,`utf16OffsetToUtf8`),G3(this,`utf8OffsetToUtf16`),G3(this,`ptr`),!K3)throw new W3(`Must invoke loadWasm first.`);this._onigBinding=K3,this.content=t;let n=new q3(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=K3.omalloc(1e4),e._sharedPtrInUse=!0,K3.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(K3)}convertUtf8OffsetToUtf16(e){return this.utf8OffsetToUtf16?e<0?0:e>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[e]:e}convertUtf16OffsetToUtf8(e){return this.utf16OffsetToUtf8?e<0?0:e>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[e]:e}dispose(){this.ptr===e._sharedPtr?e._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};G3(J3,`LAST_ID`,0),G3(J3,`_sharedPtr`,0),G3(J3,`_sharedPtrInUse`,!1);var Y3=J3,tnt=class{constructor(e){if(G3(this,`_onigBinding`),G3(this,`_ptr`),!K3)throw new W3(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new q3(e[r]);t[r]=i.createString(K3),n[r]=i.utf8Length}let r=K3.omalloc(4*e.length);K3.HEAPU32.set(t,r/4);let i=K3.omalloc(4*e.length);K3.HEAPU32.set(n,i/4);let a=K3.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)K3.ofree(t[n]);K3.ofree(i),K3.ofree(r),a===0&&ent(K3),this._onigBinding=K3,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,n){let r=0;if(typeof n==`number`&&(r=n),typeof e==`string`){e=new Y3(e);let n=this._findNextMatchSync(e,t,!1,r);return e.dispose(),n}return this._findNextMatchSync(e,t,!1,r)}_findNextMatchSync(e,t,n,r){let i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),r);if(a===0)return null;let o=i.HEAPU32,s=a/4,c=o[s++],l=o[s++],u=[];for(let t=0;t<l;t++){let n=e.convertUtf8OffsetToUtf16(o[s++]),r=e.convertUtf8OffsetToUtf16(o[s++]);u[t]={start:n,end:r,length:r-n}}return{index:c,captureIndices:u}}};function nnt(e){return typeof e.instantiator==`function`}function rnt(e){return typeof e.default==`function`}function int(e){return e.data!==void 0}function ant(e){return typeof Response<`u`&&e instanceof Response}function ont(e){return typeof ArrayBuffer<`u`&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<`u`&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||typeof Uint32Array<`u`&&e instanceof Uint32Array}var X3;function Z3(e){if(X3)return X3;async function t(){K3=await Ztt(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),nnt(n)?n=await n.instantiator(t):rnt(n)?n=await n.default(t):(int(n)&&(n=n.data),ant(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await snt(n)(t):await cnt(n)(t):ont(n)||n instanceof WebAssembly.Module?n=await Q3(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await Q3(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return X3=t(),X3}function Q3(e){return t=>WebAssembly.instantiate(e,t)}function snt(e){return t=>WebAssembly.instantiateStreaming(e,t)}function cnt(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var $3;function lnt(e){$3=e}function unt(){return $3}async function e6(e){return e&&await Z3(e),{createScanner(e){return new tnt(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new Y3(e)}}}var t6=Htt({});Utt(t6,qtt);var n6=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function dnt(e){return r6(e)}function r6(e){return Array.isArray(e)?fnt(e):e instanceof RegExp?e:typeof e==`object`?pnt(e):e}function fnt(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=r6(e[n]);return t}function pnt(e){let t={};for(let n in e)t[n]=r6(e[n]);return t}function i6(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function a6(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?a6(e.substring(0,e.length-1)):e.substr(~t+1)}var o6=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,s6=class{static hasCaptures(e){return e!==null&&(o6.lastIndex=0,o6.test(e))}static replaceCaptures(e,t,n){return e.replace(o6,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function c6(e,t){return e<t?-1:+(e>t)}function l6(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=c6(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function u6(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function d6(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var f6=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},p6=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(gnt(e),t)}static createFromParsedTheme(e,t){return vnt(e,t)}_cachedMatchRoot=new f6(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>mnt(e.parent,t.parentScopes));return n?new h6(n.fontStyle,n.foreground,n.background):null}},m6=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function mnt(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!hnt(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function hnt(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var h6=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function gnt(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&u6(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&u6(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new _nt(l,u,e,o,s,c)}}return n}var _nt=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},g6=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(g6||{});function vnt(e,t){e.sort((e,t)=>{let n=c6(e.scope,t.scope);return n!==0||(n=l6(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new ynt(t),o=new h6(n,a.getId(r),a.getId(i)),s=new xnt(new _6(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new p6(a,o,s)}var ynt=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},bnt=Object.freeze([]),_6=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||bnt,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},xnt=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),_6.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null){this._mainRule.acceptOverwrite(e,n,r,i);return}for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(l6(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new _6(e,t,n,r,i))}},v6=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=Cnt(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c<<0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function Snt(e){return e}function Cnt(e){return e}function y6(e,t){let n=[],r=wnt(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(b6(i)){let e=[];do e.push(i),i=r.next();while(b6(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function b6(e){return!!e&&!!e.match(/[\w\.:]+/)}function wnt(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function x6(e){typeof e.dispose==`function`&&e.dispose()}var S6=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},Tnt=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},Ent=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},Dnt=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new S6(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new Ent;for(let n of e)Ont(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof S6){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function Ont(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof S6?w6({baseGrammar:a,selfGrammar:i},r):C6(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new S6(e))}function C6(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];T6([r],t,n)}}function w6(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&T6(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&T6(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function T6(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?i6({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&T6(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=E6(i);switch(a.kind){case 0:w6({...t,selfGrammar:t.baseGrammar},n);break;case 1:w6(t,n);break;case 2:C6(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?C6(a.ruleName,i,n):w6(i,n)}else a.kind===4?n.add(new Tnt(a.scopeName,a.ruleName)):n.add(new S6(a.scopeName))}}}var knt=class{kind=0},Ant=class{kind=1},jnt=class{constructor(e){this.ruleName=e}kind=2},Mnt=class{constructor(e){this.scopeName=e}kind=3},Nnt=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function E6(e){if(e===`$base`)return new knt;if(e===`$self`)return new Ant;let t=e.indexOf(`#`);return t===-1?new Mnt(e):t===0?new jnt(e.substring(1)):new Nnt(e.substring(0,t),e.substring(t+1))}var Pnt=/\\(\d+)/,D6=/\\(\d+)/g,Fnt=-1,O6=-2;function k6(e){return e}function A6(e){return e}var j6=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=s6.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=s6.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${a6(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:s6.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:s6.replaceCaptures(this._contentName,e,t)}},Int=class extends j6{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},Lnt=class extends j6{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new I6(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new L6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},M6=class extends j6{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new L6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},N6=class extends j6{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new I6(i,this.id),this.beginCaptures=a,this._end=new I6(o||`￿`,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new L6;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},P6=class extends j6{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new I6(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new I6(o,O6),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new L6;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new L6,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},F6=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new Int(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new Lnt(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=i6({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new M6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new P6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new N6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=E6(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l)if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof M6||e instanceof N6||e instanceof P6)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},I6=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&Pnt.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return D6.lastIndex=0,this.source.replace(D6,(e,t)=>d6(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=`￿`,t[i+1]=`￿`,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=`￿`,t[i+1]=`G`,n[i+1]=`￿`,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},L6=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new R6(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new R6(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},R6=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
1042
+ `)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},z6=class{constructor(e,t){this.languageId=e,this.tokenType=t}},Rnt=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new z6(e,8),this._embeddedLanguagesMatcher=new znt(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new z6(0,0);_getBasicScopeAttributes=new f6(e=>new z6(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},znt=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>d6(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var B6=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function V6(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Bnt(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new B6(i,!0);f()}return new B6(i,!1);function f(){let o=Vnt(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===Fnt){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),U6(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof N6){let r=o;U6(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof P6){let r=o;U6(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(U6(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function Bnt(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof P6&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Wnt(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==O6){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),U6(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function Vnt(e,t,n,r,i,a){let o=Hnt(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Unt(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function Hnt(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=H6(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Unt(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=H6(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function H6(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Wnt(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function U6(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a.length,o.length),l=[],u=o[0].end;for(let t=0;t<c;t++){let c=a[t];if(c===null)continue;let d=o[t];if(d.length===0)continue;if(d.start>u)break;for(;l.length>0&&l[l.length-1].endPos<=d.start;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop();if(l.length>0?i.produceFromScopes(l[l.length-1].scopes,d.start):i.produce(r,d.start),c.retokenizeCapturedWithRuleId){let t=c.getName(s,o),a=r.contentNameScopesList.pushAttributed(t,e),l=c.getContentName(s,o),u=a.pushAttributed(l,e),f=r.push(c.retokenizeCapturedWithRuleId,d.start,-1,!1,null,a,u),p=e.createOnigString(s.substring(0,d.end));V6(e,p,n&&d.start===0,d.start,f,i,!1,0),x6(p);continue}let f=c.getName(s,o);if(f!==null){let t=(l.length>0?l[l.length-1].scopes:r.contentNameScopesList).pushAttributed(f,e);l.push(new Gnt(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var Gnt=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function Knt(e,t,n,r,i,a,o,s){return new Jnt(e,t,n,r,i,a,o,s)}function W6(e,t,n,r,i){let a=y6(t,G6),o=F6.getCompiledRuleId(n,r,i.repository);for(let n of a)e.push({debugSelector:t,matcher:n.matcher,ruleId:o,grammar:i,priority:n.priority})}function G6(e,t){if(t.length<e.length)return!1;let n=0;return e.every(e=>{for(let r=n;r<t.length;r++)if(qnt(t[r],e))return n=r+1,!0;return!1})}function qnt(e,t){if(!e)return!1;if(e===t)return!0;let n=t.length;return e.length>n&&e.substr(0,n)===t&&e[n]===`.`}var Jnt=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new Rnt(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=K6(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=y6(e,G6);for(let n of t)this._tokenTypeMatchers.push({matcher:n.matcher,type:i[e]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:e=>e===this._rootScopeName?this._grammar:this.getExternalGrammar(e),injections:e=>this._grammarRepository.injections(e)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let e=r.injections;if(e)for(let n in e)W6(t,n,e[n],this,r);let i=this._grammarRepository.injections(n);i&&i.forEach(e=>{let n=this.getExternalGrammar(e);if(n){let e=n.injectionSelector;e&&W6(t,e,n,this,n)}})}return t.sort((e,t)=>e.priority-t.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(k6(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[A6(e)]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=K6(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=F6.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===J6.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=v6.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?q6.createRootAndLookUpScopeName(a,r,this):q6.createRoot(`unknown`,r),t=new J6(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
1043
+ `;let a=this.createOnigString(e),o=a.content.length,s=new Xnt(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=V6(this,a,i,0,t,s,!0,r);return x6(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function K6(e,t){return e=dnt(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var q6=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=m6.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new m6(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new m6(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(!0)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),v6.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},J6=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?q6.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:A6(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=q6.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,k6(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,q6.fromExtension(r,n.contentNameScopesList))}},Ynt=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):y6(e,G6).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>y6(e,G6).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Xnt=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=v6.set(n,0,Snt(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=v6.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},Znt=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,Knt(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},Qnt=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new Znt(p6.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(p6.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new Ynt(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new Dnt(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},Y6=J6.NULL;function X6(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function Z6(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function $nt(e){return Array.isArray(e)?e:[e]}async function Q6(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function $6(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function e8(e){return e===`ansi`||$6(e)}function t8(e){return e===`none`}function n8(e){return t8(e)}function r8(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(/(\r?\n)/g),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var i8={light:`#333333`,dark:`#bbbbbb`},a8={light:`#fffffe`,dark:`#1e1e1e`},o8=`__shiki_resolved`;function s8(e){if(e?.[o8])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?i8.light:i8.dark,n||=t.type===`light`?a8.light:a8.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,o8,{enumerable:!1,writable:!1,value:!0}),t}async function c8(e){return Array.from(new Set((await Promise.all(e.filter(e=>!e8(e)).map(async e=>await Q6(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function l8(e){return(await Promise.all(e.map(async e=>n8(e)?null:s8(await Q6(e))))).filter(e=>!!e)}function u8(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new n6(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var ert=class extends Qnt{_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=s8(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=p6.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=u8(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=Array.from(this._langGraph.entries()),n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new n6(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},trt=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},d8=0;function nrt(e){d8+=1,e.warnings!==!1&&d8>=10&&d8%10==0&&console.warn(`[Shiki] ${d8} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new n6("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(s8),i=new ert(new trt(e.engine,n),r,n,e.langAlias),a;function o(t){return u8(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new n6(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new n6(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await c8(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await l8(e))}function g(){if(t)throw new n6(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--d8)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function rrt(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([l8(e.themes||[]),c8(e.langs||[]),e.engine]);return nrt({...e,themes:t,langs:n,engine:r})}var f8=new WeakMap;function p8(e,t){f8.set(e,t)}function m8(e){return f8.get(e)}var h8=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries($nt(n).map(e=>[e,Y6])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return irt(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function irt(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function art(e,t){if(!(e instanceof h8))throw new n6(`Invalid grammar state`);return e.getInternalStack(t)}function g8(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if($6(e.resolveLangAlias(n.lang||`text`))||t8(r))return r8(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new n6(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new n6(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return srt(t,o,i,a,n)}function ort(...e){if(e.length===2)return m8(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if($6(i)||t8(a))throw new n6(`Plain language does not have grammar state`);if(i===`ansi`)throw new n6(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new h8(_8(n,c,o,s,r).stateStack,c.name,o.name)}function srt(e,t,n,r,i){let a=_8(e,t,n,r,i),o=new h8(a.stateStack,t.name,n.name);return p8(a.tokens,o),a.tokens}function _8(e,t,n,r,i){let a=X6(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=r8(e),l=i.grammarState?art(i.grammarState,n.name)??Y6:i.grammarContextCode==null?Y6:_8(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,u=[],d=[];for(let e=0,f=c.length;e<f;e++){let[f,p]=c[e];if(f===``){u=[],d.push([]);continue}if(o>0&&f.length>=o){u=[],d.push([{content:f,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;i.includeExplanation&&(m=t.tokenizeLine(f,l,s),h=m.tokens,g=0);let _=t.tokenizeLine2(f,l,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:f.length;if(t===o)continue;let s=_.tokens[2*e+1],c=Z6(r[v6.getForeground(s)],a),l=v6.getFontStyle(s),d={content:f.substring(t,o),offset:p+t,color:c,fontStyle:l};if(i.includeExplanation){let e=[];if(i.includeExplanation!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(/,/).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(/ /))})}d.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=f.substring(t.startIndex,t.endIndex);r+=n.length,d.explanation.push({content:n,scopes:i.includeExplanation===`scopeName`?crt(t.scopes):lrt(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function crt(e){return e.map(e=>({scopeName:e}))}function lrt(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:drt(e,i,t.slice(0,r))}}return n}function v8(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function urt(e,t,n){if(!v8(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)v8(e[r],n[i])&&--r,--i;return r===-1}function drt(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(urt(e,t,n)){r.push(a);break}return r}function y8(e,t,n,r=g8){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:m8(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=frt(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new h8(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&p8(s,c),s}function frt(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}function b8(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function prt(e){let t=r8(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t[t.length-1].length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}function mrt(e,t,n){let r=new Set;for(let t of e.matchAll(/:?lang=["']([^"']+)["']/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/\\begin\{([\w-]+)\}/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let e=t[1].toLowerCase().trim(),n=e.includes(`/`)?e.split(`/`).pop():e;n&&r.add(n)}if(!n)return Array.from(r);let i=n.getBundledLanguages();return Array.from(r).filter(e=>e&&i[e])}var x8=`light-dark()`,hrt=[`color`,`background-color`];function grt(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function _rt(e,t){let n=Array.from(t instanceof Set?t:new Set(t)).sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=n.filter(t=>e.offset<t&&t<e.offset+e.content.length).map(t=>t-e.offset).sort((e,t)=>e-t);return t.length?grt(e,t):e})):e}function vrt(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>S8(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&hrt.includes(a))if(r===x8&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new n6('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');c[a]=`light-dark(${o[e][a]||`inherit`}, ${o[r][a]||`inherit`})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s;else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function S8(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&g6.Italic&&(t[`font-style`]=`italic`),e.fontStyle&g6.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&g6.Underline&&n.push(`underline`),e.fontStyle&g6.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function C8(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function yrt(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=prt(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new n6(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new n6(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new n6(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));brt(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return _rt(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=Array.from(e.children).filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new n6(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=w8(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new n6(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new n6(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&b8(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function brt(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new n6(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new n6(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function w8(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(w8).join(``):``}var xrt=[yrt()];function T8(e){let t=Srt(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...xrt]}function Srt(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var E8=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],D8={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function Crt(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function O8(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function wrt(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:`resetAll`});else if(r<=9)D8[r]&&t.push({type:`setDecoration`,value:D8[r]});else if(r<=29){let e=D8[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:E8[r-30]}});else if(r===38){let n=O8(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:E8[r-40]}});else if(r===48){let n=O8(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:E8[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:E8[r-100+8]}})}return t}function Trt(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=Crt(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=wrt(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var Ert={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function Drt(e=Ert){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<E8.length;e++)r.push(t(E8[e]));let e=[0,95,135,175,215,255];for(let t=0;t<6;t++)for(let i=0;i<6;i++)for(let a=0;a<6;a++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var Ort={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function krt(e,t,n){let r=X6(e,n),i=r8(t),a=Drt(Object.fromEntries(E8.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||Ort[t]]}))),o=Trt();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=Z6(i,r),o=Z6(o,r),n.decorations.has(`dim`)&&(i=Art(i));let s=g6.None;return n.decorations.has(`bold`)&&(s|=g6.Bold),n.decorations.has(`italic`)&&(s|=g6.Italic),n.decorations.has(`underline`)&&(s|=g6.Underline),n.decorations.has(`strikethrough`)&&(s|=g6.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function Art(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function k8(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!$6(r)&&!t8(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return krt(r,t,n)}return g8(e,t,n)}function A8(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new n6("`themes` option must not be empty");let p=y8(e,t,n,k8);if(c=m8(p),l&&x8!==l&&!f.find(e=>e.color===l))throw new n6(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>vrt(e,h,u,l,d))),c&&p8(a,c);let g=f.map(e=>X6(e.theme,n));i=j8(f,m,g,u,l,`fg`,d),r=j8(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=X6(n.theme,n);a=k8(e,t,n);let l=e.getTheme(n.theme);r=Z6(l.bg,s),i=Z6(l.fg,s),o=l.name,c=m8(a)}else throw new n6("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function j8(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=Z6(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===x8&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new n6('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${Z6(t[r][a],n[r])||`inherit`}, ${Z6(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function M8(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>M8(e,t,n),codeToTokens:(t,n)=>A8(e,t,n)}){let i=t;for(let e of T8(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=A8(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=Mrt(a):d===`never`&&(a=Nrt(a)),f&&(a=Prt(a));let p={...r,get source(){return i}};for(let e of T8(n))a=e.tokens?.call(p,a)||a;return jrt(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function jrt(e,t,n,r=m8(e)){let i=T8(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:b8,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
1044
+ `}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=C8(a.htmlStyle||S8(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&p8(m,r),m}function Mrt(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&g6.Underline||i.fontStyle&g6.Strikethrough));o&&i.content.match(/^\s+$/)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function Nrt(e){return e.map(e=>e.flatMap(e=>{if(e.content.match(/^\s+$/))return e;let t=e.content.match(/^(\s*)(.*?)(\s*)$/);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function Prt(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t[t.length-1],r=C8(e.htmlStyle||S8(e)),i=C8(n.htmlStyle||S8(n)),a=e.fontStyle&&(e.fontStyle&g6.Underline||e.fontStyle&g6.Strikethrough),o=n.fontStyle&&(n.fontStyle&g6.Underline||n.fontStyle&g6.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var Frt=S3;function Irt(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>M8(e,t,n),codeToTokens:(t,n)=>A8(e,t,n)},i=Frt(M8(e,t,n,r));for(let e of T8(n))i=e.postprocess?.call(r,i,n)||i;return i}async function N8(e){let t=await rrt(e);return{getLastGrammarState:(...e)=>ort(t,...e),codeToTokensBase:(e,n)=>k8(t,e,n),codeToTokensWithThemes:(e,n)=>y8(t,e,n),codeToTokens:(e,n)=>A8(t,e,n),codeToHast:(e,n)=>M8(t,e,n),codeToHtml:(e,n)=>Irt(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function Lrt(e){let t=e.langs,n=e.themes,r=e.engine;async function i(e){function i(n){if(typeof n==`string`){if(n=e.langAlias?.[n]||n,e8(n))return[];let r=t[n];if(!r)throw new n6(`Language \`${n}\` is not included in this bundle. You may want to load it from external source.`);return r}return n}function a(e){if(n8(e))return`none`;if(typeof e==`string`){let t=n[e];if(!t)throw new n6(`Theme \`${e}\` is not included in this bundle. You may want to load it from external source.`);return t}return e}let o=(e.themes??[]).map(e=>a(e)),s=(e.langs??[]).map(e=>i(e)),c=await N8({engine:e.engine??r(),...e,themes:o,langs:s});return{...c,loadLanguage(...e){return c.loadLanguage(...e.map(i))},loadTheme(...e){return c.loadTheme(...e.map(a))},getBundledLanguages(){return t},getBundledThemes(){return n}}}return i}function Rrt(e){let t;async function n(n={}){if(t){let e=await t;return await Promise.all([e.loadTheme(...n.themes||[]),e.loadLanguage(...n.langs||[])]),e}{t=e({...n,themes:[],langs:[]});let r=await t;return await Promise.all([r.loadTheme(...n.themes||[]),r.loadLanguage(...n.langs||[])]),r}}return n}function zrt(e,t){let n=Rrt(e);async function r(e,r){let i=await n({langs:[r.lang],themes:`theme`in r?[r.theme]:Object.values(r.themes)}),a=await t?.guessEmbeddedLanguages?.(e,r.lang,i);return a&&await i.loadLanguage(...a),i}return{getSingletonHighlighter(e){return n(e)},async codeToHtml(e,t){return(await r(e,t)).codeToHtml(e,t)},async codeToHast(e,t){return(await r(e,t)).codeToHast(e,t)},async codeToTokens(e,t){return(await r(e,t)).codeToTokens(e,t)},async codeToTokensBase(e,t){return(await r(e,t)).codeToTokensBase(e,t)},async codeToTokensWithThemes(e,t){return(await r(e,t)).codeToTokensWithThemes(e,t)},async getLastGrammarState(e,t){return(await n({langs:[t.lang],themes:[t.theme]})).getLastGrammarState(e,t)}}}var P8=Lrt({langs:U3,themes:Ktt,engine:()=>(0,t6.createOnigurumaEngine)(N(()=>import(`./wasm-BnjxR4X6.js`),[]))}),{codeToHtml:Brt,codeToHast:Vrt,codeToTokens:Hrt,codeToTokensBase:Urt,codeToTokensWithThemes:Wrt,getSingletonHighlighter:Grt,getLastGrammarState:Krt}=zrt(P8,{guessEmbeddedLanguages:mrt}),F8=4294967295,qrt=class{regexps;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}})}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=[];function a(e,t,n=0){return{index:e,captureIndices:t.indices.map(e=>e==null?{start:F8,end:F8,length:0}:{start:e[0]+n,end:e[1]+n,length:e[1]-e[0]})}}for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{n.lastIndex=t;let o=n.exec(r);if(!o)continue;if(o.index===t)return a(e,o,0);i.push([e,o,0])}catch(e){if(this.options.forgiving)continue;throw e}}if(i.length){let e=Math.min(...i.map(e=>e[1].index));for(let[t,n,r]of i)if(n.index===e)return a(t,n,r)}return null}};function I8(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function Jrt(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var L8=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),R8=String.raw;function z8(e,t){if(e==null)throw Error(t??`Value expected`);return e}var B8=R8`\[\^?`,V8=`c.? | C(?:-.?)?|${R8`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${R8`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${R8`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${R8`o\{[^\}]*\}?`}|${R8`\d{1,3}`}`,H8=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,U8=new RegExp(R8`
1045
1045
  \\ (?:
1046
1046
  ${V8}
1047
1047
  | [gk]<[^>]*>?
@@ -1072,8 +1072,8 @@ If init has been called in the preload and contextIsolation is disabled, is not
1072
1072
  | ${B8}
1073
1073
  | &&
1074
1074
  | .
1075
- `.replace(/\s+/g,``),`gsu`);function Zrt(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=git(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(U8.lastIndex=0;s=U8.exec(e);){let t=Qrt(a,e,s[0],U8.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(U8.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?vit(e,u):e).flat(),flags:r}}function Qrt(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=$rt(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:K8(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:lit(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:q8(n)}}if(a===`K`)return{token:Z8(`keep`,n)};if(a===`N`||a===`R`)return{token:X8(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:X8(`any`,n)};if(a===`X`)return{token:X8(`text_segment`,n)};let e=G8(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:pit(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:fit(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:Q8(`group`,n)};if(n===`(?>`)return{token:Q8(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:Q8(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:Q8(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:Q8(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:oit(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
1076
- `,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:X8(`dot`,n)}:n===`^`||n===`$`?{token:K8(e.singleline?{"^":R8`\A`,$:R8`\Z`}[n]:n,n)}:n===`|`?{token:tit(n)}:H8.test(n)?{tokens:yit(n)}:{token:J8(I8(n),n)}}function $rt(e,t,n){let r=[Y8(t[1]===`^`,t)],i=1,a;for(W8.lastIndex=n;a=W8.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(Y8(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(J8(93,e));else if(i--,r.push(nit(e)),!i)break}else{let t=eit(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:W8.lastIndex||e.length}}function eit(e){if(e[0]===`\\`)return G8(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!L8.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return X8(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?rit(e):e===`&&`?iit(e):J8(I8(e),e)}function G8(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return dit(e);if(`dDhHsSwW`.includes(n))return mit(e);if(e.startsWith(R8`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return hit(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return J8(I8(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return J8(_it(e),e);if($8.has(n))return J8($8.get(n),e);if(/\d/.test(n))return ait(t,e);if(e===`\\`)throw Error(R8`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return J8(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function tit(e){return{type:`Alternator`,raw:e}}function K8(e,t){return{type:`Assertion`,kind:e,raw:t}}function q8(e){return{type:`Backreference`,raw:e}}function J8(e,t){return{type:`Character`,value:e,raw:t}}function nit(e){return{type:`CharacterClassClose`,raw:e}}function rit(e){return{type:`CharacterClassHyphen`,raw:e}}function iit(e){return{type:`CharacterClassIntersector`,raw:e}}function Y8(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function X8(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function Z8(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:z8(n.flags),raw:t}}function ait(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function oit(e){return{type:`GroupClose`,raw:e}}function Q8(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function sit(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function cit(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function lit(e){return{type:`Subroutine`,raw:e}}var uit=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),$8=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function dit(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return J8(I8(t.toUpperCase())-64,e)}function fit(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=t5(n),o=t5(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),Z8(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,Q8(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function pit(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=uit.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return sit(l,r??null,i?.split(`,`)??null,e)}function e5(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return cit(t,n,r,e)}function mit(e){let t=e[1].toLowerCase();return X8({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function hit(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return X8(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function t5(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function git(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3;continue}t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function _it(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function vit(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[q8(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(R8`Octal encoded byte above 177 unsupported "${n}"`)}else r=I8(t);a.push(J8(r,(e===0?`\\`:``)+t))}return a}function yit(e){let t=[],n=new RegExp(H8,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(e5(e.slice(0,-1)));continue}}}t.push(e5(e))}return t}function n5(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function bit(e){return xit.has(e.type)}var xit=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function r5(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=Zrt(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return i5();case`Assertion`:return Sit(n);case`Backreference`:return Cit(n,a);case`Character`:return c5(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return wit(n,a,t);case`CharacterClassOpen`:return Tit(n,a,t);case`CharacterSet`:return Eit(n,a);case`Directive`:return Mit(n.kind,{flags:n.flags});case`GroupOpen`:return Dit(n,a,t);case`NamedCallout`:return Pit(n.kind,n.tag,n.arguments);case`Quantifier`:return Oit(n,a);case`Subroutine`:return kit(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=Iit(Nit(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(R8`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(R8`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function Sit({kind:e}){return a5(z8({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===R8`\B`||e===R8`\Y`})}function Cit({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i)if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,o5(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return o5(r)}return i(+r)}function wit(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),jit(o,e);throw Error(`Invalid character class range`)}return c5(I8(`-`))}function Tit({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[l5()],s=x5(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(l5()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=x5(r[t.nextIndex],a)}let c=l5({negate:e});return o.length===1?c.body=o[0].body:(c.kind=`intersection`,c.body=o.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function Eit({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=b5(n);if(L8.has(r)&&!o?.has(r))e=`posix`,n=r;else return h5(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?Fit(n,{negate:t}):u5(e,{negate:t})}function Dit(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=Lit(e),l=c.type===`AbsenceFunction`,u=y5(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&Xrt(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=S5(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(i5()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(v5(t)||t.type===`CapturingGroup`)throw Error(e)}else if(v5(t)||y5(t)&&t.negate)throw Error(e)}}f=S5(r[t.nextIndex])}return t.nextIndex++,c}function Oit({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!bit(a))throw Error(`Quantifier requires a repeatable token`);let o=p5(e,t,n,a);return i.body.pop(),o}function kit({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=m5(i);return r.push(o),o}function Ait(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:g5(t?.body)}}function i5(e){return{type:`Alternative`,body:_5(e?.body)}}function a5(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function o5(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function s5(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!Rit(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:g5(t?.body)}}function c5(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function l5(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:_5(e?.body)}}function jit(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function u5(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function Mit(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:z8(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function Nit(e){return{type:`Flags`,...e}}function d5(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:g5(e?.body)}}function f5(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:g5(e?.body)}}function Pit(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function Fit(e,t){let n=!!t?.negate;if(!L8.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function p5(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function Iit(e,t){return{type:`Regex`,body:g5(t?.body),flags:e}}function m5(e){return{type:`Subroutine`,ref:e}}function h5(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(b5(e));if(!r){if(n.normalizeUnknownPropertyNames)r=zit(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(R8`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function Lit({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return Ait(`repeater`);case`atomic`:return d5({atomic:!0});case`capturing`:return s5(i,{name:n});case`group`:return d5({flags:e});case`lookahead`:case`lookbehind`:return f5({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function g5(e){if(e===void 0)e=[i5()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function _5(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function v5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function y5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function Rit(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function zit(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function b5(e){return e.replace(/[- _]+/g,``).toLowerCase()}function x5(e,t){return z8(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function S5(e){return z8(e,`Unclosed group`)}function C5(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){w5(c).splice(Math.max(0,T5(s)+l),1),l--,u=!0},removeAllNextSiblings(){return w5(c).splice(T5(s)+1)},removeAllPrevSiblings(){let e=T5(s)+l;return l-=e,w5(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,T5(s)+l)]=e:z8(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(w5(c).splice(Math.max(0,T5(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,T5(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`CapturingGroup`:case`Group`:r(a.body,a);break;case`Alternative`:case`CharacterClass`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`LookaroundAssertion`:r(a.body,a);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function w5(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function T5(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var Bit=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function Vit(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Hit(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var E5=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function D5(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;if(!i&&(!r||r===E5.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?E5.CHAR_CLASS:E5.DEFAULT,negated:a[a.length-1]}):s+=n;continue}e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e}return s}function O5(e,t,n,r){D5(e,t,n,r)}function Uit(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===E5.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function k5(e,t,n){return!!Uit(e,t,0,n)}function Wit(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var A5=new RegExp(String.raw`(?<noncapturingStart>${Bit})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function Git(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(A5.lastIndex=Number.isNaN(c)?0:c+7;f=A5.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),Vit(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=D5(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},E5.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var j5=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,M5=new RegExp(String.raw`
1075
+ `.replace(/\s+/g,``),`gsu`);function Yrt(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=mit(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(U8.lastIndex=0;s=U8.exec(e);){let t=Xrt(a,e,s[0],U8.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(U8.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?git(e,u):e).flat(),flags:r}}function Xrt(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=Zrt(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:K8(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:sit(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:q8(n)}}if(a===`K`)return{token:Z8(`keep`,n)};if(a===`N`||a===`R`)return{token:X8(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:X8(`any`,n)};if(a===`X`)return{token:X8(`text_segment`,n)};let e=G8(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:dit(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:uit(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:Q8(`group`,n)};if(n===`(?>`)return{token:Q8(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:Q8(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:Q8(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:Q8(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:iit(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
1076
+ `,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:X8(`dot`,n)}:n===`^`||n===`$`?{token:K8(e.singleline?{"^":R8`\A`,$:R8`\Z`}[n]:n,n)}:n===`|`?{token:$rt(n)}:H8.test(n)?{tokens:_it(n)}:{token:J8(I8(n),n)}}function Zrt(e,t,n){let r=[Y8(t[1]===`^`,t)],i=1,a;for(W8.lastIndex=n;a=W8.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(Y8(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(J8(93,e));else if(i--,r.push(eit(e)),!i)break}else{let t=Qrt(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:W8.lastIndex||e.length}}function Qrt(e){if(e[0]===`\\`)return G8(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!L8.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return X8(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?tit(e):e===`&&`?nit(e):J8(I8(e),e)}function G8(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return lit(e);if(`dDhHsSwW`.includes(n))return fit(e);if(e.startsWith(R8`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return pit(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return J8(I8(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return J8(hit(e),e);if($8.has(n))return J8($8.get(n),e);if(/\d/.test(n))return rit(t,e);if(e===`\\`)throw Error(R8`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return J8(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function $rt(e){return{type:`Alternator`,raw:e}}function K8(e,t){return{type:`Assertion`,kind:e,raw:t}}function q8(e){return{type:`Backreference`,raw:e}}function J8(e,t){return{type:`Character`,value:e,raw:t}}function eit(e){return{type:`CharacterClassClose`,raw:e}}function tit(e){return{type:`CharacterClassHyphen`,raw:e}}function nit(e){return{type:`CharacterClassIntersector`,raw:e}}function Y8(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function X8(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function Z8(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:z8(n.flags),raw:t}}function rit(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function iit(e){return{type:`GroupClose`,raw:e}}function Q8(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function ait(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function oit(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function sit(e){return{type:`Subroutine`,raw:e}}var cit=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),$8=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function lit(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return J8(I8(t.toUpperCase())-64,e)}function uit(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=t5(n),o=t5(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),Z8(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,Q8(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function dit(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=cit.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return ait(l,r??null,i?.split(`,`)??null,e)}function e5(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return oit(t,n,r,e)}function fit(e){let t=e[1].toLowerCase();return X8({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function pit(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return X8(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function t5(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function mit(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3;continue}t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function hit(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function git(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[q8(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(R8`Octal encoded byte above 177 unsupported "${n}"`)}else r=I8(t);a.push(J8(r,(e===0?`\\`:``)+t))}return a}function _it(e){let t=[],n=new RegExp(H8,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(e5(e.slice(0,-1)));continue}}}t.push(e5(e))}return t}function n5(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function vit(e){return yit.has(e.type)}var yit=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function r5(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=Yrt(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return i5();case`Assertion`:return bit(n);case`Backreference`:return xit(n,a);case`Character`:return c5(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return Sit(n,a,t);case`CharacterClassOpen`:return Cit(n,a,t);case`CharacterSet`:return wit(n,a);case`Directive`:return Ait(n.kind,{flags:n.flags});case`GroupOpen`:return Tit(n,a,t);case`NamedCallout`:return Mit(n.kind,n.tag,n.arguments);case`Quantifier`:return Eit(n,a);case`Subroutine`:return Dit(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=Pit(jit(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(R8`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(R8`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function bit({kind:e}){return a5(z8({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===R8`\B`||e===R8`\Y`})}function xit({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i)if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,o5(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return o5(r)}return i(+r)}function Sit(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),kit(o,e);throw Error(`Invalid character class range`)}return c5(I8(`-`))}function Cit({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[l5()],s=x5(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(l5()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=x5(r[t.nextIndex],a)}let c=l5({negate:e});return o.length===1?c.body=o[0].body:(c.kind=`intersection`,c.body=o.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function wit({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=b5(n);if(L8.has(r)&&!o?.has(r))e=`posix`,n=r;else return h5(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?Nit(n,{negate:t}):u5(e,{negate:t})}function Tit(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=Fit(e),l=c.type===`AbsenceFunction`,u=y5(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&Jrt(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=S5(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(i5()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(v5(t)||t.type===`CapturingGroup`)throw Error(e)}else if(v5(t)||y5(t)&&t.negate)throw Error(e)}}f=S5(r[t.nextIndex])}return t.nextIndex++,c}function Eit({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!vit(a))throw Error(`Quantifier requires a repeatable token`);let o=p5(e,t,n,a);return i.body.pop(),o}function Dit({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=m5(i);return r.push(o),o}function Oit(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:g5(t?.body)}}function i5(e){return{type:`Alternative`,body:_5(e?.body)}}function a5(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function o5(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function s5(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!Iit(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:g5(t?.body)}}function c5(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function l5(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:_5(e?.body)}}function kit(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function u5(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function Ait(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:z8(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function jit(e){return{type:`Flags`,...e}}function d5(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:g5(e?.body)}}function f5(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:g5(e?.body)}}function Mit(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function Nit(e,t){let n=!!t?.negate;if(!L8.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function p5(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function Pit(e,t){return{type:`Regex`,body:g5(t?.body),flags:e}}function m5(e){return{type:`Subroutine`,ref:e}}function h5(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(b5(e));if(!r){if(n.normalizeUnknownPropertyNames)r=Lit(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(R8`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function Fit({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return Oit(`repeater`);case`atomic`:return d5({atomic:!0});case`capturing`:return s5(i,{name:n});case`group`:return d5({flags:e});case`lookahead`:case`lookbehind`:return f5({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function g5(e){if(e===void 0)e=[i5()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function _5(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function v5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function y5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function Iit(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function Lit(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function b5(e){return e.replace(/[- _]+/g,``).toLowerCase()}function x5(e,t){return z8(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function S5(e){return z8(e,`Unclosed group`)}function C5(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){w5(c).splice(Math.max(0,T5(s)+l),1),l--,u=!0},removeAllNextSiblings(){return w5(c).splice(T5(s)+1)},removeAllPrevSiblings(){let e=T5(s)+l;return l-=e,w5(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,T5(s)+l)]=e:z8(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(w5(c).splice(Math.max(0,T5(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,T5(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`CapturingGroup`:case`Group`:r(a.body,a);break;case`Alternative`:case`CharacterClass`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`LookaroundAssertion`:r(a.body,a);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function w5(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function T5(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var Rit=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function zit(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Bit(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var E5=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function D5(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;if(!i&&(!r||r===E5.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?E5.CHAR_CLASS:E5.DEFAULT,negated:a[a.length-1]}):s+=n;continue}e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e}return s}function O5(e,t,n,r){D5(e,t,n,r)}function Vit(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===E5.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function k5(e,t,n){return!!Vit(e,t,0,n)}function Hit(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var A5=new RegExp(String.raw`(?<noncapturingStart>${Rit})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function Uit(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(A5.lastIndex=Number.isNaN(c)?0:c+7;f=A5.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),zit(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=D5(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},E5.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var j5=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,M5=new RegExp(String.raw`
1077
1077
  \\(?: \d+
1078
1078
  | c[A-Za-z]
1079
1079
  | [gk]<[^>]+>
@@ -1088,7 +1088,7 @@ If init has been called in the preload and contextIsolation is disabled, is not
1088
1088
  ))?
1089
1089
  | (?<qBase>${j5})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
1090
1090
  | \\?.
1091
- `.replace(/\s+/g,``),`gsu`);function Kit(e){if(!RegExp(`${j5}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(M5.lastIndex=0;o=M5.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a)if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=Hit(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}M5.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null);i=s}return{pattern:e}}var N5=String.raw,P5=N5`\(\?R=(?<rDepth>[^\)]+)\)|${N5`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,F5=N5`\(\?<(?![=!])(?<captureName>[^>]+)>`,I5=N5`${F5}|(?<unnamed>\()(?!\?)`,L5=new RegExp(N5`${F5}|${P5}|\(\?|\\?.`,`gsu`),R5=`Cannot use multiple overlapping recursions`;function qit(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(P5,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&k5(e,N5`\(\?\(DEFINE\)`,E5.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=k5(e,N5`\\[1-9]`,E5.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(L5.lastIndex=0;f=L5.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(z5(m),l)throw Error(R5);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(L5.lastIndex);if(k5(s,P5,E5.DEFAULT))throw Error(R5);let c=m-1;e=B5(t,s,c,!1,n,a,d),i=H5(i,t,c,a.length,0,d);break}if(h){z5(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(R5);break}if(!u)throw Error(N5`Recursive \g cannot be used outside the referenced group "${r===`external`?h:N5`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Wit(e,p);if(o&&k5(m,N5`${F5}|\((?!\?)`,E5.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),y=a.length,b=g-1,x=B5(_,v,b,!0,n,a,d);i=H5(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,L5.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),L5.lastIndex),s.set(p,L5.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),L5.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function z5(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function B5(e,t,n,r,i,a,o){let s=new Set;r&&O5(e+t,F5,({groups:{captureName:e}})=>{s.add(e)},E5.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${V5(`(?:${e}`,`forward`,...c)}(?:)${V5(`${t})`,`backward`,...c)}${t}`}function V5(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=D5(e,N5`${I5}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Jit(i,n),s?e:`(?<${t}${l}>`}return N5`\k<${c}${l}>`},E5.DEFAULT)}return c}function Jit(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function H5(e,t,n,r,i,a){if(e.size&&r){let o=0;O5(t,I5,()=>o++,E5.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var U5=String.fromCodePoint,W5=String.raw,G5={},K5=globalThis.RegExp;G5.flagGroups=(()=>{try{new K5(`(?i:)`)}catch{return!1}return!0})(),G5.unicodeSets=(()=>{try{new K5(`[[]]`,`v`)}catch{return!1}return!0})(),G5.bugFlagVLiteralHyphenIsRange=G5.unicodeSets?(()=>{try{new K5(W5`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,G5.bugNestedClassIgnoresNegation=G5.unicodeSets&&new K5(`[[^a]]`,`v`).test(`a`);function q5(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function J5(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function Y5(e,t){return X5[e]>=X5[t]}function Yit(e,t){if(e==null)throw Error(t??`Value expected`);return e}var X5={ES2025:2025,ES2024:2024,ES2018:2018},Xit={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function Z5(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!Xit[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`auto`,verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target===`auto`&&(t.target=G5.flagGroups?`ES2025`:G5.unicodeSets?`ES2024`:`ES2018`),t}var Zit=`[ -\r ]`,Qit=new Set([U5(304),U5(305)]),Q5=W5`[\p{L}\p{M}\p{N}\p{Pc}]`;function $5(e){if(Qit.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=tat.get(n),a=$it.get(n),o=eat.get(n);return[...r].length===1&&t.add(r),o&&t.add(o),i&&t.add(i),t.add(n),a&&t.add(a),[...t]}var e7=new Map(`C Other
1091
+ `.replace(/\s+/g,``),`gsu`);function Wit(e){if(!RegExp(`${j5}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(M5.lastIndex=0;o=M5.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a)if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=Bit(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}M5.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null);i=s}return{pattern:e}}var N5=String.raw,P5=N5`\(\?R=(?<rDepth>[^\)]+)\)|${N5`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,F5=N5`\(\?<(?![=!])(?<captureName>[^>]+)>`,I5=N5`${F5}|(?<unnamed>\()(?!\?)`,L5=new RegExp(N5`${F5}|${P5}|\(\?|\\?.`,`gsu`),R5=`Cannot use multiple overlapping recursions`;function Git(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(P5,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&k5(e,N5`\(\?\(DEFINE\)`,E5.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=k5(e,N5`\\[1-9]`,E5.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(L5.lastIndex=0;f=L5.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(z5(m),l)throw Error(R5);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(L5.lastIndex);if(k5(s,P5,E5.DEFAULT))throw Error(R5);let c=m-1;e=B5(t,s,c,!1,n,a,d),i=H5(i,t,c,a.length,0,d);break}if(h){z5(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(R5);break}if(!u)throw Error(N5`Recursive \g cannot be used outside the referenced group "${r===`external`?h:N5`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Hit(e,p);if(o&&k5(m,N5`${F5}|\((?!\?)`,E5.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),y=a.length,b=g-1,x=B5(_,v,b,!0,n,a,d);i=H5(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,L5.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),L5.lastIndex),s.set(p,L5.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),L5.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function z5(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function B5(e,t,n,r,i,a,o){let s=new Set;r&&O5(e+t,F5,({groups:{captureName:e}})=>{s.add(e)},E5.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${V5(`(?:${e}`,`forward`,...c)}(?:)${V5(`${t})`,`backward`,...c)}${t}`}function V5(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=D5(e,N5`${I5}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Kit(i,n),s?e:`(?<${t}${l}>`}return N5`\k<${c}${l}>`},E5.DEFAULT)}return c}function Kit(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function H5(e,t,n,r,i,a){if(e.size&&r){let o=0;O5(t,I5,()=>o++,E5.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var U5=String.fromCodePoint,W5=String.raw,G5={},K5=globalThis.RegExp;G5.flagGroups=(()=>{try{new K5(`(?i:)`)}catch{return!1}return!0})(),G5.unicodeSets=(()=>{try{new K5(`[[]]`,`v`)}catch{return!1}return!0})(),G5.bugFlagVLiteralHyphenIsRange=G5.unicodeSets?(()=>{try{new K5(W5`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,G5.bugNestedClassIgnoresNegation=G5.unicodeSets&&new K5(`[[^a]]`,`v`).test(`a`);function q5(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function J5(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function Y5(e,t){return X5[e]>=X5[t]}function qit(e,t){if(e==null)throw Error(t??`Value expected`);return e}var X5={ES2025:2025,ES2024:2024,ES2018:2018},Jit={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function Z5(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!Jit[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`auto`,verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target===`auto`&&(t.target=G5.flagGroups?`ES2025`:G5.unicodeSets?`ES2024`:`ES2018`),t}var Yit=`[ -\r ]`,Xit=new Set([U5(304),U5(305)]),Q5=W5`[\p{L}\p{M}\p{N}\p{Pc}]`;function $5(e){if(Xit.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=$it.get(n),a=Zit.get(n),o=Qit.get(n);return[...r].length===1&&t.add(r),o&&t.add(o),i&&t.add(i),t.add(n),a&&t.add(a),[...t]}var e7=new Map(`C Other
1092
1092
  Cc Control cntrl
1093
1093
  Cf Format
1094
1094
  Cn Unassigned
@@ -1178,18 +1178,18 @@ Uppercase Upper
1178
1178
  Variation_Selector VS
1179
1179
  White_Space space
1180
1180
  XID_Continue XIDC
1181
- XID_Start XIDS`.split(/\s/).map(e=>[b5(e),e])),$it=new Map([[`s`,U5(383)],[U5(383),`s`]]),eat=new Map([[U5(223),U5(7838)],[U5(107),U5(8490)],[U5(229),U5(8491)],[U5(969),U5(8486)]]),tat=new Map([t7(453),t7(456),t7(459),t7(498),...n7(8072,8079),...n7(8088,8095),...n7(8104,8111),t7(8124),t7(8140),t7(8188)]),nat=new Map([[`alnum`,W5`[\p{Alpha}\p{Nd}]`],[`alpha`,W5`\p{Alpha}`],[`ascii`,W5`\p{ASCII}`],[`blank`,W5`[\p{Zs}\t]`],[`cntrl`,W5`\p{Cc}`],[`digit`,W5`\p{Nd}`],[`graph`,W5`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,W5`\p{Lower}`],[`print`,W5`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,W5`[\p{P}\p{S}]`],[`space`,W5`\p{space}`],[`upper`,W5`\p{Upper}`],[`word`,W5`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,W5`\p{AHex}`]]);function rat(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function t7(e){let t=U5(e);return[t.toLowerCase(),t]}function n7(e,t){return rat(e,t).map(e=>t7(e))}var r7=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function iat(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};i7(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:Y5(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};C5(e,aat,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return C5(e,oat,a),C5(e,sat,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var aat={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=d5();e.body[0].body.push(f5({negate:!0,body:r}),h5(`Any`));let i=d5();i.body[0].body.push(p5(`greedy`,0,1/0,e)),n(g7(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];J5(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=c7(t.get(e));if(n){let t=d5({flags:n});t.body[0].body=e.body,e.body=[g7(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(g7(f5({body:[i5({body:[a5(`string_end`)]}),i5({body:[c5(10)]})]}),t));else if(c===`line_start`)o(g7(p7(W5`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`)if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&pat(e))o(g7(f5({negate:!0}),t));else if(d)throw Error(W5`Uses "\G" in a way that requires a subclass`);else o(h7(a5(`string_start`),t)),s.strategy=`clip_search`}else if(c!==`string_end`&&c!==`string_start`)if(c===`string_end_newline`)o(g7(p7(W5`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${Q5})(?!${Q5})|(?<!${Q5})(?=${Q5}))`,n=`(?:(?<=${Q5})(?=${Q5})|(?<!${Q5})(?!${Q5}))`;o(g7(p7(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!f7(n)&&(n=s7(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!f7(r)&&(r=s7(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(g7(l5({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`)){n(h7(u5(`digit`,{negate:l}),t));return}if(o&&(c===`space`||u===`space`)){n(g7(m7(p7(Zit),l),t));return}if(s&&(c===`word`||u===`word`)){n(h7(u5(`word`,{negate:l}),t));return}if(c===`any`)n(h7(h5(`Any`),t));else if(c===`digit`)n(h7(h5(`Nd`,{negate:l}),t));else if(c!==`dot`)if(c===`text_segment`){if(r===`strict`)throw Error(W5`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=W5`\p{RI}{2}|${e}(?:\u200D${e})*`;n(g7(p7(W5`(?>\r\n|${i?W5`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(h7(h5(`AHex`,{negate:l}),t));else if(c===`newline`)n(g7(p7(l?`[^
1181
+ XID_Start XIDS`.split(/\s/).map(e=>[b5(e),e])),Zit=new Map([[`s`,U5(383)],[U5(383),`s`]]),Qit=new Map([[U5(223),U5(7838)],[U5(107),U5(8490)],[U5(229),U5(8491)],[U5(969),U5(8486)]]),$it=new Map([t7(453),t7(456),t7(459),t7(498),...n7(8072,8079),...n7(8088,8095),...n7(8104,8111),t7(8124),t7(8140),t7(8188)]),eat=new Map([[`alnum`,W5`[\p{Alpha}\p{Nd}]`],[`alpha`,W5`\p{Alpha}`],[`ascii`,W5`\p{ASCII}`],[`blank`,W5`[\p{Zs}\t]`],[`cntrl`,W5`\p{Cc}`],[`digit`,W5`\p{Nd}`],[`graph`,W5`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,W5`\p{Lower}`],[`print`,W5`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,W5`[\p{P}\p{S}]`],[`space`,W5`\p{space}`],[`upper`,W5`\p{Upper}`],[`word`,W5`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,W5`\p{AHex}`]]);function tat(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function t7(e){let t=U5(e);return[t.toLowerCase(),t]}function n7(e,t){return tat(e,t).map(e=>t7(e))}var r7=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function nat(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};i7(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:Y5(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};C5(e,rat,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return C5(e,iat,a),C5(e,aat,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var rat={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=d5();e.body[0].body.push(f5({negate:!0,body:r}),h5(`Any`));let i=d5();i.body[0].body.push(p5(`greedy`,0,1/0,e)),n(g7(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];J5(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=c7(t.get(e));if(n){let t=d5({flags:n});t.body[0].body=e.body,e.body=[g7(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(g7(f5({body:[i5({body:[a5(`string_end`)]}),i5({body:[c5(10)]})]}),t));else if(c===`line_start`)o(g7(p7(W5`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`)if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&dat(e))o(g7(f5({negate:!0}),t));else if(d)throw Error(W5`Uses "\G" in a way that requires a subclass`);else o(h7(a5(`string_start`),t)),s.strategy=`clip_search`}else if(c!==`string_end`&&c!==`string_start`)if(c===`string_end_newline`)o(g7(p7(W5`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${Q5})(?!${Q5})|(?<!${Q5})(?=${Q5}))`,n=`(?:(?<=${Q5})(?=${Q5})|(?<!${Q5})(?!${Q5}))`;o(g7(p7(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!f7(n)&&(n=s7(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!f7(r)&&(r=s7(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(g7(l5({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`)){n(h7(u5(`digit`,{negate:l}),t));return}if(o&&(c===`space`||u===`space`)){n(g7(m7(p7(Yit),l),t));return}if(s&&(c===`word`||u===`word`)){n(h7(u5(`word`,{negate:l}),t));return}if(c===`any`)n(h7(h5(`Any`),t));else if(c===`digit`)n(h7(h5(`Nd`,{negate:l}),t));else if(c!==`dot`)if(c===`text_segment`){if(r===`strict`)throw Error(W5`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=W5`\p{RI}{2}|${e}(?:\u200D${e})*`;n(g7(p7(W5`(?>\r\n|${i?W5`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(h7(h5(`AHex`,{negate:l}),t));else if(c===`newline`)n(g7(p7(l?`[^
1182
1182
  ]`:`(?>\r
1183
1183
  ?|[
1184
- \v\f…\u2028\u2029])`),t));else if(c===`posix`)if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${U5(e.codePointAt(0)-1)}${U5(e.codePointAt(2)+1)}-\u{10FFFF}`),n(g7(p7(`[${e}]`),t))}else n(g7(m7(p7(nat.get(u)),l),t));else if(c===`property`)e7.has(b5(u))||(e.key=`sc`);else if(c===`space`)n(h7(h5(`space`,{negate:l}),t));else if(c===`word`)n(g7(m7(p7(Q5),l),t));else throw Error(`Unexpected character set kind "${c}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`)if(!c.enable&&!c.disable)r();else{let e=d5({flags:c});e.body[0].body=o(),i(g7(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&n5(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(W5`Uses "\K" in a way that's unsupported`);let o=f5({behind:!0});o.body[0].body=a(),i(g7(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(g7(f5({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=d5();t.body[0].body.push(e.body),e.body=g7(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=u7(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(W5`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!f7(n)&&(n=s7(n,t),e.ref=n)}},oat={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=h7(o7(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&J5(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=J5(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=q5(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?o7(0):a7(o,r.groupOriginByCopy,null),l=c;if(!s){let e=c7(uat(o,e=>e.type===`Group`&&!!e.flags)),t=e?q5(r.globalFlags,e):r.globalFlags;cat(t,r.currentFlags)||(l=d5({flags:dat(t)}),l.body[0].body.push(c))}n(g7(l,t),{traverse:!s})}},sat={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>lat(t,e));i.length?i.length>1?n(g7(d5({atomic:!0,body:i.reverse().map(e=>i5({body:[o5(e.number)]}))}),t)):e.ref=i[0].number:n(g7(f5({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=s5();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function i7(e){C5(e,{"*"({node:e,parent:t}){e.parent=t}})}function cat(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function lat(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=l7(n.parent);for(let r of t){if(r===n)break;if(r===e||d7(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function a7(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=a7(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function o7(e){let t=m5(e);return t.isRecursive=!0,t}function uat(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function s7(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function c7(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function dat({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function l7(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function u7(e){let t=e.find(e=>e.kind===`search_start`||mat(e,{negate:!1})||!fat(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=u7(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function d7(e,t){let n=l7(e)??[];for(let e of n)if(e===t||d7(e,t))return!0;return!1}function fat({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function pat(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function mat(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&n5(e.body[0],{type:`Assertion`,kind:`search_start`})}function f7(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function p7(e,t){let n=r5(e,{...t,unicodePropertyMap:e7}).body;return n.length>1||n[0].body.length>1?d5({body:n}):n[0].body[0]}function m7(e,t){return e.negate=t,e}function h7(e,t){return e.parent=t,e}function g7(e,t){return i7(e),e.parent=t,e}function hat(e,t){let n=Z5(t),r=Y5(n.target,`ES2024`),i=Y5(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];C5(e,gat,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||o)&&!s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,Yit(_at[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&J5(f._captureTransfers,e.transferTo,[]).push(t)}),f}var gat={"*":{enter({node:e},t){if(x7(e)){let n=t.getCurrentModI();t.pushModI(e.flags?q5({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){x7(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){v7(U5(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),y7(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&r7.has(e.value)&&t.setHasCasedChar()}},_at={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?W5`\B`:W5`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=U5(e),r=b7(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&v7(n)){let e=$5(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);G5.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(S7)&&(o=[c5(45),...o.filter(e=>!S7(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||G5.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=d5(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=i5({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(G5.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=b7(n,i),o=b7(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Sat(y7(e)).forEach(e=>{s.add(Array.isArray(e)?`${b7(e[0],i)}-${b7(e[1],i)}`:b7(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:W5`[^\n]`;if(e===`digit`)return t?W5`\D`:W5`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&r7.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?W5`\P`:W5`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?W5`\W`:W5`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=q5(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${Cat(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+wat(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:W5`\g<${t}&R=${r}>`}},vat=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),yat=new Set([`-`,`\\`,`]`,`^`,`[`]),bat=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),_7=new Map([[9,W5`\t`],[10,W5`\n`],[11,W5`\v`],[12,W5`\f`],[13,W5`\r`],[8232,W5`\u2028`],[8233,W5`\u2029`],[65279,W5`\uFEFF`]]),xat=/^\p{Cased}$/u;function v7(e){return xat.test(e)}function y7(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=U5(e);if(!v7(t))continue;let o=$5(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function b7(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(_7.has(e))return _7.get(e);if(e<32||e>126&&e<160||e>262143||t&&Tat(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?bat:yat:vat,a=U5(e);return(i.has(a)?`\\`:``)+a}function Sat(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function Cat(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function wat({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function x7({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function Tat(e){return e>47&&e<58}function S7({type:e,value:t}){return e===`Character`&&t===45}var Eat=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=Oat(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(Dat(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=kat(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function Dat(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function Oat(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)J5(n,t,{}).transferTo=e;return n}function kat(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function Aat(e,t){let n=jat(e,t);return n.options?new Eat(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function jat(e,t){let n=Z5(t),r=iat(r5(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:e7}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=hat(r,n),a=qit(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Git(Kit(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function Mat(e,t){return Aat(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function Nat(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>Mat(e,{target:t.target}),{createScanner(e){return new Yrt(e,t)},createString(e){return{content:e}}}}async function C7(e){if(B3())throw Error(`resolveLanguage("${e}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);let t=L3.get(e);if(t!=null)return t;try{let t=Rtt.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(W3,e)&&(t=W3[e]),t==null)throw Error(`resolveLanguage: "${e}" not found in bundled or custom languages`);let n=t().then(({default:t})=>{let n={name:e,data:t};return I3.has(e)||I3.set(e,n),n});return L3.set(e,n),await n}finally{L3.delete(e)}}function w7(e){return I3.get(e)??C7(e)}var T7=new Set;function E7(e){let t=[],n=new Set;for(let r of Pat(e.themes)){let e=D7(r)?r.getThemes():[r];for(let r of e){if(n.has(r.name))throw Error(`Theme collection already contains theme "${r.name}"`);n.add(r.name),t.push(r)}}let r=Object.freeze([...t]),i=Object.freeze(r.filter(e=>e.colorScheme===`light`)),a=Object.freeze(r.filter(e=>e.colorScheme===`dark`)),o=new Map(r.map(e=>[e.name,e])),s=Object.freeze(r.map(e=>e.name)),c=Object.freeze(i.map(e=>e.name)),l=Object.freeze(a.map(e=>e.name));function u(e){if(e==null)return r;let{colorScheme:t,collection:n}=e;return n==null?t===`light`?i:t===`dark`?a:r:r.filter(e=>e.collection===n?t==null||e.colorScheme===t:!1)}return{getTheme(e){return o.get(e)},getThemes(e){return u(e)},getThemeNames(e){return e?.collection==null?e?.colorScheme===`light`?c:e?.colorScheme===`dark`?l:s:u(e).map(e=>e.name)},hasTheme(e){return o.has(e)},orderBy(e){return E7({themes:r.map((e,t)=>({descriptor:e,index:t})).sort((t,n)=>{let r=e(t.descriptor,n.descriptor);return r===0?t.index-n.index:r}).map(e=>e.descriptor)})},pick(e){let t=[],n=new Set;for(let r of e){if(n.has(r))throw Error(`Theme collection pick already includes theme "${r}"`);n.add(r);let e=o.get(r);if(e==null)throw Error(`Theme collection does not contain theme "${r}"`);t.push(e)}return E7({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function Pat(e){return Fat(e)?[e]:e}function Fat(e){return D7(e)||Iat(e)}function Iat(e){return typeof e.name==`string`&&typeof e.load==`function`}function D7(e){return typeof e.getThemes==`function`}function O7(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var Lat=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},Rat=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},zat=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function Bat(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new Lat(t);e.set(t,n)}function a(t,n){return!e.has(t)&&(e.set(t,n),!0)}function o(t){return e.has(t)}function s(i){let a=t.get(i);if(a!==void 0)return Promise.resolve(a);let o=n.get(i);if(o!==void 0)return o;let s=e.get(i);if(s===void 0)return Promise.reject(new Rat(i));let c=r,l=s().then(e=>{let a=O7(e);return c===r&&t.set(i,a),n.get(i)===l&&n.delete(i),a}).catch(e=>{throw n.get(i)===l&&n.delete(i),e});return n.set(i,l),l}function c(e){return Promise.all(e.map(e=>s(e)))}function l(e,n){t.set(e,n)}function u(e){for(let[t,n]of e)l(t,n)}function d(e){return t.get(e)}function f(e){let n=[];for(let r of e){let e=t.get(r);if(e===void 0)throw new zat(r);n.push(e)}return n}function p(e){return t.has(e)}function m(e){for(let n of e)if(!t.has(n))return!1;return!0}function h(e){let n=t.get(e);return n===void 0?s(e):n}function g(){r++,t.clear(),n.clear()}return{clearResolvedThemes:g,getResolvedOrResolveTheme:h,getResolvedTheme:d,getResolvedThemes:f,hasRegisteredTheme:o,hasResolvedTheme:p,hasResolvedThemes:m,registerTheme:i,registerThemeIfAbsent:a,resolveTheme:s,resolveThemes:c,seedResolvedTheme:l,seedResolvedThemes:u}}var k7=Bat();function A7(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=k7.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,k7.getResolvedTheme(n)??k7.seedResolvedTheme(n,e);T7.has(n)||(T7.add(n),t.loadThemeSync(e))}}function j7({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:Vat(t)}}function Vat(e){return async()=>c8(O7(await e()))}var Hat=`pierre`,Uat=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],M7=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],Wat=[...M7,...Uat],Gat=new Set(M7);function Kat(e){return Gat.has(e)?`light`:`dark`}var qat={"pierre-dark":`Pierre Dark`,"pierre-dark-soft":`Pierre Dark Soft`,"pierre-dark-vibrant":`Pierre Dark Vibrant`,"pierre-dark-protanopia-deuteranopia":`Pierre Dark Protanopia & Deuteranopia`,"pierre-dark-tritanopia":`Pierre Dark Tritanopia`,"pierre-light":`Pierre Light`,"pierre-light-soft":`Pierre Light Soft`,"pierre-light-vibrant":`Pierre Light Vibrant`,"pierre-light-protanopia-deuteranopia":`Pierre Light Protanopia & Deuteranopia`,"pierre-light-tritanopia":`Pierre Light Tritanopia`},Jat={"pierre-dark":()=>N(()=>import(`./pierre-dark-CpLgRqie.js`),[]),"pierre-dark-soft":()=>N(()=>import(`./pierre-dark-soft-kZQmAZld.js`),[]),"pierre-dark-vibrant":()=>N(()=>import(`./pierre-dark-vibrant-CpQYzh95.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>N(()=>import(`./pierre-dark-protanopia-deuteranopia-B35FxJx-.js`),[]),"pierre-dark-tritanopia":()=>N(()=>import(`./pierre-dark-tritanopia-CpjhbsIL.js`),[]),"pierre-light":()=>N(()=>import(`./pierre-light-CoaEpmwp.js`),[]),"pierre-light-soft":()=>N(()=>import(`./pierre-light-soft-lWLdNTOI.js`),[]),"pierre-light-vibrant":()=>N(()=>import(`./pierre-light-vibrant-D80Fkn33.js`),[]),"pierre-light-protanopia-deuteranopia":()=>N(()=>import(`./pierre-light-protanopia-deuteranopia-0fSaH845.js`),[]),"pierre-light-tritanopia":()=>N(()=>import(`./pierre-light-tritanopia-CEbqgOJL.js`),[])};function Yat(e){return j7({name:e,collection:Hat,colorScheme:Kat(e),displayName:qat[e],load:Jat[e]})}var Xat=E7({themes:Wat.map(e=>Yat(e))}),Zat=`shiki`,N7=[`ayu-light`,`catppuccin-latte`,`everforest-light`,`github-light`,`github-light-default`,`github-light-high-contrast`,`gruvbox-light-hard`,`gruvbox-light-medium`,`gruvbox-light-soft`,`horizon-bright`,`kanagawa-lotus`,`light-plus`,`material-theme-lighter`,`min-light`,`night-owl-light`,`one-light`,`rose-pine-dawn`,`slack-ochin`,`snazzy-light`,`solarized-light`,`vitesse-light`],Qat=`andromeeda.aurora-x.ayu-dark.ayu-mirage.catppuccin-frappe.catppuccin-macchiato.catppuccin-mocha.dark-plus.dracula.dracula-soft.everforest-dark.github-dark.github-dark-default.github-dark-dimmed.github-dark-high-contrast.gruvbox-dark-hard.gruvbox-dark-medium.gruvbox-dark-soft.horizon.houston.kanagawa-dragon.kanagawa-wave.laserwave.material-theme.material-theme-darker.material-theme-ocean.material-theme-palenight.min-dark.monokai.night-owl.nord.one-dark-pro.plastic.poimandres.red.rose-pine.rose-pine-moon.slack-dark.solarized-dark.synthwave-84.tokyo-night.vesper.vitesse-black.vitesse-dark`.split(`.`),$at=new Set(N7);function eot(e){return $at.has(e)?`light`:`dark`}var tot={andromeeda:()=>N(()=>import(`./andromeeda-vGVdxbeo.js`),[]),"aurora-x":()=>N(()=>import(`./aurora-x-CDeNXAV0.js`),[]),"ayu-dark":()=>N(()=>import(`./ayu-dark-DluEY0Gj.js`),[]),"ayu-light":()=>N(()=>import(`./ayu-light-C3h-C4tm.js`),[]),"ayu-mirage":()=>N(()=>import(`./ayu-mirage-Bqwy1Gya.js`),[]),"catppuccin-frappe":()=>N(()=>import(`./catppuccin-frappe-3VR1Za6u.js`),[]),"catppuccin-latte":()=>N(()=>import(`./catppuccin-latte-DwIHMF0Q.js`),[]),"catppuccin-macchiato":()=>N(()=>import(`./catppuccin-macchiato-DYnBP6_5.js`),[]),"catppuccin-mocha":()=>N(()=>import(`./catppuccin-mocha-DYhrFGRu.js`),[]),"dark-plus":()=>N(()=>import(`./dark-plus-Cs2F2srj.js`),[]),dracula:()=>N(()=>import(`./dracula-BHWKrbxM.js`),[]),"dracula-soft":()=>N(()=>import(`./dracula-soft-5eyTD99u.js`),[]),"everforest-dark":()=>N(()=>import(`./everforest-dark-sB-x3p7T.js`),[]),"everforest-light":()=>N(()=>import(`./everforest-light-Df2xbC6M.js`),[]),"github-dark":()=>N(()=>import(`./github-dark-C-LZuMrd.js`),[]),"github-dark-default":()=>N(()=>import(`./github-dark-default-DXG-b-1a.js`),[]),"github-dark-dimmed":()=>N(()=>import(`./github-dark-dimmed-Bx1FflLF.js`),[]),"github-dark-high-contrast":()=>N(()=>import(`./github-dark-high-contrast-B_tTalzw.js`),[]),"github-light":()=>N(()=>import(`./github-light-EUqPIrTm.js`),[]),"github-light-default":()=>N(()=>import(`./github-light-default-BXViO-2h.js`),[]),"github-light-high-contrast":()=>N(()=>import(`./github-light-high-contrast-B68TUdTA.js`),[]),"gruvbox-dark-hard":()=>N(()=>import(`./gruvbox-dark-hard-C820rvS2.js`),[]),"gruvbox-dark-medium":()=>N(()=>import(`./gruvbox-dark-medium-BPjhmG05.js`),[]),"gruvbox-dark-soft":()=>N(()=>import(`./gruvbox-dark-soft-MrdJrrXF.js`),[]),"gruvbox-light-hard":()=>N(()=>import(`./gruvbox-light-hard-BC_s9l72.js`),[]),"gruvbox-light-medium":()=>N(()=>import(`./gruvbox-light-medium-BAWPOn9u.js`),[]),"gruvbox-light-soft":()=>N(()=>import(`./gruvbox-light-soft-BSMLrYjP.js`),[]),horizon:()=>N(()=>import(`./horizon-CE9ld1lL.js`),[]),"horizon-bright":()=>N(()=>import(`./horizon-bright-DSNQnXHK.js`),[]),houston:()=>N(()=>import(`./houston-CsvMBhTu.js`),[]),"kanagawa-dragon":()=>N(()=>import(`./kanagawa-dragon-CXtmUGW6.js`),[]),"kanagawa-lotus":()=>N(()=>import(`./kanagawa-lotus-BN08jTvb.js`),[]),"kanagawa-wave":()=>N(()=>import(`./kanagawa-wave-CTweb8Dz.js`),[]),laserwave:()=>N(()=>import(`./laserwave-C_8bwKvT.js`),[]),"light-plus":()=>N(()=>import(`./light-plus-DVQuIRkW.js`),[]),"material-theme":()=>N(()=>import(`./material-theme-Bm3Qr25_.js`),[]),"material-theme-darker":()=>N(()=>import(`./material-theme-darker-2IIEA8gg.js`),[]),"material-theme-lighter":()=>N(()=>import(`./material-theme-lighter-uhdI0v04.js`),[]),"material-theme-ocean":()=>N(()=>import(`./material-theme-ocean-CHQ94UKr.js`),[]),"material-theme-palenight":()=>N(()=>import(`./material-theme-palenight-B5W6OYN7.js`),[]),"min-dark":()=>N(()=>import(`./min-dark-BSWPekZh.js`),[]),"min-light":()=>N(()=>import(`./min-light-DDpmG2fV.js`),[]),monokai:()=>N(()=>import(`./monokai-CdkpiU2Y.js`),[]),"night-owl":()=>N(()=>import(`./night-owl-DhmEMT88.js`),[]),"night-owl-light":()=>N(()=>import(`./night-owl-light-eJ-hLW7d.js`),[]),nord:()=>N(()=>import(`./nord-Cb4Vim4T.js`),[]),"one-dark-pro":()=>N(()=>import(`./one-dark-pro-CLwyXe_n.js`),[]),"one-light":()=>N(()=>import(`./one-light-D7Lr4KcI.js`),[]),plastic:()=>N(()=>import(`./plastic-DQwYfKfQ.js`),[]),poimandres:()=>N(()=>import(`./poimandres-DRFjx7u4.js`),[]),red:()=>N(()=>import(`./red-CJ3rzSJv.js`),[]),"rose-pine":()=>N(()=>import(`./rose-pine-BthvhNj6.js`),[]),"rose-pine-dawn":()=>N(()=>import(`./rose-pine-dawn-Dg85fqjY.js`),[]),"rose-pine-moon":()=>N(()=>import(`./rose-pine-moon-hon4tzzS.js`),[]),"slack-dark":()=>N(()=>import(`./slack-dark-DnToyrRv.js`),[]),"slack-ochin":()=>N(()=>import(`./slack-ochin-B2OO5cIa.js`),[]),"snazzy-light":()=>N(()=>import(`./snazzy-light-4G7pJPwS.js`),[]),"solarized-dark":()=>N(()=>import(`./solarized-dark-DV17i1UV.js`),[]),"solarized-light":()=>N(()=>import(`./solarized-light-DSh2HLQt.js`),[]),"synthwave-84":()=>N(()=>import(`./synthwave-84-nFMaYfgc.js`),[]),"tokyo-night":()=>N(()=>import(`./tokyo-night-oM2G3aXe.js`),[]),vesper:()=>N(()=>import(`./vesper-DdrHHSXu.js`),[]),"vitesse-black":()=>N(()=>import(`./vitesse-black-fwtXNY1n.js`),[]),"vitesse-dark":()=>N(()=>import(`./vitesse-dark-BZCL-v6S.js`),[]),"vitesse-light":()=>N(()=>import(`./vitesse-light-VbXTXTou.js`),[])};function P7(e){return j7({name:e,collection:Zat,colorScheme:eot(e),load:tot[e]})}var not=E7({themes:Object.freeze([...N7.map(e=>P7(e)),...Qat.map(e=>P7(e))])});function F7(e){if(B3())throw Error(`Theme "${e}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);if(k7.hasRegisteredTheme(e))return;let t=not.getTheme(e);if(t!=null){k7.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function I7(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function rot(e){F7(e);let t=await k7.resolveTheme(e);return I7(e,t),t}function iot(e){return k7.getResolvedTheme(e)??rot(e)}var L7;async function R7({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){L7??=P8({themes:[],langs:[`text`],engine:n===`shiki-wasm`?t6(N(()=>import(`./wasm-BnjxR4X6.js`),[])):Nat()});let r=oot(L7)?await L7:L7;L7=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=w7(e);`then`in t?i.push(t):z3(t,r)}let a=[];for(let t of e){let e=iot(t);`then`in e?a.push(e):A7(e,L7)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{z3(e,r)}),Promise.all(a).then(e=>{A7(e,r)})]),r}function aot(){if(L7!=null&&!(`then`in L7))return L7}function oot(e=L7){return e!=null&&`then`in e}for(let e of Xat.getThemes())k7.registerThemeIfAbsent(e.name,e.load);function z7(e=B2){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function sot(e){for(let t of z7(e))if(!T7.has(t))return!1;return!0}function B7(e){return k7.hasResolvedThemes(e)}function V7(e,t){return Y2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function cot(e,t){return e==null||t==null?e===t:e.startingLine===t.startingLine&&e.totalLines===t.totalLines&&e.bufferBefore===t.bufferBefore&&e.bufferAfter===t.bufferAfter}function lot(e){return w4({tagName:`div`,children:[w4({tagName:`div`,children:e.annotations?.map(e=>w4({tagName:`slot`,properties:{name:e}})),properties:{"data-annotation-content":``}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function uot(e){switch(e){case`file`:return`diffs-icon-file-code`;case`change`:return`diffs-icon-symbol-modified`;case`new`:return`diffs-icon-symbol-added`;case`deleted`:return`diffs-icon-symbol-deleted`;case`rename-pure`:case`rename-changed`:return`diffs-icon-symbol-moved`}}function dot({fileOrDiff:e,mode:t,stickyHeader:n}){let r=`type`in e?e:void 0,i={"data-diffs-header":t,"data-change-type":r?.type,"data-sticky":n?``:void 0};return w4({tagName:`div`,children:[t===`custom`?w4({tagName:`slot`,properties:{name:z2}}):fot({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[pot(r)]],properties:i})}function fot({name:e,prevName:t,iconType:n}){let r=[w4({tagName:`slot`,properties:{name:I2}}),T4({name:uot(n),properties:{"data-change-icon":n}})];return t!=null&&(r.push(w4({tagName:`div`,children:[w4({tagName:`bdi`,children:[C4(t)]})],properties:{"data-prev-name":``}})),r.push(T4({name:`diffs-icon-arrow-right-short`,properties:{"data-rename-icon":``}}))),r.push(w4({tagName:`div`,children:[w4({tagName:`bdi`,children:[C4(e)]})],properties:{"data-title":``}})),r.push(w4({tagName:`slot`,properties:{name:L2}})),w4({tagName:`div`,children:r,properties:{"data-header-content":``}})}function pot(e){let t=[];if(e!=null){let n=0,r=0;for(let t of e.hunks)n+=t.additionLines,r+=t.deletionLines;(r>0||n===0)&&t.push(w4({tagName:`span`,children:[C4(`-${r}`)],properties:{"data-deletions-count":``}})),(n>0||r===0)&&t.push(w4({tagName:`span`,children:[C4(`+${n}`)],properties:{"data-additions-count":``}}))}return t.push(w4({tagName:`slot`,properties:{name:R2}})),w4({tagName:`div`,children:t,properties:{"data-metadata":``}})}function mot(e){return w4({tagName:`pre`,properties:hot(e)})}function hot({diffIndicators:e,disableBackground:t,disableLineNumbers:n,overflow:r,split:i,totalLines:a,type:o,customProperties:s}){return{...s,"data-diff":o===`diff`?``:void 0,"data-file":o===`file`?``:void 0,"data-diff-type":o===`diff`?i?`split`:`single`:void 0,"data-overflow":r,"data-disable-line-numbers":n?``:void 0,"data-background":t?void 0:``,"data-indicators":e===`bars`||e===`classic`?e:void 0,style:`--diffs-min-number-column-width-default:${`${a}`.length}ch;`}}var H7=new Map,got=0,U7={"1c":`1c`,abap:`abap`,as:`actionscript-3`,ada:`ada`,adb:`ada`,ads:`ada`,adoc:`asciidoc`,asciidoc:`asciidoc`,"component.html":`angular-html`,"component.ts":`angular-ts`,conf:`nginx`,htaccess:`apache`,cls:`tex`,trigger:`apex`,apl:`apl`,applescript:`applescript`,scpt:`applescript`,ara:`ara`,asm:`asm`,s:`riscv`,astro:`astro`,awk:`awk`,bal:`ballerina`,sh:`zsh`,bash:`zsh`,bat:`cmd`,cmd:`cmd`,be:`berry`,beancount:`beancount`,bib:`bibtex`,bicep:`bicep`,"blade.php":`blade`,bsl:`bsl`,c:`c`,h:`objective-cpp`,cs:`csharp`,cpp:`cpp`,hpp:`cpp`,cc:`cpp`,cxx:`cpp`,hh:`cpp`,cdc:`cdc`,cairo:`cairo`,clar:`clarity`,clj:`clojure`,cljs:`clojure`,cljc:`clojure`,soy:`soy`,cmake:`cmake`,"CMakeLists.txt":`cmake`,cob:`cobol`,cbl:`cobol`,cobol:`cobol`,CODEOWNERS:`codeowners`,ql:`ql`,coffee:`coffeescript`,lisp:`lisp`,cl:`lisp`,lsp:`lisp`,log:`log`,v:`verilog`,cql:`cql`,cr:`crystal`,css:`css`,csv:`csv`,cue:`cue`,cypher:`cypher`,cyp:`cypher`,d:`d`,dart:`dart`,dax:`dax`,desktop:`desktop`,diff:`diff`,patch:`diff`,Dockerfile:`dockerfile`,dockerfile:`dockerfile`,env:`dotenv`,dm:`dream-maker`,edge:`edge`,el:`emacs-lisp`,ex:`elixir`,exs:`elixir`,elm:`elm`,erb:`erb`,erl:`erlang`,hrl:`erlang`,f:`fortran-fixed-form`,for:`fortran-fixed-form`,fs:`fsharp`,fsi:`fsharp`,fsx:`fsharp`,f03:`f03`,f08:`f08`,f18:`f18`,f77:`f77`,f90:`fortran-free-form`,f95:`fortran-free-form`,fnl:`fennel`,fish:`fish`,ftl:`ftl`,tres:`gdresource`,res:`gdresource`,gd:`gdscript`,gdshader:`gdshader`,gs:`genie`,feature:`gherkin`,COMMIT_EDITMSG:`git-commit`,"git-rebase-todo":`git-rebase`,gjs:`glimmer-js`,gleam:`gleam`,gts:`glimmer-ts`,glsl:`glsl`,vert:`glsl`,frag:`glsl`,shader:`shaderlab`,gp:`gnuplot`,plt:`gnuplot`,gnuplot:`gnuplot`,go:`go`,graphql:`graphql`,gql:`graphql`,groovy:`groovy`,gvy:`groovy`,hack:`hack`,haml:`haml`,hbs:`handlebars`,handlebars:`handlebars`,hs:`haskell`,lhs:`haskell`,hx:`haxe`,hcl:`hcl`,hjson:`hjson`,hlsl:`hlsl`,fx:`hlsl`,html:`html`,htm:`html`,http:`http`,rest:`http`,hxml:`hxml`,hy:`hy`,imba:`imba`,ini:`ini`,cfg:`ini`,jade:`pug`,pug:`pug`,java:`java`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jinja:`jinja`,jinja2:`jinja`,j2:`jinja`,jison:`jison`,jl:`julia`,json:`json`,json5:`json5`,jsonc:`jsonc`,jsonl:`jsonl`,jsonnet:`jsonnet`,libsonnet:`jsonnet`,jssm:`jssm`,jsx:`jsx`,kt:`kotlin`,kts:`kts`,kql:`kusto`,tex:`tex`,ltx:`tex`,lean:`lean4`,less:`less`,liquid:`liquid`,lit:`lit`,ll:`llvm`,logo:`logo`,lua:`lua`,luau:`luau`,Makefile:`makefile`,mk:`makefile`,makefile:`makefile`,md:`markdown`,markdown:`markdown`,marko:`marko`,m:`wolfram`,mat:`matlab`,mdc:`mdc`,mdx:`mdx`,wiki:`wikitext`,mediawiki:`wikitext`,mmd:`mermaid`,mermaid:`mermaid`,mips:`mipsasm`,mojo:`mojo`,"🔥":`mojo`,move:`move`,nar:`narrat`,nf:`nextflow`,nim:`nim`,nims:`nim`,nimble:`nim`,nix:`nix`,nu:`nushell`,mm:`objective-cpp`,ml:`ocaml`,mli:`ocaml`,mll:`ocaml`,mly:`ocaml`,pas:`pascal`,p:`pascal`,pl:`prolog`,pm:`perl`,t:`perl`,raku:`raku`,p6:`raku`,pl6:`raku`,php:`php`,phtml:`php`,pls:`plsql`,sql:`sql`,po:`po`,polar:`polar`,pcss:`postcss`,pot:`pot`,potx:`potx`,pq:`powerquery`,pqm:`powerquery`,ps1:`powershell`,psm1:`powershell`,psd1:`powershell`,prisma:`prisma`,pro:`prolog`,P:`prolog`,properties:`properties`,proto:`protobuf`,pp:`puppet`,purs:`purescript`,py:`python`,pyw:`python`,pyi:`python`,qml:`qml`,qmldir:`qmldir`,qss:`qss`,r:`r`,R:`r`,rkt:`racket`,rktl:`racket`,razor:`razor`,cshtml:`razor`,rb:`ruby`,rbw:`ruby`,reg:`reg`,regex:`regexp`,rel:`rel`,rs:`rust`,rst:`rst`,rake:`ruby`,gemspec:`ruby`,jbuilder:`ruby`,builder:`ruby`,rabl:`ruby`,arb:`ruby`,ru:`ruby`,podspec:`ruby`,Gemfile:`ruby`,Rakefile:`ruby`,Guardfile:`ruby`,Capfile:`ruby`,Berksfile:`ruby`,Brewfile:`ruby`,Vagrantfile:`ruby`,Thorfile:`ruby`,Appraisals:`ruby`,Dangerfile:`ruby`,sas:`sas`,sass:`sass`,scala:`scala`,sc:`scala`,scm:`scheme`,ss:`scheme`,sld:`scheme`,scss:`scss`,sdbl:`sdbl`,shadergraph:`shader`,st:`smalltalk`,sol:`solidity`,sparql:`sparql`,rq:`sparql`,spl:`splunk`,config:`ssh-config`,do:`stata`,ado:`stata`,dta:`stata`,styl:`stylus`,stylus:`stylus`,svelte:`svelte`,swift:`swift`,sv:`system-verilog`,svh:`system-verilog`,service:`systemd`,socket:`systemd`,device:`systemd`,timer:`systemd`,talon:`talonscript`,tasl:`tasl`,tcl:`tcl`,templ:`templ`,tf:`tf`,tfvars:`tfvars`,toml:`toml`,ts:`typescript`,mts:`typescript`,cts:`typescript`,tsp:`typespec`,tsv:`tsv`,tsx:`tsx`,ttl:`turtle`,twig:`twig`,typ:`typst`,vv:`v`,vala:`vala`,vapi:`vala`,vb:`vb`,vbs:`vb`,bas:`vb`,vh:`verilog`,vhd:`vhdl`,vhdl:`vhdl`,vim:`vimscript`,vue:`vue`,"vine.ts":`vue-vine`,vy:`vyper`,wasm:`wasm`,wat:`wasm`,wy:`文言`,wgsl:`wgsl`,wit:`wit`,wl:`wolfram`,nb:`wolfram`,xml:`xml`,xsl:`xsl`,xslt:`xsl`,yaml:`yaml`,yml:`yml`,zs:`zenscript`,zig:`zig`,zsh:`zsh`,sty:`tex`};function W7(e){if(H7.has(e))return H7.get(e)??`text`;if(U7[e]!=null)return U7[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(H7.has(t[1]))return H7.get(t[1])??`text`;if(U7[t[1]]!=null)return U7[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return H7.has(n)?H7.get(n)??`text`:U7[n]??`text`}function G7(){return got}function K7(){return Object.fromEntries(H7)}function _ot(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:z7(t),preferredHighlighter:n}}function vot(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function yot(e,t,n){let r=typeof n.lineInfo==`function`?n.lineInfo(t):n.lineInfo[t-1];if(r==null){let r=`processLine: line ${t}, contains no state.lineInfo`;throw console.error(r,{node:e,line:t,state:n}),Error(r)}return e.tagName=`div`,e.properties[`data-line`]=r.lineNumber,e.properties[`data-alt-line`]=r.altLineNumber,e.properties[`data-line-type`]=r.type,e.properties[`data-line-index`]=r.lineIndex,e.children.length===0&&e.children.push(C4(`
1185
- `)),e}var q7=Symbol(`no-token`),J7=Symbol(`multiple-tokens`);function Y7(e){let t=bot(e);if(t!=null)return t;let n=q7,r=[],i=[],a,o=()=>{if(i.length===0||a==null){i=[],a=void 0;return}if(i.length===1){let e=i[0];if(e?.type===`element`){xot(e,a);for(let t of e.children)X7(t)}else X7(e);r.push(e),i=[],a=void 0;return}for(let e of i)X7(e);r.push(w4({tagName:`span`,properties:{"data-char":a},children:i})),i=[],a=void 0},s=e=>{if(e!==q7){if(e===J7){n=J7;return}if(n===q7){n=e;return}n!==e&&(n=J7)}};for(let t of e.children){let e=t.type===`element`?Y7(t):q7;if(s(e),typeof e!=`number`){o(),r.push(t);continue}a!=null&&a!==e&&o(),a??=e,i.push(t)}return o(),e.children=r,n}function bot(e){let t=e.properties[`data-char`];if(typeof t==`number`)return t}function X7(e){if(e.type===`element`){e.properties[`data-char`]=void 0;for(let t of e.children)X7(t)}}function xot(e,t){e.properties[`data-char`]=t}function Sot(e={}){let{classPrefix:t=`__shiki_`,classSuffix:n=``,classReplacer:r=e=>e}=e,i=new Map;function a(e){return Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function o(e){let o=typeof e==`string`?e:a(e),s=t+Cot(o)+n;return s=r(s),i.has(s)||i.set(s,typeof e==`string`?e:{...e}),s}return{name:`@shikijs/transformers:style-to-class`,pre(e){if(!e.properties.style)return;let t=o(e.properties.style);delete e.properties.style,this.addClassToHast(e,t)},tokens(e){for(let t of e)for(let e of t){if(!e.htmlStyle)continue;let t=o(e.htmlStyle);e.htmlStyle={},e.htmlAttrs||={},e.htmlAttrs.class?e.htmlAttrs.class+=` ${t}`:e.htmlAttrs.class=t}},getClassRegistry(){return i},getCSS(){let e=``;for(let[t,n]of i.entries())e+=`.${t}{${typeof n==`string`?n:a(n)}}`;return e},clearRegistry(){i.clear()}}}function Cot(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0,i;t<e.length;t++)i=e.charCodeAt(t),n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&r)+(n>>>0)).toString(36).slice(0,6)}function Z7(e=!1,t=!1){let n={lineInfo:[]},r=[{line(e){return delete e.properties.class,e},pre(t){let r=ret(t),i=[];if(r!=null){let t=1;for(let a of r.children)a.type===`element`&&(e&&Y7(a),i.push(yot(a,t,n)),t++);r.children=i}return t},...e?{tokens(e){for(let t of e){let e=0;for(let n of t){let t=n;t.__lineChar??=e,e+=n.content.length}}},preprocess(e,t){t.mergeWhitespaces=`never`},span(e,t,n,r,i){if(i?.offset!=null&&i.content!=null){let t=i.__lineChar;return t!=null&&(e.properties[`data-char`]=t),e}return e}}:null}];return t&&r.push(wot,Q7),e&&r.push({line:e=>(e.type===`element`&&e.children.length===0&&e.children.push({type:`element`,tagName:`br`,properties:{},children:[]}),e)}),{state:n,transformers:r,toClass:Q7}}var Q7=Sot({classPrefix:`hl-`}),wot={name:`token-style-normalizer`,tokens(e){for(let t of e)for(let e of t){if(e.htmlStyle!=null)continue;let t={};e.color!=null&&(t.color=e.color),e.bgColor!=null&&(t[`background-color`]=e.bgColor),e.fontStyle!=null&&e.fontStyle!==0&&(e.fontStyle&1&&(t[`font-style`]=`italic`),e.fontStyle&2&&(t[`font-weight`]=`bold`),e.fontStyle&4&&(t[`text-decoration`]=`underline`)),Object.keys(t).length>0&&(e.htmlStyle=t)}}};function $7(e){return`--${e===`token`?`diffs-token`:`diffs`}-`}var Tot=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,Eot=/^0(?:\.0+)?%?$/;function Dot(e){let t=e.indexOf(`(`);if(t<=0||!e.endsWith(`)`))return;let n=e.slice(0,t).trim();if(!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(n))return;let r=e.slice(t+1,-1).trim();if(r.length===0)return;let i=r.lastIndexOf(`/`);if(i!==-1)return r.slice(i+1).trim();if(/^(?:rgba|hsla)$/i.test(n)){let e=r.split(`,`);if(e.length===4)return e[3]?.trim()}}function Oot(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(e.trim());if(t==null)return null;let n=t[1],r,i=1;return n.length===3?r=n.split(``).map(e=>e+e).join(``):n.length===6?r=n:(r=n.slice(0,6),i=parseInt(n.slice(6,8),16)/255),[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16),i]}function e9(e){if(e==null)return null;let t=Oot(e);if(t==null)return null;let n=t[0]/255,r=t[1]/255,i=t[2]/255,a=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return .2126*a(n)+.7152*a(r)+.0722*a(i)}function t9(e){if(e==null)return!1;let t=e.trim().toLowerCase();if(t===`transparent`||Tot.test(t))return!0;let n=Dot(t);return n!=null&&Eot.test(n)}function kot(e,t,n){if(t==null||n==null)return!1;let r=e9(e),i=e9(t),a=e9(n);return r==null||i==null||a==null?!1:Math.abs(r-a)<Math.abs(r-i)}var n9=new WeakMap;function r9(e){let t=n9.get(e);if(t!=null)return t;let n=e.colors??{},r={...n},i=n[`editor.background`]??e.bg,a=n[`editor.foreground`]??e.fg,o=n[`sideBar.background`]??i,s=n[`sideBar.foreground`]??a;i9(r,`editor.background`,i),i9(r,`editor.foreground`,a),i9(r,`sideBar.background`,o),i9(r,`sideBar.foreground`,s),i9(r,`input.background`,n[`input.background`]??o),i9(r,`sideBarSectionHeader.foreground`,n[`sideBarSectionHeader.foreground`]??s),i9(r,`list.activeSelectionForeground`,n[`list.activeSelectionForeground`]??s),i9(r,`gitDecoration.addedResourceForeground`,a9(n[`gitDecoration.addedResourceForeground`],n[`terminal.ansiGreen`],n[`editorGutter.addedBackground`])),i9(r,`gitDecoration.modifiedResourceForeground`,a9(n[`gitDecoration.modifiedResourceForeground`],n[`terminal.ansiBlue`],n[`editorGutter.modifiedBackground`])),i9(r,`gitDecoration.deletedResourceForeground`,a9(n[`gitDecoration.deletedResourceForeground`],n[`terminal.ansiRed`],n[`editorGutter.deletedBackground`]));let c=(t9(n[`list.focusOutline`])?void 0:n[`list.focusOutline`])??(t9(n.focusBorder)?void 0:n.focusBorder);c==null?delete r[`list.focusOutline`]:r[`list.focusOutline`]=c;let l=n[`list.hoverBackground`];l!=null&&(Aot(l,o)||kot(l,o,s))&&delete r[`list.hoverBackground`];let u=Object.freeze({...e,colors:Object.freeze(r)});return n9.set(e,u),u}function i9(e,t,n){n!=null&&n!==``&&(e[t]=n)}function a9(...e){for(let t of e)if(t!=null&&t!==``)return t}function Aot(e,t){return t!=null&&e.toLowerCase()===t.toLowerCase()}function o9({theme:e=B2,highlighter:t,prefix:n}){let r=``;if(typeof e==`string`){let i=t.getTheme(e),a=r9(i);r+=`color:${a.fg};`,r+=`background-color:${a.bg};`,r+=`${$7(`global`)}fg:${a.fg};`,r+=`${$7(`global`)}bg:${a.bg};`,r+=s9(i,n)}else{let n=t.getTheme(e.dark),i=r9(n);r+=`${$7(`global`)}dark:${i.fg};`,r+=`${$7(`global`)}dark-bg:${i.bg};`,r+=s9(n,`dark`),n=t.getTheme(e.light),i=r9(n),r+=`${$7(`global`)}light:${i.fg};`,r+=`${$7(`global`)}light-bg:${i.bg};`,r+=s9(n,`light`)}return r}function s9(e,t){t=t==null?``:`${t}-`;let n=``,r=e.colors?.[`gitDecoration.addedResourceForeground`]??e.colors?.[`terminal.ansiGreen`];r!=null&&(n+=`${$7(`global`)}${t}addition-color:${r};`);let i=e.colors?.[`gitDecoration.deletedResourceForeground`]??e.colors?.[`terminal.ansiRed`];i!=null&&(n+=`${$7(`global`)}${t}deletion-color:${i};`);let a=e.colors?.[`gitDecoration.modifiedResourceForeground`]??e.colors?.[`terminal.ansiBlue`];return a!=null&&(n+=`${$7(`global`)}${t}modified-color:${a};`),n}function c9(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t.children;t=`children`in t?t.children[0]:null}throw console.error(e),Error(`getLineNodes: Unable to find children`)}var l9=10,u9=13,jot=4,Mot=40;function Not(e){let t=[0],n=e.indexOf(`\r`),r=e.indexOf(`
1184
+ \v\f…\u2028\u2029])`),t));else if(c===`posix`)if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${U5(e.codePointAt(0)-1)}${U5(e.codePointAt(2)+1)}-\u{10FFFF}`),n(g7(p7(`[${e}]`),t))}else n(g7(m7(p7(eat.get(u)),l),t));else if(c===`property`)e7.has(b5(u))||(e.key=`sc`);else if(c===`space`)n(h7(h5(`space`,{negate:l}),t));else if(c===`word`)n(g7(m7(p7(Q5),l),t));else throw Error(`Unexpected character set kind "${c}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`)if(!c.enable&&!c.disable)r();else{let e=d5({flags:c});e.body[0].body=o(),i(g7(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&n5(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(W5`Uses "\K" in a way that's unsupported`);let o=f5({behind:!0});o.body[0].body=a(),i(g7(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(g7(f5({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=d5();t.body[0].body.push(e.body),e.body=g7(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=u7(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(W5`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!f7(n)&&(n=s7(n,t),e.ref=n)}},iat={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=h7(o7(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&J5(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=J5(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=q5(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?o7(0):a7(o,r.groupOriginByCopy,null),l=c;if(!s){let e=c7(cat(o,e=>e.type===`Group`&&!!e.flags)),t=e?q5(r.globalFlags,e):r.globalFlags;oat(t,r.currentFlags)||(l=d5({flags:lat(t)}),l.body[0].body.push(c))}n(g7(l,t),{traverse:!s})}},aat={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>sat(t,e));i.length?i.length>1?n(g7(d5({atomic:!0,body:i.reverse().map(e=>i5({body:[o5(e.number)]}))}),t)):e.ref=i[0].number:n(g7(f5({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=s5();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function i7(e){C5(e,{"*"({node:e,parent:t}){e.parent=t}})}function oat(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function sat(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=l7(n.parent);for(let r of t){if(r===n)break;if(r===e||d7(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function a7(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=a7(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function o7(e){let t=m5(e);return t.isRecursive=!0,t}function cat(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function s7(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function c7(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function lat({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function l7(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function u7(e){let t=e.find(e=>e.kind===`search_start`||fat(e,{negate:!1})||!uat(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=u7(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function d7(e,t){let n=l7(e)??[];for(let e of n)if(e===t||d7(e,t))return!0;return!1}function uat({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function dat(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function fat(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&n5(e.body[0],{type:`Assertion`,kind:`search_start`})}function f7(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function p7(e,t){let n=r5(e,{...t,unicodePropertyMap:e7}).body;return n.length>1||n[0].body.length>1?d5({body:n}):n[0].body[0]}function m7(e,t){return e.negate=t,e}function h7(e,t){return e.parent=t,e}function g7(e,t){return i7(e),e.parent=t,e}function pat(e,t){let n=Z5(t),r=Y5(n.target,`ES2024`),i=Y5(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];C5(e,mat,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||o)&&!s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,qit(hat[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&J5(f._captureTransfers,e.transferTo,[]).push(t)}),f}var mat={"*":{enter({node:e},t){if(x7(e)){let n=t.getCurrentModI();t.pushModI(e.flags?q5({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){x7(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){v7(U5(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),y7(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&r7.has(e.value)&&t.setHasCasedChar()}},hat={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?W5`\B`:W5`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=U5(e),r=b7(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&v7(n)){let e=$5(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);G5.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(S7)&&(o=[c5(45),...o.filter(e=>!S7(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||G5.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=d5(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=i5({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(G5.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=b7(n,i),o=b7(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&bat(y7(e)).forEach(e=>{s.add(Array.isArray(e)?`${b7(e[0],i)}-${b7(e[1],i)}`:b7(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:W5`[^\n]`;if(e===`digit`)return t?W5`\D`:W5`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&r7.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?W5`\P`:W5`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?W5`\W`:W5`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=q5(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${xat(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+Sat(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:W5`\g<${t}&R=${r}>`}},gat=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),_at=new Set([`-`,`\\`,`]`,`^`,`[`]),vat=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),_7=new Map([[9,W5`\t`],[10,W5`\n`],[11,W5`\v`],[12,W5`\f`],[13,W5`\r`],[8232,W5`\u2028`],[8233,W5`\u2029`],[65279,W5`\uFEFF`]]),yat=/^\p{Cased}$/u;function v7(e){return yat.test(e)}function y7(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=U5(e);if(!v7(t))continue;let o=$5(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function b7(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(_7.has(e))return _7.get(e);if(e<32||e>126&&e<160||e>262143||t&&Cat(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?vat:_at:gat,a=U5(e);return(i.has(a)?`\\`:``)+a}function bat(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function xat(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function Sat({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function x7({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function Cat(e){return e>47&&e<58}function S7({type:e,value:t}){return e===`Character`&&t===45}var wat=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=Eat(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(Tat(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=Dat(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function Tat(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function Eat(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)J5(n,t,{}).transferTo=e;return n}function Dat(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function Oat(e,t){let n=kat(e,t);return n.options?new wat(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function kat(e,t){let n=Z5(t),r=nat(r5(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:e7}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=pat(r,n),a=Git(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Uit(Wit(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function Aat(e,t){return Oat(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function jat(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>Aat(e,{target:t.target}),{createScanner(e){return new qrt(e,t)},createString(e){return{content:e}}}}async function C7(e){if(z3())throw Error(`resolveLanguage("${e}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);let t=I3.get(e);if(t!=null)return t;try{let t=Ltt.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(U3,e)&&(t=U3[e]),t==null)throw Error(`resolveLanguage: "${e}" not found in bundled or custom languages`);let n=t().then(({default:t})=>{let n={name:e,data:t};return F3.has(e)||F3.set(e,n),n});return I3.set(e,n),await n}finally{I3.delete(e)}}function w7(e){return F3.get(e)??C7(e)}var T7=new Set;function E7(e){let t=[],n=new Set;for(let r of Mat(e.themes)){let e=D7(r)?r.getThemes():[r];for(let r of e){if(n.has(r.name))throw Error(`Theme collection already contains theme "${r.name}"`);n.add(r.name),t.push(r)}}let r=Object.freeze([...t]),i=Object.freeze(r.filter(e=>e.colorScheme===`light`)),a=Object.freeze(r.filter(e=>e.colorScheme===`dark`)),o=new Map(r.map(e=>[e.name,e])),s=Object.freeze(r.map(e=>e.name)),c=Object.freeze(i.map(e=>e.name)),l=Object.freeze(a.map(e=>e.name));function u(e){if(e==null)return r;let{colorScheme:t,collection:n}=e;return n==null?t===`light`?i:t===`dark`?a:r:r.filter(e=>e.collection===n?t==null||e.colorScheme===t:!1)}return{getTheme(e){return o.get(e)},getThemes(e){return u(e)},getThemeNames(e){return e?.collection==null?e?.colorScheme===`light`?c:e?.colorScheme===`dark`?l:s:u(e).map(e=>e.name)},hasTheme(e){return o.has(e)},orderBy(e){return E7({themes:r.map((e,t)=>({descriptor:e,index:t})).sort((t,n)=>{let r=e(t.descriptor,n.descriptor);return r===0?t.index-n.index:r}).map(e=>e.descriptor)})},pick(e){let t=[],n=new Set;for(let r of e){if(n.has(r))throw Error(`Theme collection pick already includes theme "${r}"`);n.add(r);let e=o.get(r);if(e==null)throw Error(`Theme collection does not contain theme "${r}"`);t.push(e)}return E7({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function Mat(e){return Nat(e)?[e]:e}function Nat(e){return D7(e)||Pat(e)}function Pat(e){return typeof e.name==`string`&&typeof e.load==`function`}function D7(e){return typeof e.getThemes==`function`}function O7(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var Fat=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},Iat=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},Lat=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function Rat(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new Fat(t);e.set(t,n)}function a(t,n){return!e.has(t)&&(e.set(t,n),!0)}function o(t){return e.has(t)}function s(i){let a=t.get(i);if(a!==void 0)return Promise.resolve(a);let o=n.get(i);if(o!==void 0)return o;let s=e.get(i);if(s===void 0)return Promise.reject(new Iat(i));let c=r,l=s().then(e=>{let a=O7(e);return c===r&&t.set(i,a),n.get(i)===l&&n.delete(i),a}).catch(e=>{throw n.get(i)===l&&n.delete(i),e});return n.set(i,l),l}function c(e){return Promise.all(e.map(e=>s(e)))}function l(e,n){t.set(e,n)}function u(e){for(let[t,n]of e)l(t,n)}function d(e){return t.get(e)}function f(e){let n=[];for(let r of e){let e=t.get(r);if(e===void 0)throw new Lat(r);n.push(e)}return n}function p(e){return t.has(e)}function m(e){for(let n of e)if(!t.has(n))return!1;return!0}function h(e){let n=t.get(e);return n===void 0?s(e):n}function g(){r++,t.clear(),n.clear()}return{clearResolvedThemes:g,getResolvedOrResolveTheme:h,getResolvedTheme:d,getResolvedThemes:f,hasRegisteredTheme:o,hasResolvedTheme:p,hasResolvedThemes:m,registerTheme:i,registerThemeIfAbsent:a,resolveTheme:s,resolveThemes:c,seedResolvedTheme:l,seedResolvedThemes:u}}var k7=Rat();function A7(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=k7.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,k7.getResolvedTheme(n)??k7.seedResolvedTheme(n,e);T7.has(n)||(T7.add(n),t.loadThemeSync(e))}}function j7({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:zat(t)}}function zat(e){return async()=>s8(O7(await e()))}var Bat=`pierre`,Vat=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],M7=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],Hat=[...M7,...Vat],Uat=new Set(M7);function Wat(e){return Uat.has(e)?`light`:`dark`}var Gat={"pierre-dark":`Pierre Dark`,"pierre-dark-soft":`Pierre Dark Soft`,"pierre-dark-vibrant":`Pierre Dark Vibrant`,"pierre-dark-protanopia-deuteranopia":`Pierre Dark Protanopia & Deuteranopia`,"pierre-dark-tritanopia":`Pierre Dark Tritanopia`,"pierre-light":`Pierre Light`,"pierre-light-soft":`Pierre Light Soft`,"pierre-light-vibrant":`Pierre Light Vibrant`,"pierre-light-protanopia-deuteranopia":`Pierre Light Protanopia & Deuteranopia`,"pierre-light-tritanopia":`Pierre Light Tritanopia`},Kat={"pierre-dark":()=>N(()=>import(`./pierre-dark-CpLgRqie.js`),[]),"pierre-dark-soft":()=>N(()=>import(`./pierre-dark-soft-kZQmAZld.js`),[]),"pierre-dark-vibrant":()=>N(()=>import(`./pierre-dark-vibrant-CpQYzh95.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>N(()=>import(`./pierre-dark-protanopia-deuteranopia-B35FxJx-.js`),[]),"pierre-dark-tritanopia":()=>N(()=>import(`./pierre-dark-tritanopia-CpjhbsIL.js`),[]),"pierre-light":()=>N(()=>import(`./pierre-light-CoaEpmwp.js`),[]),"pierre-light-soft":()=>N(()=>import(`./pierre-light-soft-lWLdNTOI.js`),[]),"pierre-light-vibrant":()=>N(()=>import(`./pierre-light-vibrant-D80Fkn33.js`),[]),"pierre-light-protanopia-deuteranopia":()=>N(()=>import(`./pierre-light-protanopia-deuteranopia-0fSaH845.js`),[]),"pierre-light-tritanopia":()=>N(()=>import(`./pierre-light-tritanopia-CEbqgOJL.js`),[])};function qat(e){return j7({name:e,collection:Bat,colorScheme:Wat(e),displayName:Gat[e],load:Kat[e]})}var Jat=E7({themes:Hat.map(e=>qat(e))}),Yat=`shiki`,N7=[`ayu-light`,`catppuccin-latte`,`everforest-light`,`github-light`,`github-light-default`,`github-light-high-contrast`,`gruvbox-light-hard`,`gruvbox-light-medium`,`gruvbox-light-soft`,`horizon-bright`,`kanagawa-lotus`,`light-plus`,`material-theme-lighter`,`min-light`,`night-owl-light`,`one-light`,`rose-pine-dawn`,`slack-ochin`,`snazzy-light`,`solarized-light`,`vitesse-light`],Xat=`andromeeda.aurora-x.ayu-dark.ayu-mirage.catppuccin-frappe.catppuccin-macchiato.catppuccin-mocha.dark-plus.dracula.dracula-soft.everforest-dark.github-dark.github-dark-default.github-dark-dimmed.github-dark-high-contrast.gruvbox-dark-hard.gruvbox-dark-medium.gruvbox-dark-soft.horizon.houston.kanagawa-dragon.kanagawa-wave.laserwave.material-theme.material-theme-darker.material-theme-ocean.material-theme-palenight.min-dark.monokai.night-owl.nord.one-dark-pro.plastic.poimandres.red.rose-pine.rose-pine-moon.slack-dark.solarized-dark.synthwave-84.tokyo-night.vesper.vitesse-black.vitesse-dark`.split(`.`),Zat=new Set(N7);function Qat(e){return Zat.has(e)?`light`:`dark`}var $at={andromeeda:()=>N(()=>import(`./andromeeda-vGVdxbeo.js`),[]),"aurora-x":()=>N(()=>import(`./aurora-x-CDeNXAV0.js`),[]),"ayu-dark":()=>N(()=>import(`./ayu-dark-DluEY0Gj.js`),[]),"ayu-light":()=>N(()=>import(`./ayu-light-C3h-C4tm.js`),[]),"ayu-mirage":()=>N(()=>import(`./ayu-mirage-Bqwy1Gya.js`),[]),"catppuccin-frappe":()=>N(()=>import(`./catppuccin-frappe-3VR1Za6u.js`),[]),"catppuccin-latte":()=>N(()=>import(`./catppuccin-latte-DwIHMF0Q.js`),[]),"catppuccin-macchiato":()=>N(()=>import(`./catppuccin-macchiato-DYnBP6_5.js`),[]),"catppuccin-mocha":()=>N(()=>import(`./catppuccin-mocha-DYhrFGRu.js`),[]),"dark-plus":()=>N(()=>import(`./dark-plus-Cs2F2srj.js`),[]),dracula:()=>N(()=>import(`./dracula-BHWKrbxM.js`),[]),"dracula-soft":()=>N(()=>import(`./dracula-soft-5eyTD99u.js`),[]),"everforest-dark":()=>N(()=>import(`./everforest-dark-sB-x3p7T.js`),[]),"everforest-light":()=>N(()=>import(`./everforest-light-Df2xbC6M.js`),[]),"github-dark":()=>N(()=>import(`./github-dark-C-LZuMrd.js`),[]),"github-dark-default":()=>N(()=>import(`./github-dark-default-DXG-b-1a.js`),[]),"github-dark-dimmed":()=>N(()=>import(`./github-dark-dimmed-Bx1FflLF.js`),[]),"github-dark-high-contrast":()=>N(()=>import(`./github-dark-high-contrast-B_tTalzw.js`),[]),"github-light":()=>N(()=>import(`./github-light-EUqPIrTm.js`),[]),"github-light-default":()=>N(()=>import(`./github-light-default-BXViO-2h.js`),[]),"github-light-high-contrast":()=>N(()=>import(`./github-light-high-contrast-B68TUdTA.js`),[]),"gruvbox-dark-hard":()=>N(()=>import(`./gruvbox-dark-hard-C820rvS2.js`),[]),"gruvbox-dark-medium":()=>N(()=>import(`./gruvbox-dark-medium-BPjhmG05.js`),[]),"gruvbox-dark-soft":()=>N(()=>import(`./gruvbox-dark-soft-MrdJrrXF.js`),[]),"gruvbox-light-hard":()=>N(()=>import(`./gruvbox-light-hard-BC_s9l72.js`),[]),"gruvbox-light-medium":()=>N(()=>import(`./gruvbox-light-medium-BAWPOn9u.js`),[]),"gruvbox-light-soft":()=>N(()=>import(`./gruvbox-light-soft-BSMLrYjP.js`),[]),horizon:()=>N(()=>import(`./horizon-CE9ld1lL.js`),[]),"horizon-bright":()=>N(()=>import(`./horizon-bright-DSNQnXHK.js`),[]),houston:()=>N(()=>import(`./houston-CsvMBhTu.js`),[]),"kanagawa-dragon":()=>N(()=>import(`./kanagawa-dragon-CXtmUGW6.js`),[]),"kanagawa-lotus":()=>N(()=>import(`./kanagawa-lotus-BN08jTvb.js`),[]),"kanagawa-wave":()=>N(()=>import(`./kanagawa-wave-CTweb8Dz.js`),[]),laserwave:()=>N(()=>import(`./laserwave-C_8bwKvT.js`),[]),"light-plus":()=>N(()=>import(`./light-plus-DVQuIRkW.js`),[]),"material-theme":()=>N(()=>import(`./material-theme-Bm3Qr25_.js`),[]),"material-theme-darker":()=>N(()=>import(`./material-theme-darker-2IIEA8gg.js`),[]),"material-theme-lighter":()=>N(()=>import(`./material-theme-lighter-uhdI0v04.js`),[]),"material-theme-ocean":()=>N(()=>import(`./material-theme-ocean-CHQ94UKr.js`),[]),"material-theme-palenight":()=>N(()=>import(`./material-theme-palenight-B5W6OYN7.js`),[]),"min-dark":()=>N(()=>import(`./min-dark-BSWPekZh.js`),[]),"min-light":()=>N(()=>import(`./min-light-DDpmG2fV.js`),[]),monokai:()=>N(()=>import(`./monokai-CdkpiU2Y.js`),[]),"night-owl":()=>N(()=>import(`./night-owl-DhmEMT88.js`),[]),"night-owl-light":()=>N(()=>import(`./night-owl-light-eJ-hLW7d.js`),[]),nord:()=>N(()=>import(`./nord-Cb4Vim4T.js`),[]),"one-dark-pro":()=>N(()=>import(`./one-dark-pro-CLwyXe_n.js`),[]),"one-light":()=>N(()=>import(`./one-light-D7Lr4KcI.js`),[]),plastic:()=>N(()=>import(`./plastic-DQwYfKfQ.js`),[]),poimandres:()=>N(()=>import(`./poimandres-DRFjx7u4.js`),[]),red:()=>N(()=>import(`./red-CJ3rzSJv.js`),[]),"rose-pine":()=>N(()=>import(`./rose-pine-BthvhNj6.js`),[]),"rose-pine-dawn":()=>N(()=>import(`./rose-pine-dawn-Dg85fqjY.js`),[]),"rose-pine-moon":()=>N(()=>import(`./rose-pine-moon-hon4tzzS.js`),[]),"slack-dark":()=>N(()=>import(`./slack-dark-DnToyrRv.js`),[]),"slack-ochin":()=>N(()=>import(`./slack-ochin-B2OO5cIa.js`),[]),"snazzy-light":()=>N(()=>import(`./snazzy-light-4G7pJPwS.js`),[]),"solarized-dark":()=>N(()=>import(`./solarized-dark-DV17i1UV.js`),[]),"solarized-light":()=>N(()=>import(`./solarized-light-DSh2HLQt.js`),[]),"synthwave-84":()=>N(()=>import(`./synthwave-84-nFMaYfgc.js`),[]),"tokyo-night":()=>N(()=>import(`./tokyo-night-oM2G3aXe.js`),[]),vesper:()=>N(()=>import(`./vesper-DdrHHSXu.js`),[]),"vitesse-black":()=>N(()=>import(`./vitesse-black-fwtXNY1n.js`),[]),"vitesse-dark":()=>N(()=>import(`./vitesse-dark-BZCL-v6S.js`),[]),"vitesse-light":()=>N(()=>import(`./vitesse-light-VbXTXTou.js`),[])};function P7(e){return j7({name:e,collection:Yat,colorScheme:Qat(e),load:$at[e]})}var eot=E7({themes:Object.freeze([...N7.map(e=>P7(e)),...Xat.map(e=>P7(e))])});function F7(e){if(z3())throw Error(`Theme "${e}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);if(k7.hasRegisteredTheme(e))return;let t=eot.getTheme(e);if(t!=null){k7.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function I7(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function tot(e){F7(e);let t=await k7.resolveTheme(e);return I7(e,t),t}function not(e){return k7.getResolvedTheme(e)??tot(e)}var L7;async function R7({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){L7??=P8({themes:[],langs:[`text`],engine:n===`shiki-wasm`?e6(N(()=>import(`./wasm-BnjxR4X6.js`),[])):jat()});let r=iot(L7)?await L7:L7;L7=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=w7(e);`then`in t?i.push(t):R3(t,r)}let a=[];for(let t of e){let e=not(t);`then`in e?a.push(e):A7(e,L7)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{R3(e,r)}),Promise.all(a).then(e=>{A7(e,r)})]),r}function rot(){if(L7!=null&&!(`then`in L7))return L7}function iot(e=L7){return e!=null&&`then`in e}for(let e of Jat.getThemes())k7.registerThemeIfAbsent(e.name,e.load);function z7(e=z2){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function aot(e){for(let t of z7(e))if(!T7.has(t))return!1;return!0}function B7(e){return k7.hasResolvedThemes(e)}function V7(e,t){return J2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function oot(e,t){return e==null||t==null?e===t:e.startingLine===t.startingLine&&e.totalLines===t.totalLines&&e.bufferBefore===t.bufferBefore&&e.bufferAfter===t.bufferAfter}function sot(e){return C4({tagName:`div`,children:[C4({tagName:`div`,children:e.annotations?.map(e=>C4({tagName:`slot`,properties:{name:e}})),properties:{"data-annotation-content":``}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function cot(e){switch(e){case`file`:return`diffs-icon-file-code`;case`change`:return`diffs-icon-symbol-modified`;case`new`:return`diffs-icon-symbol-added`;case`deleted`:return`diffs-icon-symbol-deleted`;case`rename-pure`:case`rename-changed`:return`diffs-icon-symbol-moved`}}function lot({fileOrDiff:e,mode:t,stickyHeader:n}){let r=`type`in e?e:void 0,i={"data-diffs-header":t,"data-change-type":r?.type,"data-sticky":n?``:void 0};return C4({tagName:`div`,children:[t===`custom`?C4({tagName:`slot`,properties:{name:R2}}):uot({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[dot(r)]],properties:i})}function uot({name:e,prevName:t,iconType:n}){let r=[C4({tagName:`slot`,properties:{name:F2}}),w4({name:cot(n),properties:{"data-change-icon":n}})];return t!=null&&(r.push(C4({tagName:`div`,children:[C4({tagName:`bdi`,children:[S4(t)]})],properties:{"data-prev-name":``}})),r.push(w4({name:`diffs-icon-arrow-right-short`,properties:{"data-rename-icon":``}}))),r.push(C4({tagName:`div`,children:[C4({tagName:`bdi`,children:[S4(e)]})],properties:{"data-title":``}})),r.push(C4({tagName:`slot`,properties:{name:I2}})),C4({tagName:`div`,children:r,properties:{"data-header-content":``}})}function dot(e){let t=[];if(e!=null){let n=0,r=0;for(let t of e.hunks)n+=t.additionLines,r+=t.deletionLines;(r>0||n===0)&&t.push(C4({tagName:`span`,children:[S4(`-${r}`)],properties:{"data-deletions-count":``}})),(n>0||r===0)&&t.push(C4({tagName:`span`,children:[S4(`+${n}`)],properties:{"data-additions-count":``}}))}return t.push(C4({tagName:`slot`,properties:{name:L2}})),C4({tagName:`div`,children:t,properties:{"data-metadata":``}})}function fot(e){return C4({tagName:`pre`,properties:pot(e)})}function pot({diffIndicators:e,disableBackground:t,disableLineNumbers:n,overflow:r,split:i,totalLines:a,type:o,customProperties:s}){return{...s,"data-diff":o===`diff`?``:void 0,"data-file":o===`file`?``:void 0,"data-diff-type":o===`diff`?i?`split`:`single`:void 0,"data-overflow":r,"data-disable-line-numbers":n?``:void 0,"data-background":t?void 0:``,"data-indicators":e===`bars`||e===`classic`?e:void 0,style:`--diffs-min-number-column-width-default:${`${a}`.length}ch;`}}var H7=new Map,mot=0,U7={"1c":`1c`,abap:`abap`,as:`actionscript-3`,ada:`ada`,adb:`ada`,ads:`ada`,adoc:`asciidoc`,asciidoc:`asciidoc`,"component.html":`angular-html`,"component.ts":`angular-ts`,conf:`nginx`,htaccess:`apache`,cls:`tex`,trigger:`apex`,apl:`apl`,applescript:`applescript`,scpt:`applescript`,ara:`ara`,asm:`asm`,s:`riscv`,astro:`astro`,awk:`awk`,bal:`ballerina`,sh:`zsh`,bash:`zsh`,bat:`cmd`,cmd:`cmd`,be:`berry`,beancount:`beancount`,bib:`bibtex`,bicep:`bicep`,"blade.php":`blade`,bsl:`bsl`,c:`c`,h:`objective-cpp`,cs:`csharp`,cpp:`cpp`,hpp:`cpp`,cc:`cpp`,cxx:`cpp`,hh:`cpp`,cdc:`cdc`,cairo:`cairo`,clar:`clarity`,clj:`clojure`,cljs:`clojure`,cljc:`clojure`,soy:`soy`,cmake:`cmake`,"CMakeLists.txt":`cmake`,cob:`cobol`,cbl:`cobol`,cobol:`cobol`,CODEOWNERS:`codeowners`,ql:`ql`,coffee:`coffeescript`,lisp:`lisp`,cl:`lisp`,lsp:`lisp`,log:`log`,v:`verilog`,cql:`cql`,cr:`crystal`,css:`css`,csv:`csv`,cue:`cue`,cypher:`cypher`,cyp:`cypher`,d:`d`,dart:`dart`,dax:`dax`,desktop:`desktop`,diff:`diff`,patch:`diff`,Dockerfile:`dockerfile`,dockerfile:`dockerfile`,env:`dotenv`,dm:`dream-maker`,edge:`edge`,el:`emacs-lisp`,ex:`elixir`,exs:`elixir`,elm:`elm`,erb:`erb`,erl:`erlang`,hrl:`erlang`,f:`fortran-fixed-form`,for:`fortran-fixed-form`,fs:`fsharp`,fsi:`fsharp`,fsx:`fsharp`,f03:`f03`,f08:`f08`,f18:`f18`,f77:`f77`,f90:`fortran-free-form`,f95:`fortran-free-form`,fnl:`fennel`,fish:`fish`,ftl:`ftl`,tres:`gdresource`,res:`gdresource`,gd:`gdscript`,gdshader:`gdshader`,gs:`genie`,feature:`gherkin`,COMMIT_EDITMSG:`git-commit`,"git-rebase-todo":`git-rebase`,gjs:`glimmer-js`,gleam:`gleam`,gts:`glimmer-ts`,glsl:`glsl`,vert:`glsl`,frag:`glsl`,shader:`shaderlab`,gp:`gnuplot`,plt:`gnuplot`,gnuplot:`gnuplot`,go:`go`,graphql:`graphql`,gql:`graphql`,groovy:`groovy`,gvy:`groovy`,hack:`hack`,haml:`haml`,hbs:`handlebars`,handlebars:`handlebars`,hs:`haskell`,lhs:`haskell`,hx:`haxe`,hcl:`hcl`,hjson:`hjson`,hlsl:`hlsl`,fx:`hlsl`,html:`html`,htm:`html`,http:`http`,rest:`http`,hxml:`hxml`,hy:`hy`,imba:`imba`,ini:`ini`,cfg:`ini`,jade:`pug`,pug:`pug`,java:`java`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jinja:`jinja`,jinja2:`jinja`,j2:`jinja`,jison:`jison`,jl:`julia`,json:`json`,json5:`json5`,jsonc:`jsonc`,jsonl:`jsonl`,jsonnet:`jsonnet`,libsonnet:`jsonnet`,jssm:`jssm`,jsx:`jsx`,kt:`kotlin`,kts:`kts`,kql:`kusto`,tex:`tex`,ltx:`tex`,lean:`lean4`,less:`less`,liquid:`liquid`,lit:`lit`,ll:`llvm`,logo:`logo`,lua:`lua`,luau:`luau`,Makefile:`makefile`,mk:`makefile`,makefile:`makefile`,md:`markdown`,markdown:`markdown`,marko:`marko`,m:`wolfram`,mat:`matlab`,mdc:`mdc`,mdx:`mdx`,wiki:`wikitext`,mediawiki:`wikitext`,mmd:`mermaid`,mermaid:`mermaid`,mips:`mipsasm`,mojo:`mojo`,"🔥":`mojo`,move:`move`,nar:`narrat`,nf:`nextflow`,nim:`nim`,nims:`nim`,nimble:`nim`,nix:`nix`,nu:`nushell`,mm:`objective-cpp`,ml:`ocaml`,mli:`ocaml`,mll:`ocaml`,mly:`ocaml`,pas:`pascal`,p:`pascal`,pl:`prolog`,pm:`perl`,t:`perl`,raku:`raku`,p6:`raku`,pl6:`raku`,php:`php`,phtml:`php`,pls:`plsql`,sql:`sql`,po:`po`,polar:`polar`,pcss:`postcss`,pot:`pot`,potx:`potx`,pq:`powerquery`,pqm:`powerquery`,ps1:`powershell`,psm1:`powershell`,psd1:`powershell`,prisma:`prisma`,pro:`prolog`,P:`prolog`,properties:`properties`,proto:`protobuf`,pp:`puppet`,purs:`purescript`,py:`python`,pyw:`python`,pyi:`python`,qml:`qml`,qmldir:`qmldir`,qss:`qss`,r:`r`,R:`r`,rkt:`racket`,rktl:`racket`,razor:`razor`,cshtml:`razor`,rb:`ruby`,rbw:`ruby`,reg:`reg`,regex:`regexp`,rel:`rel`,rs:`rust`,rst:`rst`,rake:`ruby`,gemspec:`ruby`,jbuilder:`ruby`,builder:`ruby`,rabl:`ruby`,arb:`ruby`,ru:`ruby`,podspec:`ruby`,Gemfile:`ruby`,Rakefile:`ruby`,Guardfile:`ruby`,Capfile:`ruby`,Berksfile:`ruby`,Brewfile:`ruby`,Vagrantfile:`ruby`,Thorfile:`ruby`,Appraisals:`ruby`,Dangerfile:`ruby`,sas:`sas`,sass:`sass`,scala:`scala`,sc:`scala`,scm:`scheme`,ss:`scheme`,sld:`scheme`,scss:`scss`,sdbl:`sdbl`,shadergraph:`shader`,st:`smalltalk`,sol:`solidity`,sparql:`sparql`,rq:`sparql`,spl:`splunk`,config:`ssh-config`,do:`stata`,ado:`stata`,dta:`stata`,styl:`stylus`,stylus:`stylus`,svelte:`svelte`,swift:`swift`,sv:`system-verilog`,svh:`system-verilog`,service:`systemd`,socket:`systemd`,device:`systemd`,timer:`systemd`,talon:`talonscript`,tasl:`tasl`,tcl:`tcl`,templ:`templ`,tf:`tf`,tfvars:`tfvars`,toml:`toml`,ts:`typescript`,mts:`typescript`,cts:`typescript`,tsp:`typespec`,tsv:`tsv`,tsx:`tsx`,ttl:`turtle`,twig:`twig`,typ:`typst`,vv:`v`,vala:`vala`,vapi:`vala`,vb:`vb`,vbs:`vb`,bas:`vb`,vh:`verilog`,vhd:`vhdl`,vhdl:`vhdl`,vim:`vimscript`,vue:`vue`,"vine.ts":`vue-vine`,vy:`vyper`,wasm:`wasm`,wat:`wasm`,wy:`文言`,wgsl:`wgsl`,wit:`wit`,wl:`wolfram`,nb:`wolfram`,xml:`xml`,xsl:`xsl`,xslt:`xsl`,yaml:`yaml`,yml:`yml`,zs:`zenscript`,zig:`zig`,zsh:`zsh`,sty:`tex`};function W7(e){if(H7.has(e))return H7.get(e)??`text`;if(U7[e]!=null)return U7[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(H7.has(t[1]))return H7.get(t[1])??`text`;if(U7[t[1]]!=null)return U7[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return H7.has(n)?H7.get(n)??`text`:U7[n]??`text`}function G7(){return mot}function K7(){return Object.fromEntries(H7)}function hot(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:z7(t),preferredHighlighter:n}}function got(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function _ot(e,t,n){let r=typeof n.lineInfo==`function`?n.lineInfo(t):n.lineInfo[t-1];if(r==null){let r=`processLine: line ${t}, contains no state.lineInfo`;throw console.error(r,{node:e,line:t,state:n}),Error(r)}return e.tagName=`div`,e.properties[`data-line`]=r.lineNumber,e.properties[`data-alt-line`]=r.altLineNumber,e.properties[`data-line-type`]=r.type,e.properties[`data-line-index`]=r.lineIndex,e.children.length===0&&e.children.push(S4(`
1185
+ `)),e}var q7=Symbol(`no-token`),J7=Symbol(`multiple-tokens`);function Y7(e){let t=vot(e);if(t!=null)return t;let n=q7,r=[],i=[],a,o=()=>{if(i.length===0||a==null){i=[],a=void 0;return}if(i.length===1){let e=i[0];if(e?.type===`element`){yot(e,a);for(let t of e.children)X7(t)}else X7(e);r.push(e),i=[],a=void 0;return}for(let e of i)X7(e);r.push(C4({tagName:`span`,properties:{"data-char":a},children:i})),i=[],a=void 0},s=e=>{if(e!==q7){if(e===J7){n=J7;return}if(n===q7){n=e;return}n!==e&&(n=J7)}};for(let t of e.children){let e=t.type===`element`?Y7(t):q7;if(s(e),typeof e!=`number`){o(),r.push(t);continue}a!=null&&a!==e&&o(),a??=e,i.push(t)}return o(),e.children=r,n}function vot(e){let t=e.properties[`data-char`];if(typeof t==`number`)return t}function X7(e){if(e.type===`element`){e.properties[`data-char`]=void 0;for(let t of e.children)X7(t)}}function yot(e,t){e.properties[`data-char`]=t}function bot(e={}){let{classPrefix:t=`__shiki_`,classSuffix:n=``,classReplacer:r=e=>e}=e,i=new Map;function a(e){return Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function o(e){let o=typeof e==`string`?e:a(e),s=t+xot(o)+n;return s=r(s),i.has(s)||i.set(s,typeof e==`string`?e:{...e}),s}return{name:`@shikijs/transformers:style-to-class`,pre(e){if(!e.properties.style)return;let t=o(e.properties.style);delete e.properties.style,this.addClassToHast(e,t)},tokens(e){for(let t of e)for(let e of t){if(!e.htmlStyle)continue;let t=o(e.htmlStyle);e.htmlStyle={},e.htmlAttrs||={},e.htmlAttrs.class?e.htmlAttrs.class+=` ${t}`:e.htmlAttrs.class=t}},getClassRegistry(){return i},getCSS(){let e=``;for(let[t,n]of i.entries())e+=`.${t}{${typeof n==`string`?n:a(n)}}`;return e},clearRegistry(){i.clear()}}}function xot(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0,i;t<e.length;t++)i=e.charCodeAt(t),n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&r)+(n>>>0)).toString(36).slice(0,6)}function Z7(e=!1,t=!1){let n={lineInfo:[]},r=[{line(e){return delete e.properties.class,e},pre(t){let r=net(t),i=[];if(r!=null){let t=1;for(let a of r.children)a.type===`element`&&(e&&Y7(a),i.push(_ot(a,t,n)),t++);r.children=i}return t},...e?{tokens(e){for(let t of e){let e=0;for(let n of t){let t=n;t.__lineChar??=e,e+=n.content.length}}},preprocess(e,t){t.mergeWhitespaces=`never`},span(e,t,n,r,i){if(i?.offset!=null&&i.content!=null){let t=i.__lineChar;return t!=null&&(e.properties[`data-char`]=t),e}return e}}:null}];return t&&r.push(Sot,Q7),e&&r.push({line:e=>(e.type===`element`&&e.children.length===0&&e.children.push({type:`element`,tagName:`br`,properties:{},children:[]}),e)}),{state:n,transformers:r,toClass:Q7}}var Q7=bot({classPrefix:`hl-`}),Sot={name:`token-style-normalizer`,tokens(e){for(let t of e)for(let e of t){if(e.htmlStyle!=null)continue;let t={};e.color!=null&&(t.color=e.color),e.bgColor!=null&&(t[`background-color`]=e.bgColor),e.fontStyle!=null&&e.fontStyle!==0&&(e.fontStyle&1&&(t[`font-style`]=`italic`),e.fontStyle&2&&(t[`font-weight`]=`bold`),e.fontStyle&4&&(t[`text-decoration`]=`underline`)),Object.keys(t).length>0&&(e.htmlStyle=t)}}};function $7(e){return`--${e===`token`?`diffs-token`:`diffs`}-`}var Cot=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,wot=/^0(?:\.0+)?%?$/;function Tot(e){let t=e.indexOf(`(`);if(t<=0||!e.endsWith(`)`))return;let n=e.slice(0,t).trim();if(!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(n))return;let r=e.slice(t+1,-1).trim();if(r.length===0)return;let i=r.lastIndexOf(`/`);if(i!==-1)return r.slice(i+1).trim();if(/^(?:rgba|hsla)$/i.test(n)){let e=r.split(`,`);if(e.length===4)return e[3]?.trim()}}function Eot(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(e.trim());if(t==null)return null;let n=t[1],r,i=1;return n.length===3?r=n.split(``).map(e=>e+e).join(``):n.length===6?r=n:(r=n.slice(0,6),i=parseInt(n.slice(6,8),16)/255),[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16),i]}function e9(e){if(e==null)return null;let t=Eot(e);if(t==null)return null;let n=t[0]/255,r=t[1]/255,i=t[2]/255,a=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return .2126*a(n)+.7152*a(r)+.0722*a(i)}function t9(e){if(e==null)return!1;let t=e.trim().toLowerCase();if(t===`transparent`||Cot.test(t))return!0;let n=Tot(t);return n!=null&&wot.test(n)}function Dot(e,t,n){if(t==null||n==null)return!1;let r=e9(e),i=e9(t),a=e9(n);return r==null||i==null||a==null?!1:Math.abs(r-a)<Math.abs(r-i)}var n9=new WeakMap;function r9(e){let t=n9.get(e);if(t!=null)return t;let n=e.colors??{},r={...n},i=n[`editor.background`]??e.bg,a=n[`editor.foreground`]??e.fg,o=n[`sideBar.background`]??i,s=n[`sideBar.foreground`]??a;i9(r,`editor.background`,i),i9(r,`editor.foreground`,a),i9(r,`sideBar.background`,o),i9(r,`sideBar.foreground`,s),i9(r,`input.background`,n[`input.background`]??o),i9(r,`sideBarSectionHeader.foreground`,n[`sideBarSectionHeader.foreground`]??s),i9(r,`list.activeSelectionForeground`,n[`list.activeSelectionForeground`]??s),i9(r,`gitDecoration.addedResourceForeground`,a9(n[`gitDecoration.addedResourceForeground`],n[`terminal.ansiGreen`],n[`editorGutter.addedBackground`])),i9(r,`gitDecoration.modifiedResourceForeground`,a9(n[`gitDecoration.modifiedResourceForeground`],n[`terminal.ansiBlue`],n[`editorGutter.modifiedBackground`])),i9(r,`gitDecoration.deletedResourceForeground`,a9(n[`gitDecoration.deletedResourceForeground`],n[`terminal.ansiRed`],n[`editorGutter.deletedBackground`]));let c=(t9(n[`list.focusOutline`])?void 0:n[`list.focusOutline`])??(t9(n.focusBorder)?void 0:n.focusBorder);c==null?delete r[`list.focusOutline`]:r[`list.focusOutline`]=c;let l=n[`list.hoverBackground`];l!=null&&(Oot(l,o)||Dot(l,o,s))&&delete r[`list.hoverBackground`];let u=Object.freeze({...e,colors:Object.freeze(r)});return n9.set(e,u),u}function i9(e,t,n){n!=null&&n!==``&&(e[t]=n)}function a9(...e){for(let t of e)if(t!=null&&t!==``)return t}function Oot(e,t){return t!=null&&e.toLowerCase()===t.toLowerCase()}function o9({theme:e=z2,highlighter:t,prefix:n}){let r=``;if(typeof e==`string`){let i=t.getTheme(e),a=r9(i);r+=`color:${a.fg};`,r+=`background-color:${a.bg};`,r+=`${$7(`global`)}fg:${a.fg};`,r+=`${$7(`global`)}bg:${a.bg};`,r+=s9(i,n)}else{let n=t.getTheme(e.dark),i=r9(n);r+=`${$7(`global`)}dark:${i.fg};`,r+=`${$7(`global`)}dark-bg:${i.bg};`,r+=s9(n,`dark`),n=t.getTheme(e.light),i=r9(n),r+=`${$7(`global`)}light:${i.fg};`,r+=`${$7(`global`)}light-bg:${i.bg};`,r+=s9(n,`light`)}return r}function s9(e,t){t=t==null?``:`${t}-`;let n=``,r=e.colors?.[`gitDecoration.addedResourceForeground`]??e.colors?.[`terminal.ansiGreen`];r!=null&&(n+=`${$7(`global`)}${t}addition-color:${r};`);let i=e.colors?.[`gitDecoration.deletedResourceForeground`]??e.colors?.[`terminal.ansiRed`];i!=null&&(n+=`${$7(`global`)}${t}deletion-color:${i};`);let a=e.colors?.[`gitDecoration.modifiedResourceForeground`]??e.colors?.[`terminal.ansiBlue`];return a!=null&&(n+=`${$7(`global`)}${t}modified-color:${a};`),n}function c9(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t.children;t=`children`in t?t.children[0]:null}throw console.error(e),Error(`getLineNodes: Unable to find children`)}var l9=10,u9=13,kot=4,Aot=40;function jot(e){let t=[0],n=e.indexOf(`\r`),r=e.indexOf(`
1186
1186
  `),i=0,a=0;for(;n!==-1||r!==-1;){let o;if(n!==-1&&(r===-1||n<r)?r===n+1?(o=r+1,n=e.indexOf(`\r`,o),r=e.indexOf(`
1187
1187
  `,o)):(o=n+1,n=e.indexOf(`\r`,o)):(o=r+1,r=e.indexOf(`
1188
- `,o)),t.push(o),++a===jot){if(o-i<=Mot){for(let n=o;n<e.length;n++){let r=e.charCodeAt(n);(r===l9||r===u9)&&(r===u9&&n+1<e.length&&e.charCodeAt(n+1)===l9&&n++,t.push(n+1))}return t}i=o,a=0}}return t}function d9(e){let t=Not(e);return Array.from({length:t.length},(n,r)=>{let i=t[r],a=t[r+1]??e.length;return e.slice(i,a)})}var Pot={forcePlainText:!1};function f9(e,t,{theme:n=B2,tokenizeMaxLineLength:r,useTokenTransformer:i},{forcePlainText:a,startingLine:o,totalLines:s,lines:c}=Pot){a?(o??=0,s??=1/0):(o=0,s=1/0);let l=o>0||s<1/0,{state:u,transformers:d}=Z7(i),f=a?`text`:e.lang??W7(e.name),p=typeof n==`string`?t.getTheme(n).type:void 0,m=o9({theme:n,highlighter:t});u.lineInfo=e=>({type:`context`,lineIndex:e-1+o,lineNumber:e+o});let h=typeof n==`string`?{lang:f,theme:n,transformers:d,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0}:{lang:f,themes:n,transformers:d,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0},g=c9(t.codeToHast(l?Fot(c??d9(e.contents),o,s):e.contents,h)),_=l?Array(o):g;return l&&_.push(...g),{code:_,themeStyles:m,baseThemeType:p}}function Fot(e,t,n){if(e.length===0)return``;let r=Math.min(t+n,e.length);return e.slice(t,r).join(``)}var Iot=`-1,-1`;function Lot(e){return e?.some(e=>e.lineNumber===0)??!1}function Rot(e){let t=e[0];return t!=null&&t.length>0?t:void 0}function zot(e){return e.startingLine===0&&e.totalLines>0}function Bot(e,t){return e.endsWith(`\r
1188
+ `,o)),t.push(o),++a===kot){if(o-i<=Aot){for(let n=o;n<e.length;n++){let r=e.charCodeAt(n);(r===l9||r===u9)&&(r===u9&&n+1<e.length&&e.charCodeAt(n+1)===l9&&n++,t.push(n+1))}return t}i=o,a=0}}return t}function d9(e){let t=jot(e);return Array.from({length:t.length},(n,r)=>{let i=t[r],a=t[r+1]??e.length;return e.slice(i,a)})}var Mot={forcePlainText:!1};function f9(e,t,{theme:n=z2,tokenizeMaxLineLength:r,useTokenTransformer:i},{forcePlainText:a,startingLine:o,totalLines:s,lines:c}=Mot){a?(o??=0,s??=1/0):(o=0,s=1/0);let l=o>0||s<1/0,{state:u,transformers:d}=Z7(i),f=a?`text`:e.lang??W7(e.name),p=typeof n==`string`?t.getTheme(n).type:void 0,m=o9({theme:n,highlighter:t});u.lineInfo=e=>({type:`context`,lineIndex:e-1+o,lineNumber:e+o});let h=typeof n==`string`?{lang:f,theme:n,transformers:d,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0}:{lang:f,themes:n,transformers:d,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0},g=c9(t.codeToHast(l?Not(c??d9(e.contents),o,s):e.contents,h)),_=l?Array(o):g;return l&&_.push(...g),{code:_,themeStyles:m,baseThemeType:p}}function Not(e,t,n){if(e.length===0)return``;let r=Math.min(t+n,e.length);return e.slice(t,r).join(``)}var Pot=`-1,-1`;function Fot(e){return e?.some(e=>e.lineNumber===0)??!1}function Iot(e){let t=e[0];return t!=null&&t.length>0?t:void 0}function Lot(e){return e.startingLine===0&&e.totalLines>0}function Rot(e,t){return e.endsWith(`\r
1189
1189
  `)?t+`\r
1190
1190
  `:e.endsWith(`\r`)?t+`\r`:e.endsWith(`
1191
1191
  `)?t+`
1192
- `:t}function Vot(e,t){return w4({tagName:`div`,children:e,properties:{"data-content":``,style:`grid-row: span ${t}`}})}function p9(e){return(e.lang??W7(e.name))===`text`}var Hot=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
1192
+ `:t}function zot(e,t){return C4({tagName:`div`,children:e,properties:{"data-content":``,style:`grid-row: span ${t}`}})}function p9(e){return(e.lang??W7(e.name))===`text`}var Bot=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
1193
1193
  <symbol id="diffs-icon-arrow-right-short" viewBox="0 0 16 16">
1194
1194
  <path d="M8.47 4.22a.75.75 0 0 0 0 1.06l1.97 1.97H3.75a.75.75 0 0 0 0 1.5h6.69l-1.97 1.97a.75.75 0 1 0 1.06 1.06l3.25-3.25a.75.75 0 0 0 0-1.06L9.53 4.22a.75.75 0 0 0-1.06 0"/>
1195
1195
  </symbol>
@@ -1241,7 +1241,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[b5(e),e])),$it=new Map([[`s`,U5(383)],[U5(38
1241
1241
  <symbol id="diffs-icon-symbol-ref" viewBox="0 0 16 16">
1242
1242
  <path d="M1.5 8c0 1.613.088 2.806.288 3.704.196.88.478 1.381.802 1.706.286.286.71.54 1.41.73V1.86c-.7.19-1.124.444-1.41.73-.324.325-.606.826-.802 1.706C1.588 5.194 1.5 6.387 1.5 8m4 6.397c.697.07 1.522.103 2.5.103 1.613 0 2.806-.088 3.704-.288.88-.195 1.381-.478 1.706-.802s.607-.826.802-1.706c.2-.898.288-2.091.288-3.704s-.088-2.806-.288-3.704c-.195-.88-.478-1.381-.802-1.706s-.826-.606-1.706-.802C10.806 1.588 9.613 1.5 8 1.5c-.978 0-1.803.033-2.5.103zM0 8c0-6.588 1.412-8 8-8s8 1.412 8 8-1.412 8-8 8-8-1.412-8-8m7-2a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z"/>
1243
1243
  </symbol>
1244
- </svg>`;function Uot(e,t){return e==null||t==null?e===t:Wot(e.customProperties,t.customProperties)&&e.type===t.type&&e.diffIndicators===t.diffIndicators&&e.disableBackground===t.disableBackground&&e.disableLineNumbers===t.disableLineNumbers&&e.overflow===t.overflow&&e.split===t.split&&e.totalLines===t.totalLines}var m9={};function Wot(e=m9,t=m9){if(e===t)return!0;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(e[r]!==t[r])return!1;return!0}function Got(e){let t=document.createElement(`div`);return t.dataset.annotationSlot=``,t.slot=e,t.style.whiteSpace=`normal`,t}function Kot(){let e=document.createElement(`div`);return e.slot=`gutter-utility-slot`,e.style.position=`absolute`,e.style.top=`0`,e.style.bottom=`0`,e.style.textAlign=`center`,e.style.whiteSpace=`normal`,e.style.touchAction=`none`,e}function qot(){let e=document.createElement(`style`);return e.setAttribute(N9e,``),e}var Jot=`@layer base {
1244
+ </svg>`;function Vot(e,t){return e==null||t==null?e===t:Hot(e.customProperties,t.customProperties)&&e.type===t.type&&e.diffIndicators===t.diffIndicators&&e.disableBackground===t.disableBackground&&e.disableLineNumbers===t.disableLineNumbers&&e.overflow===t.overflow&&e.split===t.split&&e.totalLines===t.totalLines}var m9={};function Hot(e=m9,t=m9){if(e===t)return!0;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(e[r]!==t[r])return!1;return!0}function Uot(e){let t=document.createElement(`div`);return t.dataset.annotationSlot=``,t.slot=e,t.style.whiteSpace=`normal`,t}function Wot(){let e=document.createElement(`div`);return e.slot=`gutter-utility-slot`,e.style.position=`absolute`,e.style.top=`0`,e.style.bottom=`0`,e.style.textAlign=`center`,e.style.whiteSpace=`normal`,e.style.touchAction=`none`,e}function Got(){let e=document.createElement(`style`);return e.setAttribute(M9e,``),e}var Kot=`@layer base {
1245
1245
  :host {
1246
1246
  --diffs-font-fallback: "SF Mono", Monaco, Consolas, "Ubuntu Mono", "Liberation Mono",
1247
1247
  "Courier New", monospace;
@@ -2519,15 +2519,15 @@ XID_Start XIDS`.split(/\s/).map(e=>[b5(e),e])),$it=new Map([[`s`,U5(383)],[U5(38
2519
2519
  }
2520
2520
 
2521
2521
  @layer theme, rendered, unsafe;
2522
- `,h9;function g9(e){if(h9!=null)return h9;let t=e.host;if(typeof HTMLElement<`u`&&t instanceof HTMLElement&&!t.isConnected)return;let n=document.createElement(`div`);n.setAttribute(`data-code`,``),n.setAttribute(P9e,`true`);let r=document.createElement(`div`);return r.style.position=`relative`,r.style.width=`200%`,r.style.height=`200%`,n.appendChild(r),e.appendChild(n),h9=Math.max(n.offsetHeight-n.clientHeight,0),n.remove(),h9}function _9(e){return`${V2}: ${e==null?`var(--diffs-scrollbar-gutter-fallback)`:`${e}px`};`}var v9=`@layer base, theme, rendered, unsafe;`,Yot=RegExp(`${$ot(V2)}\\s*:\\s*[^;]+;`);function Xot(e){return`${v9}
2522
+ `,h9;function g9(e){if(h9!=null)return h9;let t=e.host;if(typeof HTMLElement<`u`&&t instanceof HTMLElement&&!t.isConnected)return;let n=document.createElement(`div`);n.setAttribute(`data-code`,``),n.setAttribute(N9e,`true`);let r=document.createElement(`div`);return r.style.position=`relative`,r.style.width=`200%`,r.style.height=`200%`,n.appendChild(r),e.appendChild(n),h9=Math.max(n.offsetHeight-n.clientHeight,0),n.remove(),h9}function _9(e){return`${B2}: ${e==null?`var(--diffs-scrollbar-gutter-fallback)`:`${e}px`};`}var v9=`@layer base, theme, rendered, unsafe;`,qot=RegExp(`${Zot(B2)}\\s*:\\s*[^;]+;`);function Jot(e){return`${v9}
2523
2523
  @layer unsafe {
2524
2524
  ${e}
2525
- }`}function Zot(e,t=`system`,n){return`${v9}
2525
+ }`}function Yot(e,t=`system`,n){return`${v9}
2526
2526
  @layer rendered {
2527
2527
  :host {${t===`system`?``:`
2528
2528
  color-scheme: ${t};`}
2529
2529
  ${_9(n)}
2530
2530
  ${e}
2531
2531
  }
2532
- }`}function Qot(e,t){let n=_9(t);return e.replace(Yot,n)}function $ot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function est({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 tst(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function nst(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 rst(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function ist(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function ast(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 ost({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=sst(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function sst(){let e=document.createElement(`style`);return e.setAttribute(M9e,``),e}var cst=void 0;function lst(){return cst??=`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(Jot)),t.adoptedStyleSheets=[e]}connectedCallback(){g9(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(F2,t)}function ust(e){return{...H2,...e}}function dst(e,t){let n=fst(e,t);return t?n:e.diffHeaderHeight+n}function fst(e,t){return e.paddingTop??(t?e.spacing:0)}function pst(e){return e.paddingBottom??e.spacing}function mst(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function y9(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function b9(e,t){return Y2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function x9({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 S9({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 C9(e){return[$2(e.additionStart,e.additionCount)+1,e4(e.additionStart,e.additionCount)+1]}function w9({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-e4(t.additionStart,t.additionCount),r=e.deletionLines.length-e4(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function T9({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-e4(n.additionStart,n.additionCount),i=e.deletionLines.length-e4(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 E9({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=T9({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 gst({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]=C9(a);if(t<o){let s=w9({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=E9({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]=C9(a);return t<o+i.fromStart||t>=o+i.rangeSize}function _st({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]=C9(n),l=w9({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=E9({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 D9({type:e,metrics:t}){return t.hunkSeparatorHeight??mst(e)}function O9({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function vst({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 yst(e){return e!==`simple`&&e!==`metadata`}function bst({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!vst({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=D9({type:e,metrics:t}),a=O9({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function xst({type:e,metrics:t}){if(!yst(e))return;let n=D9({type:e,metrics:t}),r=O9({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function k9({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=Sst({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=$2(r.deletionStart,r.deletionCount),s=$2(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=w9({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?E9({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(A9(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,A9(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(A9(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=Tst(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(Est({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(A9(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 Sst({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=Cst({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 Cst({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=w9({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?E9({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 wst(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 A9(e,t,n,r,i,a){let[o,s]=wst(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 Tst(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 Est({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 Dst={forcePlainText:!1};function j9(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=Dst){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=o9({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)??kst();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)}k9({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&&Ost({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}=Ast({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 Ost({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=Q2(e),t=Q2(t),e.length>s||t.length>s))return;let c=o===`char`?q9e(e,t):Z9e(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?(S9({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),S9({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?S9({item:e,arr:l,enableJoin:d,isLastItem:t}):S9({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(x9({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(x9({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function kst(){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 Ast({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=B2,...l}}){let u=s??W7(e.name),d=s??W7(t.name),{state:f,transformers:p}=Z7(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,c9(i.codeToHast(Q2(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,c9(i.codeToHast(Q2(t.contents),m)))}}function M9(e){let t=e.lang??W7(e.name),n=e.lang??(e.prevName==null?`text`:W7(e.prevName));return t===`text`&&n===`text`}function N9(e){let t=[];for(let n of e){let e=I3.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function P9(e){for(let t of Array.isArray(e)?e:[e])if(!I3.has(t))return!1;return!0}async function F9(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=w7(r)??C7(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 I9(e){return k7.getResolvedThemes(e)}async function L9(e){for(let t of e)F7(t);let t=await k7.resolveThemes(e);for(let n=0;n<e.length;n++)I7(e[n],t[n]);return t}var R9={light:`pierre-light`,dark:`pierre-dark`};function jst(e){return e===`dark`?R9.dark:R9.light}var z9=2166136261,B9=16777619,Mst=2654435769,Nst=2246822507;function V9(e,t=z9,n=B9){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 Pst(e,t=`diff-panel`){let n=e.trim(),r=V9(n,z9,B9).toString(36),i=V9(n,Mst,Nst).toString(36);return`${t}:${n.length}:${r}:${i}`}function Fst(e){let t=(0,F.useRef)(e);return(0,F.useInsertionEffect)(()=>void(t.current=e)),(0,F.useCallback)((...e)=>t.current(...e),[])}var Ist=(0,F.createContext)(void 0);function Lst(){return(0,F.useContext)(Ist)}var Rst={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},zst={display:`contents`};function Bst(){return null}var H9=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),U9=Symbol(`IGNORE_RESPONSE`),W9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled because the pool terminated`)}},G9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled before the task completed`)}},Vst=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=B2,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 H9.default.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new H9.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??B2,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()||b9(a,this.renderOptions))return;let o=z7(e),c=[];if(Y2(a.theme,this.renderOptions.theme)||(c=B7(o)?I9(o):await L9(o)),!s())return;if(this.highlighter!=null)A7(c,this.highlighter);else{let e=await R7({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 W9||!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);q9(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=z7(this.renderOptions.theme),i=[];if(i=B7(r)?I9(r):await L9(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=P9(e)?N9(e):await F9(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([R7({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 W9||!this.isCurrentLifecycle(t)){n();return}this.initialized=!1,this.workersFailed=!0;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,Y9(e));this.queueBroadcastStateChanges(),r(e)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;let n=[],r=G7(),i=r>0?K7():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=K9(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);p9(t)||n!=null&&V7(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||p9(e)||t!=null&&V7(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 f9(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);M9(t)||n!=null&&b9(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||M9(e)||t!=null&&b9(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:j9(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 W9;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 W9;for(let t of this.activeTaskById.values())`reject`in t?t.reject(e):q9(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&&(P9(r)?t.request.resolvedLanguages=N9(r):t.request.resolvedLanguages=await F9(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,Y9(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 U9;if(t.type===`error`){let e=Error(t.error);if(t.stack&&(e.stack=t.stack),`reject`in n)n.reject(e);else if(q9(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)||!V7(i,this.getFileRenderOptions()))throw U9;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)||!b9(i,this.getDiffRenderOptions()))throw U9;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!==U9&&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,q9(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&&(q9(t)&&(this.rejectRenderTaskCallbacks(t,new G9),this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){Hst(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(let n of K9(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),q9(t)?(this.notifyHighlightError(t,n),this.rejectRenderTaskCallbacks(t,Y9(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=G7();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=K7())}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 J9(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 G9),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.rejectRenderTaskCallbacks(e,new G9),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()))q9(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(let t of J9(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 J9(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(let t of J9(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 J9(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)&&S4(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)&&y9(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())q9(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function Hst(e){return e.type===`initialize`||e.type===`file`||e.type===`diff`}function K9(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??W7(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??W7(e.request.diff.name)),t.add(e.request.diff.lang??W7(e.request.diff.prevName??`-`))}return t.delete(`text`),Array.from(t)}function q9(e){return e?.type===`file`||e?.type===`diff`}function J9(e){return e.instances}function Y9(e){return e instanceof Error?e:Error(String(e))}var X9;function Ust({poolOptions:e,highlighterOptions:t}){return X9??=new Vst(e,t),X9}function Wst(){X9!=null&&(X9.terminate(),X9=void 0)}var Z9=(0,F.createContext)(void 0),Q9=0;function Gst({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,F.useState)(()=>{if(!(typeof window>`u`))return Ust({poolOptions:t,highlighterOptions:n})});return(0,F.useInsertionEffect)(()=>{if(r!=null)return Q9++,()=>{Q9--}},[r]),(0,F.useEffect)(()=>()=>{Q9===0&&Wst()},[]),(0,Nr.jsx)(Z9.Provider,{value:r,children:e})}function Kst(){return(0,F.useContext)(Z9)}function $9(e){return Zt(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,Pr&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function qst(e){let t=(0,cl.c)(10),n=Pr&&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=Zt(`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,Nr.jsx)(`div`,{className:$9(e.mode),children:e.header}):(0,Nr.jsx)(`div`,{className:`border-b border-border`,children:(0,Nr.jsx)(`div`,{className:$9(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,Nr.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 Jst(){let e=(0,cl.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Nr.jsx)(I1,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,Nr.jsx)(I1,{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,Nr.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,Nr.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,Nr.jsx)(I1,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,Nr.jsx)(I1,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,Nr.jsx)(I1,{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,Nr.jsxs)(Nr.Fragment,{children:[r,(0,Nr.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,Nr.jsx)(I1,{className:`size-7 rounded-md`}),(0,Nr.jsx)(I1,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function Yst(e){let t=(0,cl.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Nr.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,Nr.jsx)(I1,{className:`h-4 w-32 rounded-full`}),(0,Nr.jsx)(I1,{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,Nr.jsxs)(`div`,{className:`space-y-2`,children:[(0,Nr.jsx)(I1,{className:`h-3 w-full rounded-full`}),(0,Nr.jsx)(I1,{className:`h-3 w-full rounded-full`}),(0,Nr.jsx)(I1,{className:`h-3 w-10/12 rounded-full`}),(0,Nr.jsx)(I1,{className:`h-3 w-11/12 rounded-full`}),(0,Nr.jsx)(I1,{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,Nr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,Nr.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,Nr.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,Nr.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{Rot as $,NY as $a,wi as $c,zQ as $i,Q0 as $n,GXe as $o,R6e as $r,qqe as $s,I9e as $t,dst as A,XX as Aa,gl as Ac,T$ as Ai,nre as Al,u9e as An,CZe as Ao,L8e as Ar,JK as As,$4 as At,Qot as B,MX as Ba,dl as Bc,F4e as Bi,Xne as Bl,B5e as Bn,XXe as Bo,V1 as Br,HJe as Bs,S4 as Bt,E9 as C,S1e as Ca,wl as Cc,F3e as Ci,Vr as Cl,v9e as Cn,QZe as Co,c0 as Cr,tq as Cs,Bet as Ct,b9 as D,MZ as Da,bl as Dc,E$ as Di,Ir as Dl,N2 as Dn,iY as Do,O8e as Dr,oYe as Ds,c3 as Dt,gst as E,AZ as Ea,xl as Ec,P3e as Ei,Qr as El,b9e as En,WZe as Eo,T8e as Er,mYe as Es,l3 as Et,ist as F,HX as Fa,fl as Fc,g$ as Fi,Dr as Fl,a9e as Fn,XJ as Fo,h0 as Fr,qK as Fs,aet as Ft,Kot as G,b$e as Ga,Vo as Gc,a$ as Gi,_r as Gl,J5e as Gn,RXe as Go,X6e as Gr,zJe as Gs,G9e as Gt,Xot as H,S$e as Ha,Io as Hc,c$ as Hi,Zne as Hl,a7e as Hn,OJ as Ho,i8e as Hr,MJe as Hs,e4 as Ht,rst as I,zX as Ia,pl as Ic,_$ as Ii,Er as Il,v2 as In,qJ as Io,I8e as Ir,VK as Is,iet as It,Hot as J,UQe as Ja,ji as Jc,T4e as Ji,Gne as Jl,W5e as Jn,yJ as Jo,K6e as Jr,pK as Js,Y2 as Jt,Got as K,AX as Ka,Fo as Kc,r$ as Ki,Yne as Kl,U5e as Kn,VXe as Ko,I1 as Kr,CK as Ks,Z2 as Kt,nst as L,LX as La,ml as Lc,Y4e as Li,Tr as Ll,_2 as Ln,BJ as Lo,d8e as Lr,PK as Ls,w4 as Lt,lst as M,QX as Ma,Bce as Mc,v3e as Mi,jr as Ml,c9e as Mn,DZe as Mo,P8e as Mr,WK as Ms,A4 as Mt,ost as N,YX as Na,Vce as Nc,x$ as Ni,kr as Nl,l9e as Nn,OZe as No,F8e as Nr,XK as Ns,D4 as Nt,y9 as O,$X as Oa,Cl as Oc,D3e as Oi,Fr as Ol,x9e as On,tY as Oo,N8e as Or,sYe as Os,t3 as Ot,ast as P,GX as Pa,zce as Pc,b3e as Pi,Or as Pl,n9e as Pn,ZJ as Po,j8e as Pr,nYe as Ps,oet as Pt,Iot as Q,PY as Qa,Oi as Qc,f4e as Qi,Z5e as Qn,KXe as Qo,W6e as Qr,CJe as Qs,A9e as Qt,tst as R,PX as Ra,Rce as Rc,d$ as Ri,Jne as Rl,y2 as Rn,kJ as Ro,f8e as Rr,SK as Rs,T4 as Rt,T9 as S,x1e as Sa,Dl as Sc,A$ as Si,Kr as Sl,y9e as Sn,sQe as So,v0 as Sr,aq as Ss,d3 as St,hst as T,C1e as Ta,yl as Tc,R3e as Ti,ei as Tl,C9e as Tn,tQe as To,o0 as Tr,oq as Ts,zet as Tt,g9 as U,$Qe as Ua,Lo as Uc,o$ as Ui,Vne as Ul,q5e as Un,SJ as Uo,z1 as Ur,PJe as Us,$2 as Ut,Zot as V,tX as Va,Wo as Vc,P4e as Vi,Cr as Vl,i7e as Vn,FJ as Vo,a8e as Vr,LJe as Vs,tet as Vt,qot as W,QQe as Wa,Bo as Wc,t$ as Wi,Une as Wl,R7e as Wn,wJ as Wo,n8e as Wr,AJe as Ws,Q2 as Wt,Vot as X,WY as Xa,Di as Xc,S4e as Xi,L7e as Xn,WXe as Xo,q6e as Xr,gJe as Xs,K2 as Xt,p9 as Y,LQe as Ya,Ai as Yc,C4e as Yi,vr as Yl,K5e as Yn,vJ as Yo,G6e as Yr,hJe as Ys,J2 as Yt,Bot as Z,UY as Za,ki as Zc,h4e as Zi,k7e as Zn,jXe as Zo,J6e as Zr,bJe as Zs,G2 as Zt,k9 as _,J1e as _a,rG as _c,j$ as _i,dre as _l,L2 as _n,gY as _o,M0 as _r,sq as _s,ztt as _t,Gst as a,y2e as aa,xJe as ac,M1 as ai,bi as al,V9e as an,OY as ao,I7e as ar,sXe as as,_ot as at,bst as b,D1e as ba,mle as bc,k$ as bi,Rr as bl,j9e as bn,fQe as bo,G8e as br,nq as bs,Ctt as bt,zst as c,S2e as ca,qG as cc,z6e as ci,yre as cl,B2 as cn,xY as co,r7e as cr,iXe as cs,dot as ct,Fst as d,K0e as da,fqe as dc,U6e as di,si as dl,w9e as dn,TY as do,F5e as dr,iJ as ds,V7 as dt,HQ as ea,TJe as ec,B6e as ei,Ei as el,F9e as en,FY as eo,Y5e as er,mJ as es,Lot as et,Pst as f,Y0e as fa,pqe as fc,A1 as fi,ii as fl,F2 as fn,wY as fo,P5e as fr,cXe as fs,B7 as ft,j9 as g,K1e as ga,oG as gc,z3e as gi,Ur as gl,E9e as gn,mY as go,v5e as gr,hYe as gs,R7 as gt,M9 as h,eQ as ha,mG as hc,M$ as hi,Wr as hl,k9e as hn,pY as ho,C5e as hr,oJ as hs,aot as ht,Z9 as i,PQ as ia,_K as ic,F6e as ii,wre as il,z9e as in,vQe as io,O7e as ir,Qq as is,vot as it,pst as j,t1e as ja,hl as jc,C$ as ji,Mr as jl,s9e as jn,TZe as jo,M8e as jr,GK as js,Z4 as jt,ust as k,Z$e as ka,_l as kc,E3e as ki,Pr as kl,o9e as kn,nY as ko,A8e as kr,$K as ks,Q4 as kt,Bst as l,TQ as la,Mqe as lc,M6e as li,bre as ll,L9e as ln,bY as lo,J0 as lr,rJ as ls,lot as lt,jst as m,b0e as ma,gG as mc,N$ as mi,ore as ml,O9e as mn,lY as mo,B0 as mr,nXe as ms,z7 as mt,Yst as n,IQ as na,oK as nc,V6e as ni,Ci as nl,z2 as nn,_Qe as no,r2 as nr,hJ as ns,f9 as nt,Kst as o,O2e as oa,ZG as oc,j1 as oi,mi as ol,H9e as on,DY as oo,Y0 as or,$q as os,W7 as ot,V9 as p,B0e as pa,uqe as pc,I$ as pi,ri as pl,U9e as pn,CY as po,N5e as pr,rXe as ps,sot as pt,Uot as q,y$e as qa,Ore as qc,n$ as qi,Bne as ql,F7e as qn,MXe as qo,Y6e as qr,EJe as qs,W9e as qt,qst as r,FQ as ra,fJe as rc,H6e as ri,Si as rl,R9e as rn,AY as ro,X5e as rr,oXe as rs,d9 as rt,Rst as s,b2e as sa,JG as sc,I6e as si,xre as sl,B9e as sn,EY as so,a2 as sr,aJ as ss,mot as st,Jst as t,e4e as ta,wJe as tc,N6e as ti,Ti as tl,T9e as tn,xQe as to,H5e as tr,pJ as ts,zot as tt,Lst as u,EQ as ua,dqe as uc,p6e as ui,ci as ul,H2 as un,gQe as uo,q0 as ur,aXe as us,cot as ut,w9 as v,W1e as va,iG as vc,B3e as vi,cre as vl,R2 as vn,hY as vo,N0 as vr,rq as vs,Mtt as vt,xst as w,w1e as wa,Tl as wc,O$ as wi,qr as wl,S9e as wn,YZe as wo,l0 as wr,cq as ws,u3 as wt,_st as x,NZ as xa,gle as xc,I3e as xi,Gr as xl,D9e as xn,oY as xo,H8e as xr,iq as xs,C3 as xt,C9 as y,zZ as ya,hle as yc,D$ as yi,sre as yl,I2 as yn,mQe as yo,_0 as yr,eq as ys,Stt as yt,est as z,NX as za,ul as zc,z4e as zi,Qne as zl,x2 as zn,PJ as zo,o8e as zr,IJe as zs,C4 as zt};
2533
- //# sourceMappingURL=DiffPanelShell-CUAjFqGU.js.map
2532
+ }`}function Xot(e,t){let n=_9(t);return e.replace(qot,n)}function Zot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Qot({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 $ot(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function est(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 tst(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function nst(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function rst(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 ist({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=ast(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function ast(){let e=document.createElement(`style`);return e.setAttribute(j9e,``),e}var ost=void 0;function sst(){return ost??=`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(Kot)),t.adoptedStyleSheets=[e]}connectedCallback(){g9(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(P2,t)}function cst(e){return{...V2,...e}}function lst(e,t){let n=ust(e,t);return t?n:e.diffHeaderHeight+n}function ust(e,t){return e.paddingTop??(t?e.spacing:0)}function dst(e){return e.paddingBottom??e.spacing}function fst(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function y9(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function b9(e,t){return J2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function x9({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 S9({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 C9(e){return[Q2(e.additionStart,e.additionCount)+1,$2(e.additionStart,e.additionCount)+1]}function w9({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 pst(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-$2(t.additionStart,t.additionCount),r=e.deletionLines.length-$2(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function T9({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-$2(n.additionStart,n.additionCount),i=e.deletionLines.length-$2(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 E9({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=T9({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 mst({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]=C9(a);if(t<o){let s=w9({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=E9({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]=C9(a);return t<o+i.fromStart||t>=o+i.rangeSize}function hst({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]=C9(n),l=w9({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=E9({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 D9({type:e,metrics:t}){return t.hunkSeparatorHeight??fst(e)}function O9({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 _st(e){return e!==`simple`&&e!==`metadata`}function vst({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!gst({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=D9({type:e,metrics:t}),a=O9({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function yst({type:e,metrics:t}){if(!_st(e))return;let n=D9({type:e,metrics:t}),r=O9({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function k9({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=bst({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=Q2(r.deletionStart,r.deletionCount),s=Q2(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=w9({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?E9({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(A9(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,A9(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(A9(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=Cst(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(wst({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(A9(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 bst({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=w9({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?E9({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 Sst(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 A9(e,t,n,r,i,a){let[o,s]=Sst(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 Cst(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 wst({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 Tst={forcePlainText:!1};function j9(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=Tst){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=o9({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)??Dst();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)}k9({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&&Est({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}=Ost({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 Est({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=Z2(e),t=Z2(t),e.length>s||t.length>s))return;let c=o===`char`?K9e(e,t):X9e(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?(S9({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),S9({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?S9({item:e,arr:l,enableJoin:d,isLastItem:t}):S9({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(x9({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(x9({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function Dst(){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 Ost({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=z2,...l}}){let u=s??W7(e.name),d=s??W7(t.name),{state:f,transformers:p}=Z7(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:$7(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,c9(i.codeToHast(Z2(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,c9(i.codeToHast(Z2(t.contents),m)))}}function M9(e){let t=e.lang??W7(e.name),n=e.lang??(e.prevName==null?`text`:W7(e.prevName));return t===`text`&&n===`text`}function N9(e){let t=[];for(let n of e){let e=F3.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function P9(e){for(let t of Array.isArray(e)?e:[e])if(!F3.has(t))return!1;return!0}async function F9(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=w7(r)??C7(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 I9(e){return k7.getResolvedThemes(e)}async function L9(e){for(let t of e)F7(t);let t=await k7.resolveThemes(e);for(let n=0;n<e.length;n++)I7(e[n],t[n]);return t}var R9={light:`pierre-light`,dark:`pierre-dark`};function kst(e){return e===`dark`?R9.dark:R9.light}var z9=2166136261,B9=16777619,Ast=2654435769,jst=2246822507;function V9(e,t=z9,n=B9){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 Mst(e,t=`diff-panel`){let n=e.trim(),r=V9(n,z9,B9).toString(36),i=V9(n,Ast,jst).toString(36);return`${t}:${n.length}:${r}:${i}`}function Nst(e){let t=(0,F.useRef)(e);return(0,F.useInsertionEffect)(()=>void(t.current=e)),(0,F.useCallback)((...e)=>t.current(...e),[])}var Pst=(0,F.createContext)(void 0);function Fst(){return(0,F.useContext)(Pst)}var Ist={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},Lst={display:`contents`};function Rst(){return null}var H9=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),U9=Symbol(`IGNORE_RESPONSE`),W9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled because the pool terminated`)}},G9=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled before the task completed`)}},zst=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=z2,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 H9.default.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new H9.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??z2,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()||b9(a,this.renderOptions))return;let o=z7(e),c=[];if(J2(a.theme,this.renderOptions.theme)||(c=B7(o)?I9(o):await L9(o)),!s())return;if(this.highlighter!=null)A7(c,this.highlighter);else{let e=await R7({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 W9||!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);q9(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=z7(this.renderOptions.theme),i=[];if(i=B7(r)?I9(r):await L9(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=P9(e)?N9(e):await F9(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([R7({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 W9||!this.isCurrentLifecycle(t)){n();return}this.initialized=!1,this.workersFailed=!0;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,Y9(e));this.queueBroadcastStateChanges(),r(e)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;let n=[],r=G7(),i=r>0?K7():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=K9(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);p9(t)||n!=null&&V7(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||p9(e)||t!=null&&V7(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 f9(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);M9(t)||n!=null&&b9(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||M9(e)||t!=null&&b9(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:j9(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 W9;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 W9;for(let t of this.activeTaskById.values())`reject`in t?t.reject(e):q9(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&&(P9(r)?t.request.resolvedLanguages=N9(r):t.request.resolvedLanguages=await F9(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,Y9(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 U9;if(t.type===`error`){let e=Error(t.error);if(t.stack&&(e.stack=t.stack),`reject`in n)n.reject(e);else if(q9(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)||!V7(i,this.getFileRenderOptions()))throw U9;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)||!b9(i,this.getDiffRenderOptions()))throw U9;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!==U9&&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,q9(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&&(q9(t)&&(this.rejectRenderTaskCallbacks(t,new G9),this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){Bst(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(let n of K9(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),q9(t)?(this.notifyHighlightError(t,n),this.rejectRenderTaskCallbacks(t,Y9(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=G7();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=K7())}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 J9(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 G9),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.rejectRenderTaskCallbacks(e,new G9),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()))q9(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(let t of J9(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 J9(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(let t of J9(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 J9(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)&&x4(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)&&y9(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())q9(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function Bst(e){return e.type===`initialize`||e.type===`file`||e.type===`diff`}function K9(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??W7(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??W7(e.request.diff.name)),t.add(e.request.diff.lang??W7(e.request.diff.prevName??`-`))}return t.delete(`text`),Array.from(t)}function q9(e){return e?.type===`file`||e?.type===`diff`}function J9(e){return e.instances}function Y9(e){return e instanceof Error?e:Error(String(e))}var X9;function Vst({poolOptions:e,highlighterOptions:t}){return X9??=new zst(e,t),X9}function Hst(){X9!=null&&(X9.terminate(),X9=void 0)}var Z9=(0,F.createContext)(void 0),Q9=0;function Ust({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,F.useState)(()=>{if(!(typeof window>`u`))return Vst({poolOptions:t,highlighterOptions:n})});return(0,F.useInsertionEffect)(()=>{if(r!=null)return Q9++,()=>{Q9--}},[r]),(0,F.useEffect)(()=>()=>{Q9===0&&Hst()},[]),(0,Nr.jsx)(Z9.Provider,{value:r,children:e})}function Wst(){return(0,F.useContext)(Z9)}function $9(e){return Zt(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,Pr&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function Gst(e){let t=(0,cl.c)(10),n=Pr&&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=Zt(`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,Nr.jsx)(`div`,{className:$9(e.mode),children:e.header}):(0,Nr.jsx)(`div`,{className:`border-b border-border`,children:(0,Nr.jsx)(`div`,{className:$9(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,Nr.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 Kst(){let e=(0,cl.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Nr.jsx)(F1,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,Nr.jsx)(F1,{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,Nr.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,Nr.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,Nr.jsx)(F1,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,Nr.jsx)(F1,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,Nr.jsx)(F1,{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,Nr.jsxs)(Nr.Fragment,{children:[r,(0,Nr.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,Nr.jsx)(F1,{className:`size-7 rounded-md`}),(0,Nr.jsx)(F1,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function qst(e){let t=(0,cl.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Nr.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,Nr.jsx)(F1,{className:`h-4 w-32 rounded-full`}),(0,Nr.jsx)(F1,{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,Nr.jsxs)(`div`,{className:`space-y-2`,children:[(0,Nr.jsx)(F1,{className:`h-3 w-full rounded-full`}),(0,Nr.jsx)(F1,{className:`h-3 w-full rounded-full`}),(0,Nr.jsx)(F1,{className:`h-3 w-10/12 rounded-full`}),(0,Nr.jsx)(F1,{className:`h-3 w-11/12 rounded-full`}),(0,Nr.jsx)(F1,{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,Nr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,Nr.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,Nr.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,Nr.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{Iot as $,MY as $a,Ei as $c,RQ as $i,Z0 as $n,pJ as $o,L6e as $r,TJe as $s,F9e as $t,lst as A,YX as Aa,hl as Ac,w$ as Ai,Mr as Al,l9e as An,uZe as Ao,I8e as Ar,GK as As,Q4 as At,Xot as B,jX as Ba,Wo as Bc,P4e as Bi,Cr as Bl,z5e as Bn,PJ as Bo,B1 as Br,LJe as Bs,x4 as Bt,E9 as C,x1e as Ca,Tl as Cc,P3e as Ci,qr as Cl,_9e as Cn,$Ze as Co,s0 as Cr,cq as Cs,zet as Ct,b9 as D,jZ as Da,Cl as Dc,T$ as Di,Fr as Dl,M2 as Dn,eY as Do,D8e as Dr,sYe as Ds,s3 as Dt,mst as E,kZ as Ea,bl as Ec,N3e as Ei,Ir as El,y9e as En,GZe as Eo,w8e as Er,oYe as Es,c3 as Et,nst as F,VX as Fa,pl as Fc,h$ as Fi,Er as Fl,i9e as Fn,VJ as Fo,m0 as Fr,VK as Fs,iet as Ft,Wot as G,y$e as Ga,Fo as Gc,i$ as Gi,Yne as Gl,q5e as Gn,HXe as Go,Y6e as Gr,CK as Gs,W9e as Gt,Jot as H,x$e as Ha,Lo as Hc,s$ as Hi,Vne as Hl,i7e as Hn,xJ as Ho,r8e as Hr,PJe as Hs,$2 as Ht,tst as I,RX as Ia,ml as Ic,g$ as Ii,Tr as Il,_2 as In,zJ as Io,F8e as Ir,PK as Is,ret as It,Bot as J,HQe as Ja,Ai as Jc,w4e as Ji,vr as Jl,U5e as Jn,_J as Jo,G6e as Jr,hJe as Js,J2 as Jt,Uot as K,kX as Ka,Ore as Kc,n$ as Ki,Bne as Kl,H5e as Kn,NXe as Ko,F1 as Kr,EJe as Ks,X2 as Kt,est as L,IX as La,Rce as Lc,J4e as Li,Jne as Ll,g2 as Ln,OJ as Lo,u8e as Lr,SK as Ls,C4 as Lt,sst as M,ZX as Ma,Vce as Mc,_3e as Mi,kr as Ml,s9e as Mn,pZe as Mo,N8e as Mr,XK as Ms,k4 as Mt,ist as N,JX as Na,zce as Nc,b$ as Ni,Or as Nl,c9e as Nn,GJ as No,P8e as Nr,nYe as Ns,E4 as Nt,y9 as O,QX as Oa,_l as Oc,E3e as Oi,Pr as Ol,b9e as On,tY as Oo,M8e as Or,$K as Os,e3 as Ot,rst as P,WX as Pa,fl as Pc,y3e as Pi,Dr as Pl,t9e as Pn,WJ as Po,A8e as Pr,qK as Ps,aet as Pt,Pot as Q,NY as Qa,wi as Qc,d4e as Qi,X5e as Qn,KXe as Qo,U6e as Qr,qqe as Qs,k9e as Qt,$ot as R,NX as Ra,ul as Rc,u$ as Ri,Qne as Rl,v2 as Rn,NJ as Ro,d8e as Rr,IJe as Rs,w4 as Rt,T9 as S,b1e as Sa,wl as Sc,k$ as Si,Vr as Sl,v9e as Sn,cQe as So,_0 as Sr,tq as Ss,u3 as St,pst as T,S1e as Ta,xl as Tc,L3e as Ti,Qr as Tl,S9e as Tn,nQe as To,a0 as Tr,mYe as Ts,Ret as Tt,g9 as U,QQe as Ua,Bo as Uc,a$ as Ui,Une as Ul,K5e as Un,CJ as Uo,R1 as Ur,AJe as Us,Q2 as Ut,Yot as V,eX as Va,Io as Vc,N4e as Vi,Zne as Vl,r7e as Vn,DJ as Vo,i8e as Vr,MJe as Vs,eet as Vt,Got as W,ZQe as Wa,Vo as Wc,e$ as Wi,_r as Wl,L7e as Wn,zXe as Wo,t8e as Wr,zJe as Ws,Z2 as Wt,zot as X,UY as Xa,ki as Xc,x4e as Xi,I7e as Xn,MXe as Xo,K6e as Xr,bJe as Xs,G2 as Xt,p9 as Y,IQe as Ya,Di as Yc,S4e as Yi,G5e as Yn,GXe as Yo,W6e as Yr,gJe as Ys,q2 as Yt,Rot as Z,HY as Za,Oi as Zc,m4e as Zi,O7e as Zn,qXe as Zo,q6e as Zr,CJe as Zs,W2 as Zt,k9 as _,q1e as _a,iG as _c,A$ as _i,cre as _l,I2 as _n,mY as _o,j0 as _r,rq as _s,Rtt as _t,Ust as a,v2e as aa,ZG as ac,j1 as ai,mi as al,B9e as an,DY as ao,F7e as ar,Qq as as,hot as at,vst as b,E1e as ba,gle as bc,O$ as bi,Gr as bl,A9e as bn,hY as bo,W8e as br,iq as bs,Stt as bt,Lst as c,x2e as ca,Mqe as cc,R6e as ci,bre as cl,z2 as cn,bY as co,n7e as cr,nJ as cs,lot as ct,Nst as d,G0e as da,pqe as dc,H6e as di,ii as dl,C9e as dn,wY as do,P5e as dr,lXe as ds,V7 as dt,VQ as ea,wJe as ec,z6e as ei,Ti as el,P9e as en,PY as eo,J5e as er,fJ as es,Fot as et,Mst as f,J0e as fa,uqe as fc,k1 as fi,ri as fl,P2 as fn,CY as fo,N5e as fr,iXe as fs,B7 as ft,j9 as g,G1e as ga,rG as gc,R3e as gi,dre as gl,T9e as gn,fY as go,_5e as gr,sq as gs,R7 as gt,M9 as h,$Z as ha,oG as hc,j$ as hi,Ur as hl,O9e as hn,dY as ho,S5e as hr,hYe as hs,rot as ht,Z9 as i,NQ as ia,xJe as ic,P6e as ii,bi as il,R9e as in,_Qe as io,D7e as ir,cXe as is,got as it,dst as j,e1e as ja,Bce as jc,S$ as ji,jr as jl,o9e as jn,fZe as jo,j8e as jr,WK as js,X4 as jt,cst as k,X$e as ka,gl as kc,T3e as ki,nre as kl,a9e as kn,cZe as ko,k8e as kr,JK as ks,Z4 as kt,Rst as l,wQ as la,dqe as lc,j6e as li,ci as ll,I9e as ln,yY as lo,q0 as lr,oXe as ls,sot as lt,kst as m,y0e as ma,mG as mc,M$ as mi,Wr as ml,D9e as mn,sY as mo,z0 as mr,aJ as ms,z7 as mt,qst as n,FQ as na,fJe as nc,B6e as ni,Si as nl,R2 as nn,gQe as no,n2 as nr,sXe as ns,f9 as nt,Wst as o,D2e as oa,JG as oc,A1 as oi,xre as ol,V9e as on,EY as oo,J0 as or,iJ as os,W7 as ot,V9 as p,z0e as pa,gG as pc,F$ as pi,ore as pl,H9e as pn,SY as po,M5e as pr,rXe as ps,aot as pt,Vot as q,v$e as qa,ji as qc,t$ as qi,Gne as ql,P7e as qn,vJ as qo,J6e as qr,pK as qs,U9e as qt,Gst as r,PQ as ra,_K as rc,V6e as ri,wre as rl,L9e as rn,kY as ro,Y5e as rr,Zq as rs,d9 as rt,Ist as s,y2e as sa,qG as sc,F6e as si,yre as sl,z9e as sn,TY as so,i2 as sr,aXe as ss,fot as st,Kst as t,$2e as ta,oK as tc,M6e as ti,Ci as tl,w9e as tn,bQe as to,V5e as tr,mJ as ts,Lot as tt,Fst as u,TQ as ua,fqe as uc,f6e as ui,si as ul,V2 as un,hQe as uo,K0 as ur,rJ as us,oot as ut,w9 as v,U1e as va,hle as vc,z3e as vi,sre as vl,L2 as vn,fQe as vo,M0 as vr,eq as vs,jtt as vt,yst as w,C1e as wa,yl as wc,D$ as wi,ei as wl,x9e as wn,XZe as wo,c0 as wr,oq as ws,l3 as wt,hst as x,MZ as xa,Dl as xc,F3e as xi,Kr as xl,E9e as xn,iY as xo,V8e as xr,aq as xs,S3 as xt,C9 as y,RZ as ya,mle as yc,E$ as yi,Rr as yl,F2 as yn,pY as yo,g0 as yr,nq as ys,xtt as yt,Qot as z,MX as za,dl as zc,R4e as zi,Xne as zl,b2 as zn,ZXe as zo,a8e as zr,HJe as zs,S4 as zt};
2533
+ //# sourceMappingURL=DiffPanelShell-E6S9xolL.js.map