@cmmd-center/forge 0.9.17 → 0.9.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. package/dist/bin.cjs +716 -405
  2. package/dist/bin.mjs +743 -444
  3. package/dist/client/assets/{CanvasPanel-D9sKevpO.js → CanvasPanel-DO2u5-Xk.js} +2 -2
  4. package/dist/client/assets/{CompositeItem-Bsi2e5qV.js → CompositeItem-BNUtGUNS.js} +2 -2
  5. package/dist/client/assets/{DiffPanel-ClMWe6-c.js → DiffPanel-CiOqFcOU.js} +2 -2
  6. package/dist/client/assets/{DiffPanel.logic-o7tDdTzf.js → DiffPanel.logic-CcUKnHmG.js} +2 -2
  7. package/dist/client/assets/{DiffPanelShell-R1Q66jTc.js → DiffPanelShell-B8YmcyIS.js} +33 -33
  8. package/dist/client/assets/{DiffWorkerPoolProvider-lEFZi8QR.js → DiffWorkerPoolProvider-XttvFu9p.js} +2 -2
  9. package/dist/client/assets/{PullRequestCodePanel-BpbniIb5.js → PullRequestCodePanel-BwnGKUmC.js} +2 -2
  10. package/dist/client/assets/{Virtualizer-B5NXbN5f.js → Virtualizer-DD1kZz4_.js} +2 -2
  11. package/dist/client/assets/{canvasStateStore-qioLqOoT.js → canvasStateStore-BVOZ0hkY.js} +2 -2
  12. package/dist/client/assets/{cmmdAuthRedirect-lmPzseq5.js → cmmdAuthRedirect-COJsfxk2.js} +2 -2
  13. package/dist/client/assets/{index-D0769c3n.js → index-B6v3s1Ki.js} +57 -57
  14. package/dist/client/assets/{index-4a61qSZ4.css → index-BUnBt2Vq.css} +1 -1
  15. package/dist/client/assets/{src-BL6J64vk.js → src-DEn2qb9-.js} +3 -3
  16. package/dist/client/assets/{toggle-CW3yNjj1.js → toggle-vjiHllrh.js} +2 -2
  17. package/dist/client/assets/{useTriggerFocusGuards-mvO6ygs-.js → useTriggerFocusGuards-DMJ0Xu3Z.js} +2 -2
  18. package/dist/client/index.html +11 -11
  19. package/dist/{open-FIgTDosf.mjs → open-D8mGyWmt.mjs} +3 -3
  20. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/__vite-browser-external-y4e5bF-h.js","assets/rolldown-runtime-BaTzPAyU.js","assets/workspaceReadinessAtom-DsJoTBtH.js","assets/atomRegistry-Bz2MHqst.js","assets/Stream-D8tJNlvy.js","assets/angular-html-CNXPMsN2.js","assets/html-B9culvuL.js","assets/javascript-B0UuInDI.js","assets/css-5Tn8jvjX.js","assets/angular-ts-8naLoWoA.js","assets/scss-4x_6pmF2.js","assets/apl-9RqlfC4L.js","assets/xml-CW-6mCqa.js","assets/java-DD8v6SCw.js","assets/json-Bub81p9x.js","assets/astro-DEOUVaUL.js","assets/typescript-BjG390PS.js","assets/postcss-DmNgU5nO.js","assets/tsx-Dfm676IJ.js","assets/blade-qhaBLKQC.js","assets/html-derivative-PDPS4pLY.js","assets/sql-D4jklS0K.js","assets/bsl-COh4injU.js","assets/sdbl-DSLJ-P-D.js","assets/c-Dy_bYPSr.js","assets/cairo-D9XerGFI.js","assets/python-Cb0jrteY.js","assets/cobol-P2hn7TXm.js","assets/coffee-TsaJbZkc.js","assets/cpp-lB26TbTP.js","assets/regexp-BieKZPiU.js","assets/glsl-XlVJTcyG.js","assets/crystal-BMAMEN5_.js","assets/shellscript-BCP1gymp.js","assets/edge-BsY6Dvy0.js","assets/elixir-BZz-hqbR.js","assets/elm-BRjWHXlm.js","assets/erb-DyHbZJUF.js","assets/ruby-CSzE8NZD.js","assets/haml-B-iWdzkM.js","assets/graphql-B7KqOeHs.js","assets/jsx-CVsoW34k.js","assets/lua-BAG7dOge.js","assets/yaml-_V1dSWlR.js","assets/erlang-BAaIl4Bp.js","assets/markdown-DG21OhJI.js","assets/fortran-fixed-form-DWZWCeWi.js","assets/fortran-free-form-DJxAWUrC.js","assets/fsharp-wFdh0YAg.js","assets/gdresource-C5OXSCS9.js","assets/gdshader-CaVCQW9t.js","assets/gdscript-Cu0HLvj-.js","assets/git-commit-BJn43XzB.js","assets/diff-sVB8Iqu1.js","assets/git-rebase-D753LgR4.js","assets/glimmer-js-CWIQt_ca.js","assets/glimmer-ts-Ntr1SeR3.js","assets/hack-CTggiz-m.js","assets/handlebars-D1AkJdZI.js","assets/http-DiXWLGkE.js","assets/hurl-BZDc3Jtw.js","assets/csv-Bf0U-6f3.js","assets/hxml-DWvzLpTo.js","assets/haxe-DaP2bSo8.js","assets/jinja-C3Dq7ihL.js","assets/jison-DSf4rHmh.js","assets/julia-CZXumuBX.js","assets/r-BY2iEdK7.js","assets/just-D0yza6K2.js","assets/perl-CI7jecTq.js","assets/latex-B_y1lnEN.js","assets/tex-atcWI7rk.js","assets/liquid-DP7VlZYW.js","assets/marko-Cp7qGCQm.js","assets/less-CSmnzIFU.js","assets/mdc-B8NVymwE.js","assets/nextflow-DcTewtep.js","assets/nextflow-groovy-_1_mDVJM.js","assets/nginx-DJl5z2aR.js","assets/nim-Dg-nY8m2.js","assets/php-ChFP9CBe.js","assets/pug-B0fl0unF.js","assets/qml-7gZ29K0p.js","assets/razor-CZy2ujiF.js","assets/csharp-fzmjUXps.js","assets/rst-CfjqtaYt.js","assets/cmake-zaNLyYCh.js","assets/sas-BRUw9CAa.js","assets/shaderlab-BbCj-Nnu.js","assets/hlsl-DWiTaAA1.js","assets/shellsession-D5Ijwb2H.js","assets/soy-DQ7pPiO3.js","assets/sparql-FctWdqhV.js","assets/turtle-Cy-vlDVE.js","assets/stata-WbvGE-VS.js","assets/surrealql-D-lvEuCC.js","assets/svelte-bkJnqoJz.js","assets/templ-BrwbaRfa.js","assets/go-wxR-9SwJ.js","assets/ts-tags-CbY-UhSH.js","assets/twig-83VHDTty.js","assets/vue-DQ8jEd0y.js","assets/vue-html-aJaNf4Hi.js","assets/vue-vine-DtwgVsbD.js","assets/stylus-BJGv9v6m.js","assets/xsl-D3pa6zbH.js"])))=>i.map(i=>d[i]);
2
- (function(){try{var e=typeof window<`u`?window:typeof global<`u`?global:typeof globalThis<`u`?globalThis:typeof self<`u`?self:{};e.SENTRY_RELEASE={id:`forge-web@0.9.10`};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]=`d798db5f-add5-4d07-a7bc-3016e5adaf01`,e._sentryDebugIdIdentifier=`sentry-dbid-d798db5f-add5-4d07-a7bc-3016e5adaf01`)}catch{}})();import{n as e,r as t,t as n}from"./rolldown-runtime-BaTzPAyU.js";import{$ as r,$i as i,$t as a,Ai as o,An as s,Ar as c,At as l,B as u,Ba as d,Bn as f,Br as p,Bt as m,C as h,Ci as g,Cn as _,Da as v,Dn as y,Dt as b,Ei as x,En as S,Er as C,Et as w,F as T,Fn as E,Fr as D,Ft as O,Gn as ee,Gt as te,Hn as k,Hr as A,Ht as ne,Ir as j,It as re,J as ie,Ji as ae,Jn as oe,Jt as se,K as ce,Ki as le,Kn as ue,Kt as de,L as fe,Ln as pe,Lr as me,Lt as he,M as ge,Ma as _e,Mi as ve,Mr as ye,Mt as be,N as xe,Na as Se,Nn as eee,Nt as Ce,O as we,Oa as tee,On as nee,Ot as ree,P as iee,Pa as Te,Pn as Ee,Pt as De,Qn as Oe,Qt as aee,R as ke,Ra as Ae,Rn as je,Rr as Me,Rt as oee,Sa as Ne,Sn as see,T as Pe,Ta as cee,Tn as lee,Tr as Fe,Tt as Ie,U as Le,Un as Re,Ur as ze,Ut as uee,V as dee,Va as fee,Vn as Be,Vr as Ve,Vt as He,W as Ue,Wn as pee,Wr as mee,Wt as hee,X as gee,Xn as _ee,Y as vee,Yi as We,Yn as Ge,Yt as yee,Z as Ke,Zi as qe,Zn as Je,Zt as bee,_ as xee,_i as See,_n as Cee,_r as wee,_t as Tee,aa as Ye,ai as Eee,an as Dee,at as Xe,bi as Oee,bn as kee,br as Aee,bt as Ze,ci as jee,cn as Mee,ct as Qe,di as Nee,dn as Pee,dr as Fee,dt as $e,ei as Iee,en as et,er as Lee,et as tt,fr as Ree,ft as nt,gn as rt,gt as it,hn as at,hr as ot,ht as st,in as ct,it as zee,j as lt,ja as Bee,ji as ut,jn as dt,jr as Vee,jt as ft,ka as Hee,ki as Uee,kr as Wee,kt as pt,li as Gee,ln as Kee,m as qee,ma as mt,mi as ht,mn as gt,mr as _t,mt as vt,ni as Jee,nr as yt,nt as bt,oi as xt,on as Yee,or as St,pn as Ct,pt as wt,q as Tt,qn as Et,qt as Xee,r as Zee,ra as Qee,rn as Dt,rr as $ee,rt as ete,s as tte,si as Ot,sn as nte,st as kt,ti as rte,ui as At,un as jt,ut as Mt,vn as Nt,vr as ite,vt as ate,w as Pt,wi as ote,wn as ste,wr as cte,wt as Ft,x as lte,xi as ute,xn as It,y as dte,yi as fte,yn as Lt,yt as pte,z as Rt,za as mte,zn as zt,zt as Bt}from"./Stream-D8tJNlvy.js";import{i as hte,l as Vt,n as Ht,o as Ut,s as Wt}from"./atomRegistry-Bz2MHqst.js";import{An as Gt,Fn as gte,Mn as Kt,Nn as _te,Pn as vte,Sn as yte,Z as bte,_ as xte,_n as qt,b as Jt,g as Yt,gn as Xt,i as Ste,pn as Zt,v as Cte,xn as Qt,y as wte}from"./CompositeItem-Bsi2e5qV.js";import{$t as Tte,An as $t,At as Ete,B as Dte,Bn as Ote,Bt as en,Cn as tn,Ct as nn,D as kte,Dn as rn,Dt as an,E as on,En as Ate,Et as sn,F as jte,Ft as cn,Gt as Mte,H as ln,Ht as un,In as Nte,It as Pte,J as dn,Jt as Fte,Kt as fn,L as Ite,Ln as Lte,Lt as pn,Mn as mn,Mt as hn,Nn as gn,Nt as Rte,O as zte,On as Bte,Ot as _n,Pn as Vte,Pt as Hte,Q as Ute,Qt as Wte,Rn as Gte,Rt as vn,S as Kte,Sn as yn,T as bn,Tn as qte,Ut as xn,V as Sn,Vn as Jte,Vt as Cn,Wn as Yte,Wt as Xte,X as wn,Xt as Zte,Y as Tn,Yt as Qte,Zt as En,_n as Dn,a as M,an as On,bn as kn,bt as $te,c as An,cn as jn,ct as ene,d as tne,dn as Mn,en as nne,et as Nn,f as rne,fn as Pn,ft as Fn,g as In,gn as Ln,hn as ine,ht as ane,i as one,in as Rn,it as sne,jn as zn,jt as cne,k as Bn,kt as lne,l as une,ln as dne,m as fne,mn as Vn,mt as pne,n as mne,nn as Hn,nt as Un,o as Wn,pn as Gn,pt as Kn,qn,qt as hne,rn as Jn,s as Yn,st as Xn,t as Zn,tn as Qn,tt as $n,u as er,un as tr,ut as nr,v as rr,vt as gne,wn as ir,x as _ne,xn as ar,xt as or,y as vne,zn as yne,zt as sr}from"./src-BL6J64vk.js";import{A as cr,D as lr,E as ur,F as bne,I as dr,M as xne,O as fr,P as Sne,S as Cne,_ as wne,a as pr,b as Tne,c as Ene,j as mr,k as hr,l as Dne,n as gr,s as One,u as kne,v as Ane,w as _r,x as jne,y as Mne}from"./cmmdAuthRedirect-lmPzseq5.js";import{t as N}from"./preload-helper-DDBXDd-E.js";import{n as P,t as vr}from"./transport-1MbRJyXh.js";import{n as Nne,t as Pne}from"./workspaceReadinessAtom-DsJoTBtH.js";function Fne(e){return e[e.length-1]}function Ine(e,t){return typeof e==`function`?e(t):e}var yr=Object.prototype.hasOwnProperty,Lne=Object.prototype.propertyIsEnumerable;function Rne(e){for(let t in e)if(yr.call(e,t))return!0;return!1}var zne=()=>Object.create(null),Bne=(e,t)=>br(e,t,zne);function br(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=wr(e)&&wr(i);if(!a&&!(Sr(e)&&Sr(i)))return i;let o=a?e:xr(e);if(!o)return i;let s=a?i:xr(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:yr.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=br(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function xr(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(!Lne.call(e,r))return!1;t.push(r)}return t}function Sr(e){if(!Cr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Cr(n)||!n.hasOwnProperty(`isPrototypeOf`))}function Cr(e){return Object.prototype.toString.call(e)===`[object Object]`}function wr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Tr(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(!Tr(e[r],t[r],n))return!1;return!0}if(Sr(e)&&Sr(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Tr(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||!Tr(e[o],t[o],n)))return!1;return i===a}return!1}var Vne=/[\x00-\x1f\x7f"<>`{}]/g;function Hne(e){return e.replace(Vne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Er(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 Hne(t)}var Une=[`http:`,`https:`,`mailto:`,`tel:`];function Wne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Gne(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+=Er(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Er(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Kne(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 Dr(){throw Error(`Invariant failed`)}var F=t(fee(),1),Or=F.createContext(null);function kr(e){return F.useContext(Or)}var Ar=F.createContext(void 0),Jne=F.createContext(void 0),Yne=gte();function Xne(e,t){return e===t}function jr(e,t,n=Xne){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,Yne.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Mr={};function Nr(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=br(n.current,i):i}}function Pr(e){let t=kr(),n=F.useContext(e.from?Jne:Ar),r=e.from??n,i=t.stores.getMatchStore(r),a=Nr(e,t),o=jr(i,e=>e?a(e):Mr);if(o!==Mr)return o;(e.shouldThrow??!0)&&Dr()}function Zne(e){return Pr({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 Fr=d(),Ir=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Lr=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(){}},Rr=new class extends Lr{#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`}},Qne={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},zr=new class{#e=Qne;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 $ne(e){setTimeout(e,0)}var ere=typeof window>`u`||`Deno`in globalThis;function Br(){}function tre(e,t){return typeof e==`function`?e(t):e}function Vr(e){return typeof e==`number`&&e>=0&&e!==1/0}function Hr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ur(e,t){return typeof e==`function`?e(t):e}function Wr(e,t){return typeof e==`function`?e(t):e}function nre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Gr(o,t.options))return!1}else if(!qr(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 rre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Kr(t.options.mutationKey)!==Kr(a))return!1}else if(!qr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Gr(e,t){return(t?.queryKeyHashFn||Kr)(e)}function Kr(e){return JSON.stringify(e,(e,t)=>Zr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function qr(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(!qr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!qr(e[r],t[r]))return!1;return!0}return!1}var ire=Object.prototype.hasOwnProperty;function Jr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Xr(e)&&Xr(t);if(!r&&!(Zr(e)&&Zr(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:ire.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Jr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Yr(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 Xr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Zr(e){if(!Qr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Qr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Qr(e){return Object.prototype.toString.call(e)===`[object Object]`}function are(e){return new Promise(t=>{zr.setTimeout(t,e)})}function $r(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Jr(e,t)}function ore(e){return e}function sre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function cre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ei=Symbol();function ti(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ei?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ni(e,t){return typeof e==`function`?e(...t):!!e}function lre(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 ri=(()=>{let e=()=>ere;return{isServer(){return e()},setIsServer(t){e=t}}})();function ii(){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 ure=$ne;function dre(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ure,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 ai=dre(),oi=new class extends Lr{#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 fre(e){return Math.min(1e3*2**e,3e4)}function si(e){return(e??`online`)!==`online`||oi.isOnline()}var ci=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function li(e){let t=!1,n=0,r,i=ii(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ci(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Rr.isFocused()&&(e.networkMode===`always`||oi.isOnline())&&e.canRun(),u=()=>si(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??(ri.isServer()?0:3),o=e.retryDelay??fre,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),are(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 ui=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vr(this.gcTime)&&(this.#e=zr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ri.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(zr.clearTimeout(this.#e),this.#e=void 0)}};function pre(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=>{lre(e,()=>t.signal,()=>n=!0)},u=ti(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?cre:sre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?fi:di,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:di(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 di(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 fi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function mre(e,t){return t?di(e,t)!=null:!1}function hre(e,t){return!t||!e.getPreviousPageParam?!1:fi(e,t)!=null}var gre=class extends ui{#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=hi(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=hi(this.options);e.data!==void 0&&(this.setState(mi(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=$r(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(Br).catch(Br):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=>Wr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ei||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Ur(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:!Hr(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=ti(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`?pre(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=li({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ci&&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 ci){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,...pi(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...mi(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),ai.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function pi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:si(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function mi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function hi(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 gi=class extends Lr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ii(),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),_i(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return vi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return vi(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 Wr(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&&!Yr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&yi(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Wr(this.options.enabled,this.#t)!==Wr(t.enabled,this.#t)||Ur(this.options.staleTime,this.#t)!==Ur(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Wr(this.options.enabled,this.#t)!==Wr(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 vre(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(Br)),t}#g(){this.#b();let e=Ur(this.options.staleTime,this.#t);if(ri.isServer()||this.#r.isStale||!Vr(e))return;let t=Hr(this.#r.dataUpdatedAt,e)+1;this.#d=zr.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,!(ri.isServer()||Wr(this.options.enabled,this.#t)===!1||!Vr(this.#p)||this.#p===0)&&(this.#f=zr.setInterval(()=>{(this.options.refetchIntervalInBackground||Rr.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(zr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(zr.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&&_i(e,t),o=i&&yi(e,n,t,r);(a||o)&&(l={...l,...pi(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=$r(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=$r(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:bi(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Wr(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=ii();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),!Yr(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){ai.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function _re(e,t){return Wr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Wr(t.retryOnMount,e)!==!1)}function _i(e,t){return _re(e,t)||e.state.data!==void 0&&vi(e,t,t.refetchOnMount)}function vi(e,t,n){if(Wr(t.enabled,e)!==!1&&Ur(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&bi(e,t)}return!1}function yi(e,t,n,r){return(e!==t||Wr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&bi(e,n)}function bi(e,t){return Wr(t.enabled,e)!==!1&&e.isStaleByTime(Ur(t.staleTime,e))}function vre(e,t){return!Yr(e.getCurrentResult(),t)}var xi=F.createContext(void 0),Si=e=>{let t=F.useContext(xi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},yre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Fr.jsx)(xi.Provider,{value:e,children:t})),Ci=F.createContext(!1),wi=()=>F.useContext(Ci);Ci.Provider;function bre(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var xre=F.createContext(bre()),Ti=()=>F.useContext(xre),Ei=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ni(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Di=e=>{F.useEffect(()=>{e.clearReset()},[e])},Oi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ni(n,[e.error,r])),ki=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))}},Sre=(e,t)=>e.isLoading&&e.isFetching&&!t,Ai=(e,t)=>e?.suspense&&t.isPending,ji=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Mi(e,t,n){let r=wi(),i=Ti(),a=Si(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,ki(o),Ei(o,i,s),Di(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(ai.batchCalls(e)):Br;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Ai(o,d))throw ji(o,u,i);if(Oi({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&&!ri.isServer()&&Sre(d,r)&&(l?ji(o,u,i):s?.promise)?.catch(Br).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Ni(e,t){return Mi(e,gi,t)}function Cre(e){return e}var wre={[Symbol.iterator](){return Tre}},Tre={next(){return{done:!0,value:void 0}}},Ere=()=>wre,Dre=C,Pi=globalThis.Number,Ore=e=>{if(e===`NaN`)return ve(NaN);if(e===`Infinity`)return ve(1/0);if(e===`-Infinity`)return ve(-1/0);if(e.trim()===``)return ut();let t=Pi(e);return Pi.isNaN(t)?ut():ve(t)},kre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Fi=`~effect/http/HttpClientRequest`,Are={[Fi]:Fi,...We,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Qee(this.headers),body:this.body.toJSON()}},pipe(){return Ae(this,arguments)}};function Ii(e,t,n,r,i,a){let o=Object.create(Are);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var jre=Ii(`GET`,``,hne,ut(),pn,Mte),Li=e=>(t,n)=>Nre(jre,{method:e,url:t,...n??void 0}),Mre=Li(`POST`),Nre=_e(2,(e,t)=>{let n=e;return t.method&&(n=Pre(n,t.method)),t.url&&(n=Lre(n,t.url)),t.headers&&(n=Ri(n,t.headers)),t.urlParams&&(n=Rre(n,t.urlParams)),t.hash&&(n=zre(n,t.hash)),t.body&&(n=Bi(n,t.body)),t.accept&&(n=zi(n,t.accept)),t.acceptJson&&(n=Ire(n)),n}),Pre=_e(2,(e,t)=>Ii(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Fre=_e(3,(e,t,n)=>Ii(e.method,e.url,e.urlParams,e.hash,xn(e.headers,t,n),e.body)),Ri=_e(2,(e,t)=>Ii(e.method,e.url,e.urlParams,e.hash,Xte(e.headers,t),e.body)),zi=_e(2,(e,t)=>Fre(e,`Accept`,t)),Ire=zi(`application/json`),Lre=_e(2,(e,t)=>{if(typeof t==`string`)return Ii(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Fte(n.searchParams),i=fte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Ii(e.method,n.toString(),r,i,e.headers,e.body)}),Rre=_e(2,(e,t)=>Ii(e.method,e.url,Zte(e.urlParams,t),e.hash,e.headers,e.body)),zre=_e(2,(e,t)=>Ii(e.method,e.url,e.urlParams,ve(t),e.headers,e.body)),Bi=_e(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=un(un(n,`Content-Type`),`Content-length`):(t.contentType&&(n=xn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=xn(n,`content-length`,t.contentLength.toString()))),Ii(e.method,e.url,e.urlParams,e.hash,n,t)}),Bre=e=>sr({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${o(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),Vi=`~effect/http/HttpClient`,Hi=Ot(`effect/HttpClient`),Ui=_e(2,(e,t)=>Wi(n=>t(e.postprocess(n)),e.preprocess)),Vre=Ui(bt(Rte)),Wi=(e,t)=>{let n=Object.create(Hre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Hre={[Vi]:Vi,pipe(){return Ae(this,arguments)},...We,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(kre.map(([e,t])=>[t,function(t,n){return this.execute(Li(e)(t,n))}]))},Ure=e=>Wi(t=>bt(t,t=>Nt(n=>{let i=qre.get(t),a=i??new AbortController,o=Qte(t.url,t.urlParams,g(t.hash));if(rte(o))return r(new En({reason:new Tte({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Wee)||n.getRef(Gi)(t)){let r=e(t,s,a.signal,n);return i?r:Ct(e=>Ie(e(r),{onSuccess(e){return qi.register(e,a),et(new Ji(e,a))},onFailure(e){return _t(e)&&a.abort(),tt(e)}}))}return at(n.getRef(Gre)(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(Pte),l=Cn(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Ki)?Ri(t,Bre(r)):t,Ct(o=>o(e(t,s,a.signal,n)).pipe(Lt(r,{captureStackTrace:!1}),Ie({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=Cn(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?et(e):(qi.register(e,a),et(new Ji(e,a)))},onFailure(e){return!i&&_t(e)&&a.abort(),tt(e)}})))})})),et),Wre=_e(2,(e,t)=>{let n=lee(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,a=i&&S(i),o=n?void 0:t.times;return Ui(e,Se(r===`errors-only`?Te:re({schedule:a,times:o,while:Xi}),r===`response-only`?Te:he({while:n||t.while===void 0?Yi:v(Yi,t.while),schedule:i,times:o})))}),Gi=xt(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>tee}),Ki=xt(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:Hee}),Gre=xt(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Kre=e=>dt(Hi)(ie(t=>Ze(e,e=>Ui(e,gt(e=>ht(t,e)))))),qi=(()=>{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,Ji=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[hn]=hn;[cn]=cn;applyInterrupt(e){return Dt(()=>(qi.unregister(this.original),pt(e,()=>ct(()=>{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 xee(()=>(qi.unregister(this.original),Zee(this.original.stream,ct(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[qe](){return this.original[qe]()}pipe(){return Ae(this,arguments)}},Yi=e=>Aee(e)||Jre(e),Jre=e=>Qn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Xi(e.reason.response)),Xi=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Zi=`~effect/FiberSet`,Yre=e=>mt(e,Zi),Xre={[Zi]:Zi,[Symbol.iterator](){return this.state._tag===`Closed`?Ere():this.state.backing[Symbol.iterator]()},...le,toJSON(){return{_id:`FiberMap`,state:this.state}}},Zre=(e,t)=>{let n=Object.create(Xre);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},Qre=()=>ke(ct(()=>Zre(new Set,Ge())),e=>Dt(()=>{let t=e.state;if(t._tag===`Closed`)return rt;e.state={_tag:`Closed`};let n=t.backing;return T(n).pipe(oe(e.deferred))})),Qi=-1,$re=me(D(Fee,j(Qi))),eie=_e(e=>Yre(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Qi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),yt(r)&&(n?.propagateInterruption===!0?!$re(r.cause):!ot(r.cause))&&Et(e.deferred,r))}))}),tie=function(){let e;return()=>(e===void 0&&(e=m(vt)),e)}(),nie=e=>()=>Ze(Tt(),t=>{let n=He(t);return(t,r)=>{if(e.state._tag===`Closed`)return tie();let i=n(t,r);return eie(e,i),i}}),$i=e=>ue(e.deferred),ea=`~effect/socket/Socket`,ta=Ot(`effect/socket/Socket`),rie=`~effect/socket/Socket/CloseEvent`,iie=e=>mt(e,rie),na=`~effect/socket/Socket/SocketError`,aie=e=>mt(e,na),ra=class extends On(`effect/socket/Socket/SocketReadError`)({_tag:mn(`SocketReadError`),cause:Rn}){message=`An error occurred during Read`},oie=class extends On(`effect/socket/Socket/SocketWriteError`)({_tag:mn(`SocketWriteError`),cause:Rn}){message=`An error occurred during Write`},ia=class extends On(`effect/socket/Socket/SocketOpenError`)({_tag:mn(`SocketOpenError`),kind:jn([`Unknown`,`Timeout`]),cause:Rn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},aa=class extends On(`effect/socket/Socket/SocketCloseError`)({_tag:mn(`SocketCloseError`),code:Mn,closeReason:$t(Gn)}){static filterClean(e){return function(t){return sa.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?Eee(t.reason):Iee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},oa=Dn([ra,oie,ia,aa]),sa=class extends ine(na)(`SocketError`,{_tag:mn(`SocketError`),reason:oa}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[na]=na;static is(e){return aie(e)}message=this.reason.message},sie=e=>!0,cie=class extends Ot()(`~effect/socket/Socket/WebSocket`){},ca=class extends Ot()(`@effect/platform/Socket/WebSocketConstructor`){},lie=(e,t)=>ca.use(n=>uie(ke((typeof e==`string`?et(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>ct(()=>e.close(1e3))),t)),uie=(e,t)=>Nt(n=>{let i,a=lt(!1),o=n.context,s=t?.closeCodeIsError??sie,c=(n,c)=>bee(Xe(function*(o){let l=yield*Qre().pipe(ee(o)),u=yield*ee(e,o),d=yield*De(nie(l)(),cie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=bt(ft(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return it(t)?t:rt});return d(t)}let t=n(e.data);it(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),Et(l.deferred,r(new sa({reason:f?new ra({cause:e}):new ia({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),Et(l.deferred,r(new sa({reason:new aa({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=Ge();u.addEventListener(`open`,()=>{f=!0,Et(e,rt)},{once:!0}),yield*ue(e).pipe(jt({duration:t?.openTimeout??1e4,orElse:()=>r(new sa({reason:new ia({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),O($i(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ce($i(l),aa.filterClean(e=>!s(e)),()=>rt)})).pipe(gt(e=>ht(o,e)),Ke(ct(()=>{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=et(e=>a.whenOpen(ct(()=>{let t=i;iie(e)?t.close(e.code,e.reason):t.send(e)})));return et(ta.of({[ea]:ea,run:u,runRaw:c,writer:d}))}),la=Se(lie,dt(ta)),ua=class extends Ot()(`effect/workers/Transferable/Collector`){},die=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ua.of({addAllUnsafe:t,addAll:e=>ct(()=>t(e)),readUnsafe:n,read:ct(n),clearUnsafe:r,clear:ct(r)})},fie=`~effect/workers/WorkerError`,pie=class extends On(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:mn(`WorkerSpawnError`),message:Gn,cause:$t(Rn)}){},mie=class extends On(`effect/workers/WorkerError/WorkerSendError`)({_tag:mn(`WorkerSendError`),message:Gn,cause:$t(Rn)}){},hie=class extends On(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:mn(`WorkerReceiveError`),message:Gn,cause:$t(Rn)}){},gie=class extends On(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:mn(`WorkerUnknownError`),message:Gn,cause:$t(Rn)}){},da=Dn([pie,mie,hie,gie]);On(fie)({_tag:mn(`WorkerError`),reason:da});var fa=`~effect/rpc/RpcClientError`,pa=class extends On(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:mn(`RpcClientDefect`),message:Gn,cause:Rn}){},ma=class extends On(fa)({_tag:mn(`RpcClientError`),reason:Dn([da,oa,Wte,pa])}){[fa]=fa;get message(){return`${this.reason._tag}: ${this.reason.message}`}},ha=e=>typeof e==`bigint`?e:BigInt(e),_ie={_tag:`Ping`},ga;try{ga=new TextDecoder}catch{}var I,_a,L=0,va=[],ya=va,ba=0,xa={},Sa,Ca,wa=0,Ta=0,Ea,Da,Oa=[],ka,Aa={useRecords:!1,mapsAsObjects:!0},ja=class{},Ma=new ja;Ma.name=`MessagePack 0xC1`;var Na=!1,Pa=2,Fa,Ia,La;try{Function(``)}catch{Pa=1/0}var Ra=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 so(()=>(co(),this?this.unpack(t,n):e.prototype.unpack.call(Aa,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(_a=n.end||t.length,L=n.start||0):(L=0,_a=n>-1?n:t.length),ba=0,Ta=0,Ca=null,ya=va,Ea=null,I=t;try{ka=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(xa=this,this.structures)return Sa=this.structures,za(n);(!Sa||Sa.length>0)&&(Sa=[])}else xa=Aa,(!Sa||Sa.length>0)&&(Sa=[]);return za(n)}unpackMultiple(e,t){let n,r=0;try{Na=!0;let i=e.length,a=this?this.unpack(e,i):uo.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(za(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(za());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Na=!1,co()}}_mergeStructures(e,t){Ia&&(e=Ia.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 za(e){try{if(!xa.trusted&&!Na){let e=Sa.sharedLength||0;e<Sa.length&&(Sa.length=e)}let t;if(xa.randomAccessStructure&&I[L]<64&&I[L]>=32&&Fa?(t=Fa(I,L,_a,xa),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=_a):t=Va(),Ea&&=(L=Ea.postBundlePosition,null),Na&&(Sa.restoreStructures=null),L==_a)Sa&&Sa.restoreStructures&&Ba(),Sa=null,I=null,Da&&=null;else if(L>_a)throw Error(`Unexpected end of MessagePack data`);else if(!Na){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 Sa&&Sa.restoreStructures&&Ba(),co(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>_a)&&(e.incomplete=!0),e}}function Ba(){for(let e in Sa.restoreStructures)Sa[e]=Sa.restoreStructures[e];Sa.restoreStructures=null}function Va(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=Sa[e&63]||xa.getStructures&&Wa()[e&63];return t?(t.read||=Ha(t,e&63),t.read()):e}}else if(e<144){if(e-=128,xa.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=no();e===`__proto__`&&(e=`__proto_`),t[e]=Va()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Va(),Va());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=Va();return xa.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Ta>=L)return Ca.slice(L-wa,(L+=t)-wa);if(Ta==0&&_a<140){let e=t<16?Za(t):Xa(t);if(e!=null)return e}return Ga(t)}{let t;switch(e){case 192:return null;case 193:return Ea?(t=Va(),t>0?Ea[1].slice(Ea.position1,Ea.position1+=t):Ea[0].slice(Ea.position0,Ea.position0-=t)):Ma;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return $a(t);case 197:return t=ka.getUint16(L),L+=2,$a(t);case 198:return t=ka.getUint32(L),L+=4,$a(t);case 199:return eo(I[L++]);case 200:return t=ka.getUint16(L),L+=2,eo(t);case 201:return t=ka.getUint32(L),L+=4,eo(t);case 202:if(t=ka.getFloat32(L),xa.useFloat32>2){let e=lo[(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=ka.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=ka.getUint16(L),L+=2,t;case 206:return t=ka.getUint32(L),L+=4,t;case 207:return xa.int64AsType===`number`?(t=ka.getUint32(L)*4294967296,t+=ka.getUint32(L+4)):xa.int64AsType===`string`?t=ka.getBigUint64(L).toString():xa.int64AsType===`auto`?(t=ka.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=ka.getBigUint64(L),L+=8,t;case 208:return ka.getInt8(L++);case 209:return t=ka.getInt16(L),L+=2,t;case 210:return t=ka.getInt32(L),L+=4,t;case 211:return xa.int64AsType===`number`?(t=ka.getInt32(L)*4294967296,t+=ka.getUint32(L+4)):xa.int64AsType===`string`?t=ka.getBigInt64(L).toString():xa.int64AsType===`auto`?(t=ka.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=ka.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return io(I[L++]&63);{let e=Oa[t];if(e)return e.read?(L++,e.read(Va())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,io(I[L++]&63,I[L++])):eo(2);case 214:return eo(4);case 215:return eo(8);case 216:return eo(16);case 217:return t=I[L++],Ta>=L?Ca.slice(L-wa,(L+=t)-wa):yie(t);case 218:return t=ka.getUint16(L),L+=2,Ta>=L?Ca.slice(L-wa,(L+=t)-wa):bie(t);case 219:return t=ka.getUint32(L),L+=4,Ta>=L?Ca.slice(L-wa,(L+=t)-wa):xie(t);case 220:return t=ka.getUint16(L),L+=2,qa(t);case 221:return t=ka.getUint32(L),L+=4,qa(t);case 222:return t=ka.getUint16(L),L+=2,Ja(t);case 223:return t=ka.getUint32(L),L+=4,Ja(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 vie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ha(e,t){function n(){if(n.count++>Pa){let n=e.read=Function(`r`,`return function(){return `+(xa.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:vie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(Va);return e.highByte===0&&(e.read=Ua(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]=Va()}return xa.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Ua(t,n):n}var Ua=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=Sa[r]||Wa()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=Ha(i,e),i.read()};function Wa(){let e=so(()=>(I=null,xa.getStructures()));return Sa=xa._mergeStructures(e,Sa)}var Ga=Ka,yie=Ka,bie=Ka,xie=Ka;function Ka(e){let t;if(e<16&&(t=Za(e)))return t;if(e>64&&ga)return ga.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+=Ya.apply(String,r),r.length=0)}return r.length>0&&(t+=Ya.apply(String,r)),t}function qa(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Va();return xa.freezeData?Object.freeze(t):t}function Ja(e){if(xa.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=no();e===`__proto__`&&(e=`__proto_`),t[e]=Va()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Va(),Va());return t}}var Ya=String.fromCharCode;function Xa(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 Ya.apply(String,n)}function Za(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return Ya(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return Ya(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return Ya(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 Ya(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return Ya(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 Ya(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return Ya(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 Ya(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return Ya(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 Ya(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return Ya(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 Ya(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return Ya(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 Ya(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 Ya(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Qa(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=ka.getUint16(L),L+=2;break;case 219:t=ka.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Ka(t)}function $a(e){return xa.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function eo(e){let t=I[L++];if(Oa[t]){let n;return Oa[t](I.subarray(L,n=L+=e),e=>{L=e;try{return Va()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var to=Array(4096);function no(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Ta>=L)return Ca.slice(L-wa,(L+=e)-wa);if(!(Ta==0&&_a<180))return Ga(e)}else return L--,ro(Va());let t=(e<<5^(e>1?ka.getUint16(L):e>0?I[L]:0))&4095,n=to[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=ka.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=[],to[t]=n,n.bytes=e;r<i;)a=ka.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Za(e):Xa(e);return s==null?n.string=Ga(e):n.string=s}function ro(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(xa.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 io=(e,t)=>{let n=Va().map(ro),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=Sa[e];return i&&(i.isShared||Na)&&((Sa.restoreStructures||(Sa.restoreStructures=[]))[e]=i),Sa[e]=n,n.read=Ha(n,r),n.read()};Oa[0]=()=>{},Oa[0].noBuffer=!0,Oa[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 ao={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Oa[101]=()=>{let e=Va();if(!ao[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return ao[e[0]](e[1],{cause:e[2]})},Oa[105]=e=>{if(xa.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=ka.getUint32(L-4);Da||=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};Da.set(t,i);let a=Va();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},Oa[112]=e=>{if(xa.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=ka.getUint32(L-4),n=Da.get(t);return n.used=!0,n.target},Oa[115]=()=>new Set(Va());var oo=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Sie=typeof globalThis==`object`?globalThis:window;Oa[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=oo[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 Sie[r](n)},Oa[120]=()=>{let e=Va();return new RegExp(e[0],e[1])};var Cie=[];Oa[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,Ea=Cie,Ea=[Qa(),Qa()],Ea.position0=0,Ea.position1=0,Ea.postBundlePosition=L,L=n,Va()},Oa[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 so(e){La&&La();let t=_a,n=L,r=ba,i=wa,a=Ta,o=Ca,s=ya,c=Da,l=Ea,u=new Uint8Array(I.slice(0,_a)),d=Sa,f=Sa.slice(0,Sa.length),p=xa,m=Na,h=e();return _a=t,L=n,ba=r,wa=i,Ta=a,Ca=o,ya=s,Da=c,Ea=l,I=u,Na=m,Sa=d,Sa.splice(0,Sa.length,...f),xa=p,ka=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function co(){I=null,Da=null,Sa=null}var lo=Array(147);for(let e=0;e<256;e++)lo[e]=+(`1e`+Math.floor(45.15-e*.30103));var uo=new Ra({useRecords:!1});uo.unpack,uo.unpackMultiple,uo.unpack;var wie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var fo;try{fo=new TextEncoder}catch{}var po,mo,ho=typeof Buffer<`u`,go=ho?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,_o=ho?Buffer:Uint8Array,vo=ho?4294967296:2144337920,R,yo,bo,z=0,xo,So=null,Tie,Eie=21760,Die=/[\u0080-\uFFFF]/,Co=Symbol(`record-id`),Oie=class extends Ra{constructor(e){super(e),this.offset=0;let t,n,r,i,a=_o.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:fo&&fo.encodeInto?function(e,t){return fo.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 go(8192),bo=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),xo=R.length-10,xo-z<2048?(R=new go(R.length),bo=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),xo=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`?(So=[],So.size=1/0):So=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[Co]=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)&&!mo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=So;if(So&&Do(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&&(bo.setUint32(n.position+t,bo.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&bo.setUint32(n.position+t,bo.getUint32(n.position+t)+a),z+=e.length*6,z>xo&&w(z),o.offset=z;let s=kie(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=Aie(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][Co]=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,bo.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>xo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(So&&n>=4&&n<4096){if((So.size+=n)>Eie){let e,n=(So[0]?So[0].length*3+So[1].length:0)+10;z+n>xo&&(R=w(z+n));let r;So.position?(r=So,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,Do(t,y,0),bo.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),So=[``,``],So.previous=r,So.size=0,So.position=e}let r=Die.test(e);So[+!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>xo&&(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,bo.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,bo.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,bo.setInt16(z,e),z+=2):(R[z++]=210,bo.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,bo.setFloat32(z,e);let n;if(t<4||(n=e*lo[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,bo.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,bo.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,bo.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=po.length;t<n;t++){let n=mo[t];if(e instanceof n){let n=po[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=bo,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>xo&&w(z),{target:R,targetView:bo,position:z-e}),y)}finally{r&&(R=r,bo=i,z=a,xo=R.length-10)}o&&(o.length+z>xo&&w(o.length+z),z=Eo(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,bo.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,bo.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,bo.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),ho)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>xo&&w(n.length+z),z=Eo(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,bo.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[Co];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[Co];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>vo)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(vo,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 go(n);return bo=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,xo=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[Co]=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()[Co]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=xo,c=t;R=yo,z=0,t=0,R||(yo=R=new go(8192)),xo=R.length-10,T(e,n,i),yo=R;let l=z;if(R=a,z=o,xo=s,t=c,l>1){let e=z+l-1;e>xo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(yo.slice(0,l),n),z=e}else R[r+t]=yo[0]},D=e=>{let i=Tie(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:bo,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)),bo=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};mo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ja],po=[{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?wo(e,16,t):To(ho?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==_o&&this.moreTypes?wo(e,oo.indexOf(n.name),t):To(e,t)}},{pack(e,t){this.moreTypes?wo(e,17,t):To(ho?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function wo(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 To(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 Eo(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 kie(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 Do(e,t,n){if(So.length>0){bo.setUint32(So.position+e,z+n-So.position-e),So.stringsPosition=z-e;let r=So;So=null,t(r[0]),t(r[1])}}function Aie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var Oo=new Oie({useRecords:!1});Oo.pack,Oo.pack;var{NEVER:jie,ALWAYS:Mie,DECIMAL_ROUND:Nie,DECIMAL_FIT:Pie}=wie,ko=class extends Ot()(`effect/rpc/RpcSerialization`){},Fie=ko.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)}}}),Ao=pe(ko)(Fie),Iie=e=>Dt(()=>{let t=new Set,n=new Map,r=new Map,i=(e,t)=>ie(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),rt});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return nt(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*Ce(Dt(()=>i(e)),t)}return yield*ree(w,()=>(t.delete(e),r.delete(e),rt))})}}))}),Lie=BigInt(0),Rie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Lie++),o=yield*Tt(),s=At(o,je),c=new Map,l=!1;yield*zt(s,Nt(e=>(l=!0,u(Lee(e.id)))));let u=Xe(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?Pt(n.queue):Pe(n.queue,e.cause):n.resume(e)}),d=e=>{let r=cne(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?vn(s.headers):pn,l=s?.context??Gee();if(!r){let r=t=>p(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):at(`${n}.${e._tag}`,{attributes:t.spanAttributes},r)}let u=m(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:lte(Ze(u,tte))}},p=(e,n,r,i,o,s,u)=>Nt(d=>{if(l)return vt;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(No),o)});if(u)return p;let m;return pt(Le(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?Lt(r,{captureStackTrace:!1}):Te,He(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),Rt(iee(m),_(f,Array.from(e),s))))}),m=Xe(function*(e,r,o,s,u,d){if(l)return yield*vt;let p=i?void 0:yield*pte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),m=xe(),g=a(),v=Nee(m.context,je);yield*f(v,e=>c.has(g)?(c.delete(g),_(g,yt(e)?Array.from(wee(e.cause)):[],d)):rt);let y=yield*h(u);return c.set(g,{_tag:`Queue`,rpc:e,queue:y,scope:v,context:d}),yield*r(e=>t.onFromClient({message:e,context:d,discard:!1}),{_tag:`Request`,id:g,tag:e._tag,payload:o,...p?{traceId:p.traceId,spanId:p.spanId,sampled:p.sampled}:{},headers:en(m.getRef(No),s)}).pipe(p?Lt(p,{captureStackTrace:!1}):Te,Ue(e=>Pe(y,e)),st,Mt(v,{startImmediately:!0})),y}),g=e=>{let t=[];for(let n of e.middlewares.values()){let e=o.mapUnsafe.get(`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},_=(e,n,r)=>Le(i=>{let a=xe();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Mee(1e3),He(a.context)).addObserver(()=>{i(rt)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?rt:we(i.queue,e.values).pipe(r?bt(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):Te,Ue(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),rt):e.exit._tag===`Success`?Pt(n.queue):Pe(n.queue,e.exit.cause)):rt}case`Defect`:return u(_ee(e.defect));case`ClientEnd`:return rt}},y;if(t.flatten){let t=new Map;y=function(n,r,i){let a=t.get(n);return a||(a=d(e.requests.get(n)),t.set(n,a)),a(r,i)}}else y={},e.requests.forEach(e=>{y[e._tag]=d(e)});return{client:y,write:v}}),zie=0,jo=Xe(function*(e,t){let n=zie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*Po,s=new Map,{client:c,write:u}=yield*Rie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?die():void 0,c=xe(),u={rpc:r,context:a?jee(c.context,ua,a):c.context,schemas:Bie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Ce(u.context),l,bt(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)}):rt;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):rt;case`Eof`:return rt}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=ha(e.requestId),n=s.get(t);return!n||ote(n.schemas.decodeChunk)?rt:n.schemas.decodeChunk.value(e.values).pipe(Ce(n.context),l,bt(t=>u({_tag:`Chunk`,clientId:0,requestId:ha(e.requestId),values:t})),b(t=>u({_tag:`Exit`,clientId:0,requestId:ha(e.requestId),exit:Oe(t)})))}case`Exit`:{let t=ha(e.requestId),n=s.get(t);return n?(s.delete(t),n.schemas.decodeExit(e.exit).pipe(Ce(n.context),l,Ie({onSuccess:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:Oe(e)})}))):rt}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Wie(e.defect)});case`ClientProtocolError`:{let t=Je(e.error);return kt(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return rt}}).pipe(Ue(ate),st,$e),c}),Mo=new WeakMap,Bie=e=>{let t=Mo.get(e);if(t!==void 0)return t;let n=Ete(e.successSchema);return t={decodeChunk:Uee(n,e=>yn(gn(dne(e.success)))),encodePayload:qte(gn(e.payloadSchema)),decodeExit:yn(gn(lne(e)))},Mo.set(e,t),t},No=xt(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>pn}),Po=class extends Ot()(`effect/rpc/RpcClient/Protocol`){static make=Iie},Fo=e=>Po.make(Xe(function*(t,n){let i=yield*ta,a=yield*ko,o=yield*aee(Uie),s=new Map,c=yield*i.writer,d=a.makeUnsafe(),f=yield*Hie(c(d.encode(_ie))),p,m=Dt(()=>(p=void 0,x(o)?o.value.onConnect:rt)),h=e=>kt(n,n=>t(n,e));return yield*Dt(()=>(d=a.makeUnsafe(),f.reset(),i.runRaw(e=>{try{let n=d.decode(e);if(n.length===0)return;let r=0;return Cee({while:()=>r<n.length,body:()=>{let e=n[r++];if(e._tag===`Pong`)return f.onPong(),rt;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:Bee})}catch(e){return h({_tag:`ClientProtocolError`,error:new ma({reason:new pa({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(O(bt(f.timeout,()=>r(new sa({reason:new ia({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(bt(()=>r(new sa({reason:new aa({code:1e3})}))),x(o)?Ke(o.value.onDisconnect):Te,Yee(t=>{let n=Ree(t),r=Jee(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?rt:(p=new ma({reason:r?n.success.reason:new pa({message:`Unknown socket error`,cause:Fe(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),he(e?.retryPolicy??Vie),u({module:`RpcClient`,method:`makeProtocolSocket`}),$e),{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?rt:l(c(n))},supportsAck:!0,supportsTransferables:!1}})),Vie=_(500,1.5).pipe(see(nee(5e3))),Hie=Xe(function*(e){let t=!0,n=0,r=lt();return yield*Dt(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(vee(`5 seconds`),wt,Qe,st,$e),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Uie=class extends Ot()(`effect/rpc/RpcClient/ConnectionHooks`){},Wie=kn(Rn);function Io(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function Gie(e){return e?.target.wsBaseUrl??null}function Kie(e){return e?.target.httpBaseUrl??null}function qie(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function Jie(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function Yie(e){let t=Jie(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function Xie(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 Zie(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function Qie(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Lo(e){let t=e.capabilities,n=t.runtime??Yie(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??Xie(n),tools:t.tools??Zie(n),projects:t.projects??Qie(t,n)}}function $ie(e){return e?Lo(e).projects.cloudProjects:!1}function eae(e){return e?Lo(e).runtime.workspaceProxy??!1:!1}function Ro(e,t){return{environmentId:e,projectId:t}}function zo(e,t){return{environmentId:e,threadId:t}}var Bo=`scoped:v1:`;function Vo(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Bo)?`${Bo}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Ho(e){return Vo(e)}function Uo(e){return Vo(e)}function tae(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 Wo(e){if(e.startsWith(Bo))return tae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Go(e){let t=Wo(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Ko(e){let t=Wo(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var nae=1e3,rae=64e3;jo(Wn);function iae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(nae*2**e),rae)}var qo=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Jo(e){return Array.isArray(e)?e.map(Jo):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Jo(t)])):e}function aae(e){let t=JSON.stringify(Jo(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var oae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function sae(e){return e._tag===`Ping`?oae:null}function cae(e){if(e.policy===null||e.policy.method!==e.method)throw new qo(`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 qo(`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 lae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new qo(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new qo(`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 qo(`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 qo(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var uae=[{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.codeGraphSummary,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.codeGraphNeighborhood,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.codeGraphSearch,requiredScope:`workspace.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.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:ln.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:ln.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:ln.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:ln.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:ln.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:ln.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:ln.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:ln.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`}],dae=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,ln.dispatchCommand]),fae=uae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?dae.has(e.method)?`frame`:`metadata-only`:`none`}}),pae=lae({registeredMethods:[...Wn.requests.keys()],policies:fae}),Yo={"project.create":{requiredScope:`project.write`,deliveryClass:`create-command`},"project.meta.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`}},mae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function hae(e){if(e.method!==ln.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!mae.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 qo(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Xo(e){let t=pae.get(e.method)??null,n=cae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==ln.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new qo(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in Yo))throw new qo(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=Yo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new qo(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Zo=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},Qo=class extends Zo{},$o=class extends Zo{},es=class extends Zo{},gae=class extends Zo{},_ae=class extends Zo{},vae=class extends Zo{},yae=class extends Zo{},bae=class extends Zo{},xae=class extends Zo{},Sae=class extends Zo{},ts=class extends Zo{},ns=Cae(globalThis,{});function Cae(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 wae(){if(ns!==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-y4e5bF-h.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e.subtle}catch(e){throw new ts(e)}}var rs=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await wae())}},is={Base:0,Psk:1,Auth:2,AuthPsk:3},Tae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},as={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},os={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},ss=new Uint8Array,cs=0n,ls=1n,us=2n,Eae=new Uint8Array([75,69,77,0,0]),ds=new Uint8Array([72,80,75,69,45,118,49]);function fs(e){return new Uint8Array(ps(e))}function ps(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 Dae=class extends rs{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:as.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:ss}),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(ds,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(ds,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):ps(e);if(n.byteLength!==this.hashSize)throw new Qo(`The salt length must be the same as the hashSize`);let r=ps(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=ps(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=ss,c=fs(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=ps(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:ps(e),info:ps(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===ss)throw Error(`Not initialized. Call init()`)}},Oae=class extends Dae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:as.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}})}},ms=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function hs(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 gs(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function _s(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 kae(){if(ns!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-y4e5bF-h.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e}catch{throw Error(`failed to load Crypto`)}}function Aae(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 jae=new Uint8Array([101,97,101,95,112,114,107]),Mae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Nae(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 Pae=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(Eae);r.set(hs(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(ps(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(ps(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=ps(e);if(t.byteLength>8192)throw new Qo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():ms(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=ms(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=gs(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=gs(new Uint8Array(n),new Uint8Array(r));else{let t=ms(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Nae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new gae(e)}}async decap(e){let t=ps(e.enc),n=await this._prim.deserializePublicKey(t),r=ms(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=ms(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)):gs(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=gs(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 _ae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(jae,e),r=this._kdf.buildLabeledInfo(Mae,t,this.secretSize);return await this._kdf.extractAndExpand(ss,n,r,this.secretSize)}},vs=[`deriveBits`],Fae=new Uint8Array([100,107,112,95,112,114,107]),Iae=new Uint8Array([115,107]),ys=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=[])}},Lae=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 $o(e))}}async deserializePublicKey(e){try{return await this._importRawKey(ps(e),!0)}catch(e){throw new es(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new $o(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(ps(e),!1)}catch(e){throw new es(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 es(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new ys(this._algName,e,`private`,vs);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new ts(e)}}async deriveKeyPair(e){try{let t=ps(e),n=await this._hkdf.labeledExtract(ss.buffer,Fae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Iae,ss,this._nSk),i=new ys(this._algName,new Uint8Array(r),`private`,vs);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Sae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new ys(this._algName,t,`public`))}catch(e){return Promise.reject(new es(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new $o(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 ys(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:vs))})}_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 ys(this._algName,_s(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new ys(this._algName,_s(e.d),`private`,vs)))})}};function Rae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function bs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function xs(e,t,n=``){let r=Rae(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 Ss(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 Cs(e,t){xs(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function zae(e){if(typeof e==`bigint`){if(!Ps(e))throw Error(`positive bigint expected, got `+e)}else bs(e);return e}function ws(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ts(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Bae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Es(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ds(e,t){return e<<32-t|e>>>t}var Os=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Vae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Hae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Uae(e){if(xs(e),Os)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Vae[e[n]];return t}var ks={_0:48,_9:57,A:65,F:70,a:97,f:102};function As(e){if(e>=ks._0&&e<=ks._9)return e-ks._0;if(e>=ks.A&&e<=ks.F)return e-(ks.A-10);if(e>=ks.a&&e<=ks.f)return e-(ks.a-10)}function Wae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Os)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=As(e.charCodeAt(i)),a=As(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 Gae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=cs;for(let n=0;n<e.length;n++){let r=As(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|Hae[r]}return t}function js(e){bs(e,`numberToBigint`);let t=e,n=cs,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function Ms(e){return Gae(Uae(Ns(xs(e)).reverse()))}function Kae(e,t){bs(t),e=zae(e);let n=Wae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function qae(e,t){return Kae(e,t).reverse()}function Ns(e){return Uint8Array.from(e)}function Ps(e){return typeof e==`bigint`&&0n<=e}function Jae(e,t,n){return Ps(e)&&Ps(t)&&Ps(n)&&t<=e&&e<n}function Fs(e,t,n,r){if(!Jae(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Yae(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 Xae(e=32){let t=await kae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function Zae(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function Qae(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);bs(e.outputLen),bs(e.blockLen)}function $ae(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 Is=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}),Qae(e),xs(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),Ts(r)}update(e){return Ss(this),this.iHash.update(e),this}digestInto(e){Ss(this),xs(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()}},Ls=(e,t,n)=>new Is(e,t).update(n).digest();Ls.create=(e,t)=>new Is(e,t);function eoe(e,t,n){return e&t^~e&n}function toe(e,t,n){return e&t^e&n^t&n}var noe=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=Es(this.buffer)}update(e){Ss(this),xs(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=Es(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){Ss(this),Cs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Ts(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,js(this.length*8),i),this.process(n,0);let o=Es(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()}},Rs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),roe=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]),zs=new Uint32Array(64),ioe=class extends noe{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)zs[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=zs[e-15],n=zs[e-2],r=Ds(t,7)^Ds(t,18)^t>>>3,i=Ds(n,17)^Ds(n,19)^n>>>10;zs[e]=i+zs[e-7]+r+zs[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=Ds(o,6)^Ds(o,11)^Ds(o,25),u=l+t+eoe(o,s,c)+roe[e]+zs[e]|0,d=(Ds(n,2)^Ds(n,13)^Ds(n,22))+toe(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(){Ts(zs)}destroy(){this.set(0,0,0,0,0,0,0,0),Ts(this.buffer)}},aoe=class extends ioe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Rs[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Rs[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Rs[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Rs[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Rs[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Rs[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Rs[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Rs[7]|0})}},Bs=$ae(()=>new aoe,Zae(1));function Vs(e,t){let n=e%t;return n>=0n?n:t+n}function Hs(e,t,n){let r=e;for(;t-->cs;)r*=r,r%=n;return r}function ooe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function soe(e){return Yae(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function coe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=soe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||Xae,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?us**254n:us**447n,p=f+(o?8n*us**251n-ls:4n*us**445n-ls)+ls,m=e=>Vs(e,t),h=g(u);function g(e){return qae(m(e),l)}function _(e){let t=Ns(xs(e,l,`uCoordinate`));return o&&(t[31]&=127),m(Ms(t))}function v(e){return Ms(r(Ns(xs(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){Fs(`u`,e,cs,t),Fs(`scalar`,n,f,p);let r=n,a=e,o=ls,s=cs,l=e,u=ls,h=cs;for(let e=c-1n;e>=cs;e--){let t=r>>e&ls;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)),xs(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:ooe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Us(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var loe=(e,t)=>{function n(n,...r){if(xs(n,void 0,`key`),!Bae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];xs(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&xs(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`);xs(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,xs(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(xs(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 uoe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function doe(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 Ws(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&&!poe(t))throw Error(`invalid output, must be aligned`);return t}function foe(e,t,n){Us(n);let r=new Uint8Array(16),i=Es(r);return i.setBigUint64(0,js(t),n),i.setBigUint64(8,js(e),n),r}function poe(e){return e.byteOffset%4==0}var Gs=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),moe=Gs(`expand 16-byte k`),hoe=Gs(`expand 32-byte k`),goe=ws(moe),_oe=ws(hoe);function Ks(e,t){return e<<t|e>>>32-t}function qs(e){return e.byteOffset%4==0}var Js=64,voe=16,Ys=2**32-1,Xs=Uint32Array.of();function yoe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Js),u=ws(l),d=qs(i)&&qs(a),f=d?ws(i):Xs,p=d?ws(a):Xs;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Ys)throw Error(`arx: counter overflow`);let h=Math.min(Js,c-m);if(d&&h===Js){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<voe;t++)n=e+t,p[n]=f[n]^u[t];m+=Js;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function boe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=uoe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return bs(i),bs(o),Us(a),Us(n),(t,s,c,l,u=0)=>{xs(t,void 0,`key`),xs(s,void 0,`nonce`),xs(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),xs(l,void 0,`output`),bs(u),u<0||u>=Ys)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=Ns(t)),h=_oe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=goe,f.push(m);else throw xs(t,32,`arx key`),Error(`invalid key size`);qs(s)||f.push(s=Ns(s));let g=ws(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,ws(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=ws(s);return yoe(e,h,g,v,c,l,u,o),Ts(...f),l}}function Zs(e,t){return e[t++]&255|(e[t++]&255)<<8}var xoe=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=Ns(xs(e,32,`key`));let t=Zs(e,0),n=Zs(e,2),r=Zs(e,4),i=Zs(e,6),a=Zs(e,8),o=Zs(e,10),s=Zs(e,12),c=Zs(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]=Zs(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=Zs(e,t+0),_=Zs(e,t+2),v=Zs(e,t+4),y=Zs(e,t+6),b=Zs(e,t+8),x=Zs(e,t+10),S=Zs(e,t+12),C=Zs(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),O=i[4]+((y>>>4|b<<12)&8191),ee=i[5]+(b>>>1&8191),te=i[6]+((b>>>14|x<<2)&8191),k=i[7]+((x>>>11|S<<5)&8191),A=i[8]+((S>>>8|C<<8)&8191),ne=i[9]+(C>>>5|r),j=0,re=j+w*o+5*h*T+5*m*E+5*p*D+5*f*O;j=re>>>13,re&=8191,re+=5*d*ee+5*u*te+5*l*k+5*c*A+5*s*ne,j+=re>>>13,re&=8191;let ie=j+w*s+T*o+5*h*E+5*m*D+5*p*O;j=ie>>>13,ie&=8191,ie+=5*f*ee+5*d*te+5*u*k+5*l*A+5*c*ne,j+=ie>>>13,ie&=8191;let ae=j+w*c+T*s+E*o+5*h*D+5*m*O;j=ae>>>13,ae&=8191,ae+=5*p*ee+5*f*te+5*d*k+5*u*A+5*l*ne,j+=ae>>>13,ae&=8191;let oe=j+w*l+T*c+E*s+D*o+5*h*O;j=oe>>>13,oe&=8191,oe+=5*m*ee+5*p*te+5*f*k+5*d*A+5*u*ne,j+=oe>>>13,oe&=8191;let se=j+w*u+T*l+E*c+D*s+O*o;j=se>>>13,se&=8191,se+=5*h*ee+5*m*te+5*p*k+5*f*A+5*d*ne,j+=se>>>13,se&=8191;let ce=j+w*d+T*u+E*l+D*c+O*s;j=ce>>>13,ce&=8191,ce+=ee*o+5*h*te+5*m*k+5*p*A+5*f*ne,j+=ce>>>13,ce&=8191;let le=j+w*f+T*d+E*u+D*l+O*c;j=le>>>13,le&=8191,le+=ee*s+te*o+5*h*k+5*m*A+5*p*ne,j+=le>>>13,le&=8191;let ue=j+w*p+T*f+E*d+D*u+O*l;j=ue>>>13,ue&=8191,ue+=ee*c+te*s+k*o+5*h*A+5*m*ne,j+=ue>>>13,ue&=8191;let de=j+w*m+T*p+E*f+D*d+O*u;j=de>>>13,de&=8191,de+=ee*l+te*c+k*s+A*o+5*h*ne,j+=de>>>13,de&=8191;let fe=j+w*h+T*m+E*p+D*f+O*d;j=fe>>>13,fe&=8191,fe+=ee*u+te*l+k*c+A*s+ne*o,j+=fe>>>13,fe&=8191,j=(j<<2)+j|0,j=j+re|0,re=j&8191,j>>>=13,ie+=j,i[0]=re,i[1]=ie,i[2]=ae,i[3]=oe,i[4]=se,i[5]=ce,i[6]=le,i[7]=ue,i[8]=de,i[9]=fe}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;Ts(n)}update(e){Ss(this),xs(e),e=Ns(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(){Ts(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ss(this),Cs(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 Soe(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 Coe=Soe(e=>new xoe(e));function woe(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,O=f,ee=p,te=m,k=h,A=g,ne=_,j=v,re=y,ie=b,ae=x;for(let e=0;e<a;e+=2)S=S+E|0,j=Ks(j^S,16),te=te+j|0,E=Ks(E^te,12),S=S+E|0,j=Ks(j^S,8),te=te+j|0,E=Ks(E^te,7),C=C+D|0,re=Ks(re^C,16),k=k+re|0,D=Ks(D^k,12),C=C+D|0,re=Ks(re^C,8),k=k+re|0,D=Ks(D^k,7),w=w+O|0,ie=Ks(ie^w,16),A=A+ie|0,O=Ks(O^A,12),w=w+O|0,ie=Ks(ie^w,8),A=A+ie|0,O=Ks(O^A,7),T=T+ee|0,ae=Ks(ae^T,16),ne=ne+ae|0,ee=Ks(ee^ne,12),T=T+ee|0,ae=Ks(ae^T,8),ne=ne+ae|0,ee=Ks(ee^ne,7),S=S+D|0,ae=Ks(ae^S,16),A=A+ae|0,D=Ks(D^A,12),S=S+D|0,ae=Ks(ae^S,8),A=A+ae|0,D=Ks(D^A,7),C=C+O|0,j=Ks(j^C,16),ne=ne+j|0,O=Ks(O^ne,12),C=C+O|0,j=Ks(j^C,8),ne=ne+j|0,O=Ks(O^ne,7),w=w+ee|0,re=Ks(re^w,16),te=te+re|0,ee=Ks(ee^te,12),w=w+ee|0,re=Ks(re^w,8),te=te+re|0,ee=Ks(ee^te,7),T=T+E|0,ie=Ks(ie^T,16),k=k+ie|0,E=Ks(E^k,12),T=T+E|0,ie=Ks(ie^T,8),k=k+ie|0,E=Ks(E^k,7);let oe=0;r[oe++]=o+S|0,r[oe++]=s+C|0,r[oe++]=c+w|0,r[oe++]=l+T|0,r[oe++]=u+E|0,r[oe++]=d+D|0,r[oe++]=f+O|0,r[oe++]=p+ee|0,r[oe++]=m+te|0,r[oe++]=h+k|0,r[oe++]=g+A|0,r[oe++]=_+ne|0,r[oe++]=v+j|0,r[oe++]=y+re|0,r[oe++]=b+ie|0,r[oe++]=x+ae|0}var Toe=boe(woe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Eoe=new Uint8Array(16),Qs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Eoe.subarray(n))},Doe=new Uint8Array(32);function $s(e,t,n,r,i){i!==void 0&&xs(i,void 0,`AAD`);let a=e(t,n,Doe),o=foe(r.length,i?i.length:0,!0),s=Coe.create(a);i&&Qs(s,i),Qs(s,r),s.update(o);let c=s.digest();return Ts(a,o),c}var ec=loe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=Ws(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=$s(e,t,n,s,r);return a.set(c,o),Ts(c),a},decrypt(i,a){a=Ws(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=$s(e,t,n,o,r);if(!doe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Ts(c),a}}))(Toe)),Ooe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(ps(e))}async seal(e,t,n){return await this._seal(ps(e),ps(t),ps(n))}async open(e,t,n){return await this._open(ps(e),ps(t),ps(n))}_seal(e,t,n){return new Promise(r=>{r(ec(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(ec(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},koe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:os.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 Ooe(e)}};function tc(){return new Promise((e,t)=>{t(new ts(`Not supported`))})}var Aoe=new Uint8Array([115,101,99]),nc=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 tc()}async open(e,t){return await tc()}async export(e,t){let n=ps(e);if(n.byteLength>8192)throw new Qo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Aoe,new Uint8Array(n),t)}catch(e){throw new vae(e)}}},joe=class extends nc{},Moe=class extends nc{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}},rc=class extends nc{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=hs(e.seq,e.baseNonce.byteLength);return Aae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new xae(`Message limit reached`);e.seq+=1}},Noe=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)},Poe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},ic,ac=class{constructor(){ic.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Noe(this,ic,`f`);return Poe(this,ic,t,`f`),await n,e}};ic=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)},Foe=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,Ioe=class extends rc{constructor(){super(...arguments),sc.set(this,void 0)}async open(e,t=ss.buffer){Foe(this,sc,oc(this,sc,`f`)??new ac,`f`);let n=await oc(this,sc,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),ps(e),ps(t))}catch(e){throw new bae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};sc=new WeakMap;var cc=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)},Loe=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},lc,Roe=class extends rc{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),lc.set(this,void 0),this.enc=r}async seal(e,t=ss.buffer){Loe(this,lc,cc(this,lc,`f`)??new ac,`f`);let n=await cc(this,lc,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),ps(e),ps(t))}catch(e){throw new yae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};lc=new WeakMap;var zoe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Boe=new Uint8Array([101,120,112]),Voe=new Uint8Array([105,110,102,111,95,104,97,115,104]),Hoe=new Uint8Array([107,101,121]),Uoe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Woe=new Uint8Array([115,101,99,114,101,116]),Goe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Koe=class extends rs{constructor(e){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof e.kem==`number`)throw new Qo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new Qo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new Qo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array(Goe),this._suiteId.set(hs(this._kem.id,2),4),this._suiteId.set(hs(this._kdf.id,2),6),this._suiteId.set(hs(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?is.Base:is.Auth:e.senderKey===void 0?is.Psk:is.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?is.Base:is.Auth:e.senderPublicKey===void 0?is.Psk:is.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=ss.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=ss.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?ss:fs(n.psk.id),i=await this._kdf.labeledExtract(ss,Uoe,r),a=n.info===void 0?ss:fs(n.info),o=await this._kdf.labeledExtract(ss,Voe,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?ss:fs(n.psk.key),l=this._kdf.buildLabeledIkm(Woe,c),u=this._kdf.buildLabeledInfo(Boe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===os.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(Hoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(zoe,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 Moe(this._api,this._kdf,i.exporterSecret,n):new Roe(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 joe(this._api,this._kdf,r.exporterSecret):new Ioe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new Qo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new Qo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new Qo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new Qo(`Too long psk.id`)}}},qoe=class extends Koe{},Joe=1n,uc=2n,Yoe=3n,Xoe=5n,dc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function Zoe(e){let t=10n,n=80n,r=dc,i=e*e%r*e%r,a=Hs(Hs(i,uc,r)*i%r,Joe,r)*e%r,o=Hs(a,Xoe,r)*a%r,s=Hs(o,t,r)*o%r,c=Hs(s,20n,r)*s%r,l=Hs(c,40n,r)*c%r;return{pow_p_5_8:Hs(Hs(Hs(Hs(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,uc,r)*e%r,b2:i}}function Qoe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var $oe=(()=>{let e=dc;return coe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=Zoe(t);return Vs(Hs(n,Yoe,e)*r,e)},adjustScalarBytes:Qoe})})(),ese=class extends Lae{constructor(e){super(`X25519`,32,$oe,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new $o(e))}}},fc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,tse=2**31,nse=65536,rse=16,pc=32,mc=(1n<<255n)-19n,hc=new TextEncoder,gc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function _c(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 ise=new Set([0n,1n,_c(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),_c(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),mc-1n]),ase=new Uint8Array,vc=class extends Oae{async extract(e,t){return ps(Ls(Bs,e.byteLength===0?new Uint8Array(this.hashSize):fs(e),fs(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=fs(e),i=fs(t),a=new Uint8Array(n),o=ase;for(let e=1,t=0;t<a.byteLength;e+=1){let n=Sc([o,i,Uint8Array.of(e)]);o=new Uint8Array(Ls(Bs,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 ps(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},yc=new qoe({kem:new class extends Pae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Tae.DhkemX25519HkdfSha256,new ese(e),e)}}(new vc),kdf:new vc,aead:new koe}),bc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function xc(e){return new Uint8Array(e.slice(0))}function ose(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Sc(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 Cc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new bc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function wc(e){if(!Number.isSafeInteger(e)||e<0)throw new bc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function sse(e){return Sc([Cc(e.byteLength),e])}function Tc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function cse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function Ec(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+=gc[o>>>18&63],t+=gc[o>>>12&63],n+1<e.byteLength&&(t+=gc[o>>>6&63]),n+2<e.byteLength&&(t+=gc[o&63])}return t}function Dc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new bc(`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=gc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(Ec(t)!==e)throw new bc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function lse(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 ise.has(n%mc)}var use={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new bc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return xc(await globalThis.crypto.subtle.digest(`SHA-256`,ose(e)))}},Oc={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new bc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function kc(e,t){let n=hc.encode(e).byteLength;if(n===0||n>256)throw new bc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function dse(e){let t=hc.encode(e).byteLength;if(t===0||t>65536)throw new bc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${nse} UTF-8 bytes.`)}async function Ac(e,t=use){dse(e.exactCompactTicket),kc(e.channelId,`Channel ID`),kc(e.runtimeId,`Runtime ID`),wc(e.connectionEpoch);let n=await t.sha256(hc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new bc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function fse(e){return Ec(e.ticketDigest)}async function pse(e=Oc){let t=new Uint8Array(await e.randomBytes(pc));if(t.byteLength!==pc)throw new bc(`endpoint_key_invalid`,`The endpoint random source must return ${pc} bytes.`);try{return Ec(t)}finally{t.fill(0)}}function jc(e){return Sc([hc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,Tc(e.direction)])}function Mc(e){return Sc([hc.encode(`forge-relay`),Cc(4),e.binding.ticketDigest,hc.encode(e.binding.channelId),Tc(e.binding.direction),cse(e.frameClass),wc(e.sequence),hc.encode(e.binding.runtimeId),wc(e.binding.connectionEpoch),Cc(e.ciphertextLength)].map(sse))}async function mse(e=Oc){let t=new Uint8Array(await e.randomBytes(pc));if(t.byteLength!==pc)throw new bc(`endpoint_key_invalid`,`The endpoint random source must return ${pc} bytes.`);try{return await yc.kem.deriveKeyPair(t)}catch(e){throw new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function Nc(e){try{return Ec(xc(await yc.kem.serializePublicKey(e)))}catch(e){throw new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function hse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new bc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function gse(e){try{let t=Dc(e);if(t.byteLength!==pc)throw Error(`Invalid endpoint key length.`);if(lse(t))throw new bc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await yc.kem.deserializePublicKey(t)}catch(e){throw e instanceof bc?e:new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var Pc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Fc=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=tse||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new bc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function _se(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 bc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var vse=class{binding;context;encapsulatedKey;queue=new Pc;budget=new Fc;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=Ec(xc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new bc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+rse;this.budget.assertAvailable(t);let n=this.sequence,r=Mc({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=xc(await this.context.seal(e.plaintext,r))}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new bc(`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:Ec(i)}})}},yse=class{binding;context;queue=new Pc;budget=new Fc;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(_se(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new bc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Dc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Mc({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=xc(await this.context.open(t,n))}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new bc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function bse(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Oc).randomBytes(pc)),t.byteLength!==pc)throw Error(`The endpoint random source must return ${pc} bytes.`);let n=await yc.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:jc(e.binding),ekm:t});return new vse(e.binding,n)}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function xse(e){try{let t=await yc.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Dc(e.encapsulatedKey),info:jc(e.binding)});return new yse(e.binding,t)}catch(e){throw e instanceof bc?e:new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Sse=128,Cse=2097152,wse=864e5,Ic=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Lc(e){return typeof e==`string`&&e.length>0}function Rc(e){return Lc(e)&&Number.isFinite(Date.parse(e))}function Tse(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function Ese(e){return Lc(e.transportRequestId)&&Lc(e.runtimeId)&&Lc(e.actorSessionId)&&Lc(e.durableRequestId)&&Lc(e.method)}function Dse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Ose(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Lc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function kse(e){return!Tse(e.status)||e.errorCode!==null&&!Lc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Lc(e.errorCode):e.errorCode===null}function Ase(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Ese(t)&&Dse(t)&&Ose(t)&&kse(t)&&Rc(t.createdAt)&&Rc(t.updatedAt)}function jse(e){try{return JSON.parse(e)}catch{throw new Ic(`Forge relay control journal is corrupt.`)}}function Mse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Lc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Ase)}function Nse(e){let t=new Set(e.map(zc)),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 Pse(e){let t=jse(e);if(!Mse(t))throw new Ic(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Nse(n)||t.nextSequence<=r)throw new Ic(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Fse(){return crypto.randomUUID()}function zc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Bc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Ise(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)=>Bc[t.status]>Bc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function Vc(e){let t=e.randomUUID??Fse,n=e.now??(()=>new Date),r=e.maxRecords??Sse,i=e.maxBytes??Cse,a=e.maxReplayAgeMs??wse;if(r<1||i<1||a<1)throw new Ic(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?Pse(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 Ic(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new Ic(`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=zc(e);return{key:t,existing:c.records.find(e=>zc(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 Ic(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new Ic(`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 Ic(`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 Ic(`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(zc({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 Ic(`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(zc({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 Ic(`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(zc(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 Lse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Rse=tn(rne),zse=ir(tne),Bse=ir(er),Vse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Hc(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 Uc(e,t){let n=JSON.parse(e),r=sae(n);if(r!==null)return{messageType:`request`,...r};let i=Hse(n,t);if(i!==null)return i;let a=Use(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function Hse(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=Xo({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Hc(e.headers,An.requestId)??e.id,method:e.tag,...n}}function Use(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 Wc(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 Wse=new Set([`network`,`server`,`auth`,`permission`,`client`]),Gse=new Set([`network`,`server`]);function Kse(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`&&Wse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function Jse(e){if(e.retryable===!0||typeof e.kind==`string`&&Gse.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Gc(e){let t=Kse(e);return{code:qse(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:Jse(t)}}function Kc(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 Yse(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values(An).includes(e[0])}function qc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Xse(e){if(!Array.isArray(e))return null;for(let t of e){let e=qc(t);if(e?._tag!==`Fail`)continue;let n=qc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function Zse(e){let t=qc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:Xse(t.cause)??`RELAY_RPC_FAILED`}function Jc(e){if(typeof e!=`string`)return null;try{let t=Rse(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function Qse(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 Yc(e,t,n){if(typeof e==`string`)try{let r=qc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=Zse(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 $se(e){let t=Hc(e,An.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function ece(e){return{issuedAt:Hc(e,An.issuedAt)??new Date().toISOString(),expiresAt:Hc(e,An.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function tce(e){if(e!==2&&e!==3&&e!==4)throw new qo(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function nce(e){let t=hae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=rce(e.context);if(e.acquire===void 0)throw new qo(`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 rce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new qo(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Xc(e.channelId),channelTicketDigest:Xc(e.channelTicketDigest),runtimeEndpointKeyId:Xc(e.runtimeEndpointKeyId),controlEndpointKeyId:Xc(e.controlEndpointKeyId)}}function Xc(e){if(typeof e==`string`&&e.length>0)return e;throw new qo(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function ice(e){return e===void 0?{}:{sequence:e}}function Zc(e){return e===void 0?{}:{actionGrant:e}}async function ace(e){let t=Uc(e.data,e.context.scopes),n=JSON.parse(e.data),r=ece(n.headers),i=$se(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await nce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=tce(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,...ice(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Zc(o)}:{protocolVersion:4,...c,...Zc(o)}}function Qc(e){return typeof e==`string`&&e.length>0}function oce(e){return[e.protocolVersion===4,Qc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===fc,Qc(e.channelId),Qc(e.runtimeEndpointKeyId),Qc(e.runtimeEndpointPublicKey),Qc(e.controlEndpointKeyId),Qc(e.controlEndpointPublicKey),Qc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function $c(e){if(!oce(e))throw new qo(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function sce(e){if(await Nc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new qo(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await gse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Ac({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Ac({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 bse({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function el(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function cce(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 lce(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 uce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new qo(`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 qo(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await xse({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var dce=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=Kc(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`,Kc(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=Uc(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=Gc(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`,Wc(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 ace({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 qo(`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 vce({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=>!Yse(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&&Yc(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=Gc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Wc(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 sce($c(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Vse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Gc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Wc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Jc(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`,Wc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=Qse(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=$c(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:fse(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=$c(this.route);if(t===null||n===null||!el(e,r,`handshake`))throw new qo(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await uce({channel:t,route:r,message:e})).open(e),a=zse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!cce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new qo(`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=Jc(e);if(t?.type!==`relay.encrypted-frame`)throw new qo(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!el(t,$c(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new qo(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Bse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!lce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new qo(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);Yc(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 fce(e,t,n=tl,r=Vc({storage:Lse(),randomUUID:n.randomUUID}),i={},a){return new dce(e,t,n,r,i,a).asWebSocket()}var pce=jo(one);async function mce(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 tl={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:mce},nl=`forge-relay-binding=`,hce=3e4;function gce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(nl))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 _ce(e){let t=e.crypto??tl,n=e.bindingTtlMs??hce,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=`${nl}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=gce(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?.(),fce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}async function vce(e){let t=e.issuedAt??new Date,n=e.crypto??tl;return{[An.requestId]:e.requestId??n.randomUUID(),[An.sequence]:String(e.sequence),[An.issuedAt]:t.toISOString(),[An.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[An.payloadHash]:await n.sha256Base64Url(aae(e.payload))}}function yce(e,t){return $te(une,({rpc:t,request:n,next:r})=>nt(function*(){return Xo({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function bce(e,t=tl){return pce.pipe(be(yce(e,t)))}function xce(e){let t=e.crypto??tl,n=_ce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=ft(n.acquireSocketUrl).pipe(l),i=pe(ca,n.constructSocket),a=la(r).pipe(E(i)),o=e.delayForRetry??iae,s=It(y(e.maxRetries??10),e=>et(Ve(o(e)??0)));return dt(Po,Fo({retryPolicy:s,retryTransientErrors:!0})).pipe(E(Ee(a,Ao)))}var rl=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Sce(e){let t=await mse(e),n=await Nc(t.publicKey);return{keyPair:t,publicKey:n,keyId:hse(`control`,n),channelNonce:await pse(e)}}function Cce(e){return{hpkeSuite:fc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function wce(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 rl(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:fc,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 il=`~effect/ManagedRuntime`,al=(e,t)=>{let n=t?.memoMap??eee(),r=pee(`parallel`),i=k(r,`sequential`),a={onFiberStart:fe(r)},o=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Nt(t=>(c||=m(Dee(s(e,n,i),e=>ct(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),zee(ge(c)))),u={[il]:il,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?ne(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return ne(u.disposeEffect)},disposeEffect:Dt(()=>(u.contextEffect=gee(`ManagedRuntime disposed`),u.cachedContext=void 0,Be(u.scope,St))),runFork(e,t){return u.cachedContext===void 0?m(ol(u,e),o(t)):He(u.cachedContext)(e,o(t))},runCallback(e,t){return u.cachedContext===void 0?oee(ol(u,e),o(t)):Bt(u.cachedContext)(e,o(t))},runSyncExit(e){return u.cachedContext===void 0?Xee(ol(u,e)):se(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?de(ol(u,e)):yee(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?uee(ol(u,e),o(t)):hee(u.cachedContext)(e,o(t))},runPromise(e,t){return u.cachedContext===void 0?ne(ol(u,e),o(t)):te(u.cachedContext)(e,o(t))}};return u};function ol(e,t){return bt(e.contextEffect,e=>Ce(t,e))}function sl(e,t=nr){return`${e}\0${t}`}function Tce(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=sl(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(sl(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(sl(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 cl={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function ll(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Ece(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?ll(t.keyframe):null}function Dce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?cl:t.streamGeneration>e.streamGeneration?ll(t.keyframe):null}function Oce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return ll(t.keyframe);if(t.sequence<=e.observedSequence)return cl;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function kce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return cl;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?cl:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Ace(e,t){return Ece(e,t)??Dce(e,t)??Oce(e,t)??kce(e,t)}function jce(e,t){let n=Ace(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}}ir(fne);var ul=mte(),dl=`Forge`,fl=`Alpha`,pl=dl,ml=`0.9.10`;function hl(e){return{_tag:`Value`,value:e}}function gl(e,t){return{_tag:`Record`,keys:e,value:t}}function _l(e,t){return{_tag:`Array`,length:e,value:t}}qn(`SourceError`);var vl=xt(`effect/ConfigProvider`,{defaultValue:()=>xl()}),yl={...le,toJSON(){return{_id:`ConfigProvider`}}};function bl(e,t,n){let r=Object.create(yl);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 xl(e){let t=e?.env??{APP_VERSION:`0.9.10`,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:``,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.9.10`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Sl(t);return bl(e=>et(wl(n,t,e)))}function Sl(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 Cl=/^(0|[1-9][0-9]*)$/;function wl(e,t,n){let r=t[n.map(String).join(`_`)],i=Tl(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:hl(r):a.every(e=>Cl.test(e))?_l(Math.max(...a.map(e=>parseInt(e,10)))+1,r):gl(new Set(a),r)}function Tl(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 El=`~effect/Config`,Dl=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Ol={...le,...ae,[El]:El,asEffect(){return bt(vl.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function kl(e){let t=Object.create(Ol);return t.parse=e,t}var Al=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*Al(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*Al(e,[...t,i]));return r}}}),jl=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*jl(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=Lte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*jl(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*jl(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Al(t,n);case`Suspend`:return yield*jl(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 Ml(e,t){let n=Vte(e),r=Gte(n),i=Ote(n.ast),a=typeof t==`string`?[t]:t??[];return kl(e=>{let t=e.prefix?[...e.prefix,...a]:a;return jl(i,e,a).pipe(ete(e=>r(e).pipe(Ft(e=>new Nte(t.length>0?new Yte(t,e):e)))),Ft(e=>new Dl(e)))})}var Nl=(e,t,n)=>{let r=Pn(e,t),i=Gn.pipe(ar(Pn(Gn,Gn),Jte(n)),ar(r));return Dn([r,i])},Pl=_te(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),Fl=!1,Il=!1,Ll=null,Rl=null,zl=null,Bl=!1,Vl=new Set;function Mce(e){if(Fl||Il)return;if(!e.publicKey||!e.host){Il=!0;return}if(Ll)return;if(typeof window>`u`||typeof location>`u`){Il=!0;return}let t=e.publicKey,n=e.host;Ll=N(async()=>{let{default:e}=await import(`./module-44GyzBiP.js`);return{default:e}},[]).then(({default:e})=>{Rl=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{Fl=!0,zl&&Hl(zl),Ul(),Vl.forEach(e=>e())}})}).catch(()=>{Il=!0,Rl=null})}function Hl(e){if(zl=e,!Fl||!Rl)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),Rl.identify(e.cmmdUserId,t)}function Nce(e){return!Fl||!Rl?!1:Rl.isFeatureEnabled(e)===!0}function Ul(){!Rl||Bl||(Bl=!0,Rl.onFeatureFlags(()=>{Vl.forEach(e=>e())}))}function Pce(e){return Vl.add(e),Fl&&Rl&&(Ul(),e()),()=>{Vl.delete(e)}}var Wl=`token`;function Gl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Kl(e){let t=Gl(e).get(Wl)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Wl)?.trim()??``;return n.length>0?n:null}function Fce(e){let t=new URL(e.toString()),n=Gl(t);return n.has(Wl)&&(n.delete(Wl),t.hash=n.toString()),t.searchParams.delete(Wl),t}function ql(e,t){let n=new URL(e.toString());return n.searchParams.delete(Wl),n.hash=new URLSearchParams([[Wl,t]]).toString(),n}function Ice(e,t){let n=new URL(e);return n.pathname=`/login`,ql(n,t).toString()}function Lce(e){return ql(new URL(`/login`,window.location.href),e).toString()}function Rce(e){let t=new URL(e),n=Kl(t),r=new URL(`forge:///pair`);return r.searchParams.set(`serverUrl`,t.origin),n&&r.searchParams.set(Wl,n),r.toString()}var B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Jl=`10.70.0`;function Yl(){return Xl(V),V}function Xl(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.70.0`,t[Jl]=t[`10.70.0`]||{}}function Zl(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Jl]=r[`10.70.0`]||{};return i[e]||(i[e]=t())}var Ql=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],zce=`Sentry Logger `,$l={};function eu(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys($l);r.forEach(e=>{let r=$l[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Bce(){ru().enabled=!0}function Vce(){ru().enabled=!1}function tu(){return ru().enabled}function Hce(...e){nu(`log`,...e)}function Uce(...e){nu(`warn`,...e)}function Wce(...e){nu(`error`,...e)}function nu(e,...t){B&&tu()&&eu(()=>{V.console[e](`${zce}[${e}]:`,...t)})}function ru(){return B?Zl(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:Bce,disable:Vce,isEnabled:tu,log:Hce,warn:Uce,error:Wce},iu=50,au=/\(error: (.*)\)/,ou=/captureMessage|captureException/;function su(...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
+ (function(){try{var e=typeof window<`u`?window:typeof global<`u`?global:typeof globalThis<`u`?globalThis:typeof self<`u`?self:{};e.SENTRY_RELEASE={id:`forge-web@0.9.10`};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]=`041becac-a096-45d7-967d-826f73725a8a`,e._sentryDebugIdIdentifier=`sentry-dbid-041becac-a096-45d7-967d-826f73725a8a`)}catch{}})();import{n as e,r as t,t as n}from"./rolldown-runtime-BaTzPAyU.js";import{$ as r,$i as i,$t as a,Ai as o,An as s,Ar as c,At as l,B as u,Ba as d,Bn as f,Br as p,Bt as m,C as h,Ci as g,Cn as _,Da as v,Dn as y,Dt as b,Ei as x,En as S,Er as C,Et as w,F as T,Fn as E,Fr as D,Ft as O,Gn as ee,Gt as te,Hn as k,Hr as A,Ht as ne,Ir as j,It as re,J as ie,Ji as ae,Jn as oe,Jt as se,K as ce,Ki as le,Kn as ue,Kt as de,L as fe,Ln as pe,Lr as me,Lt as he,M as ge,Ma as _e,Mi as ve,Mr as ye,Mt as be,N as xe,Na as Se,Nn as eee,Nt as Ce,O as we,Oa as tee,On as nee,Ot as ree,P as iee,Pa as Te,Pn as Ee,Pt as De,Qn as Oe,Qt as aee,R as ke,Ra as Ae,Rn as je,Rr as Me,Rt as oee,Sa as Ne,Sn as see,T as Pe,Ta as cee,Tn as lee,Tr as Fe,Tt as Ie,U as Le,Un as Re,Ur as ze,Ut as uee,V as dee,Va as fee,Vn as Be,Vr as Ve,Vt as He,W as Ue,Wn as pee,Wr as mee,Wt as hee,X as gee,Xn as _ee,Y as vee,Yi as We,Yn as Ge,Yt as yee,Z as Ke,Zi as qe,Zn as Je,Zt as bee,_ as xee,_i as See,_n as Cee,_r as wee,_t as Tee,aa as Ye,ai as Eee,an as Dee,at as Xe,bi as Oee,bn as kee,br as Aee,bt as Ze,ci as jee,cn as Mee,ct as Qe,di as Nee,dn as Pee,dr as Fee,dt as $e,ei as Iee,en as et,er as Lee,et as tt,fr as Ree,ft as nt,gn as rt,gt as it,hn as at,hr as ot,ht as st,in as ct,it as zee,j as lt,ja as Bee,ji as ut,jn as dt,jr as Vee,jt as ft,ka as Hee,ki as Uee,kr as Wee,kt as pt,li as Gee,ln as Kee,m as qee,ma as mt,mi as ht,mn as gt,mr as _t,mt as vt,ni as Jee,nr as yt,nt as bt,oi as xt,on as Yee,or as St,pn as Ct,pt as wt,q as Tt,qn as Et,qt as Xee,r as Zee,ra as Qee,rn as Dt,rr as $ee,rt as ete,s as tte,si as Ot,sn as nte,st as kt,ti as rte,ui as At,un as jt,ut as Mt,vn as Nt,vr as ite,vt as ate,w as Pt,wi as ote,wn as ste,wr as cte,wt as Ft,x as lte,xi as ute,xn as It,y as dte,yi as fte,yn as Lt,yt as pte,z as Rt,za as mte,zn as zt,zt as Bt}from"./Stream-D8tJNlvy.js";import{i as hte,l as Vt,n as Ht,o as Ut,s as Wt}from"./atomRegistry-Bz2MHqst.js";import{An as Gt,Fn as gte,Mn as Kt,Nn as _te,Pn as vte,Sn as yte,Z as bte,_ as xte,_n as qt,b as Jt,g as Yt,gn as Xt,i as Ste,pn as Zt,v as Cte,xn as Qt,y as wte}from"./CompositeItem-BNUtGUNS.js";import{$t as Tte,An as $t,At as Ete,B as Dte,Bn as Ote,Bt as en,Cn as tn,Ct as nn,D as kte,Dn as rn,Dt as an,E as on,En as Ate,Et as sn,F as jte,Ft as cn,Gt as Mte,H as ln,Ht as un,In as Nte,It as Pte,J as dn,Jt as Fte,Kt as fn,L as Ite,Ln as Lte,Lt as pn,Mn as mn,Mt as hn,Nn as gn,Nt as Rte,O as zte,On as Bte,Ot as _n,Pn as Vte,Pt as Hte,Q as Ute,Qt as Wte,Rn as Gte,Rt as vn,S as Kte,Sn as yn,T as bn,Tn as qte,Ut as xn,V as Sn,Vn as Jte,Vt as Cn,Wn as Yte,Wt as Xte,X as wn,Xt as Zte,Y as Tn,Yt as Qte,Zt as En,_n as Dn,a as M,an as On,bn as kn,bt as $te,c as An,cn as jn,ct as ene,d as tne,dn as Mn,en as nne,et as Nn,f as rne,fn as Pn,ft as Fn,g as In,gn as Ln,hn as ine,ht as ane,i as one,in as Rn,it as sne,jn as zn,jt as cne,k as Bn,kt as lne,l as une,ln as dne,m as fne,mn as Vn,mt as pne,n as mne,nn as Hn,nt as Un,o as Wn,pn as Gn,pt as Kn,qn,qt as hne,rn as Jn,s as Yn,st as Xn,t as Zn,tn as Qn,tt as $n,u as er,un as tr,ut as nr,v as rr,vt as gne,wn as ir,x as _ne,xn as ar,xt as or,y as vne,zn as yne,zt as sr}from"./src-DEn2qb9-.js";import{A as cr,D as lr,E as ur,F as bne,I as dr,M as xne,O as fr,P as Sne,S as Cne,_ as wne,a as pr,b as Tne,c as Ene,j as mr,k as hr,l as Dne,n as gr,s as One,u as kne,v as Ane,w as _r,x as jne,y as Mne}from"./cmmdAuthRedirect-COJsfxk2.js";import{t as N}from"./preload-helper-DDBXDd-E.js";import{n as P,t as vr}from"./transport-1MbRJyXh.js";import{n as Nne,t as Pne}from"./workspaceReadinessAtom-DsJoTBtH.js";function Fne(e){return e[e.length-1]}function Ine(e,t){return typeof e==`function`?e(t):e}var yr=Object.prototype.hasOwnProperty,Lne=Object.prototype.propertyIsEnumerable;function Rne(e){for(let t in e)if(yr.call(e,t))return!0;return!1}var zne=()=>Object.create(null),Bne=(e,t)=>br(e,t,zne);function br(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=wr(e)&&wr(i);if(!a&&!(Sr(e)&&Sr(i)))return i;let o=a?e:xr(e);if(!o)return i;let s=a?i:xr(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:yr.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=br(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function xr(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(!Lne.call(e,r))return!1;t.push(r)}return t}function Sr(e){if(!Cr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Cr(n)||!n.hasOwnProperty(`isPrototypeOf`))}function Cr(e){return Object.prototype.toString.call(e)===`[object Object]`}function wr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Tr(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(!Tr(e[r],t[r],n))return!1;return!0}if(Sr(e)&&Sr(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Tr(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||!Tr(e[o],t[o],n)))return!1;return i===a}return!1}var Vne=/[\x00-\x1f\x7f"<>`{}]/g;function Hne(e){return e.replace(Vne,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Er(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 Hne(t)}var Une=[`http:`,`https:`,`mailto:`,`tel:`];function Wne(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Gne(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+=Er(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Er(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Kne(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 Dr(){throw Error(`Invariant failed`)}var F=t(fee(),1),Or=F.createContext(null);function kr(e){return F.useContext(Or)}var Ar=F.createContext(void 0),Jne=F.createContext(void 0),Yne=gte();function Xne(e,t){return e===t}function jr(e,t,n=Xne){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,Yne.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Mr={};function Nr(e,t){let n=F.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=br(n.current,i):i}}function Pr(e){let t=kr(),n=F.useContext(e.from?Jne:Ar),r=e.from??n,i=t.stores.getMatchStore(r),a=Nr(e,t),o=jr(i,e=>e?a(e):Mr);if(o!==Mr)return o;(e.shouldThrow??!0)&&Dr()}function Zne(e){return Pr({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 Fr=d(),Ir=typeof window<`u`&&(window.desktopBridge!==void 0||window.nativeApi!==void 0),Lr=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(){}},Rr=new class extends Lr{#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`}},Qne={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},zr=new class{#e=Qne;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 $ne(e){setTimeout(e,0)}var ere=typeof window>`u`||`Deno`in globalThis;function Br(){}function tre(e,t){return typeof e==`function`?e(t):e}function Vr(e){return typeof e==`number`&&e>=0&&e!==1/0}function Hr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ur(e,t){return typeof e==`function`?e(t):e}function Wr(e,t){return typeof e==`function`?e(t):e}function nre(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Gr(o,t.options))return!1}else if(!qr(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 rre(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Kr(t.options.mutationKey)!==Kr(a))return!1}else if(!qr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Gr(e,t){return(t?.queryKeyHashFn||Kr)(e)}function Kr(e){return JSON.stringify(e,(e,t)=>Zr(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function qr(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(!qr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!qr(e[r],t[r]))return!1;return!0}return!1}var ire=Object.prototype.hasOwnProperty;function Jr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Xr(e)&&Xr(t);if(!r&&!(Zr(e)&&Zr(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:ire.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Jr(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Yr(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 Xr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Zr(e){if(!Qr(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Qr(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Qr(e){return Object.prototype.toString.call(e)===`[object Object]`}function are(e){return new Promise(t=>{zr.setTimeout(t,e)})}function $r(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Jr(e,t)}function ore(e){return e}function sre(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function cre(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ei=Symbol();function ti(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ei?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ni(e,t){return typeof e==`function`?e(...t):!!e}function lre(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 ri=(()=>{let e=()=>ere;return{isServer(){return e()},setIsServer(t){e=t}}})();function ii(){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 ure=$ne;function dre(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ure,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 ai=dre(),oi=new class extends Lr{#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 fre(e){return Math.min(1e3*2**e,3e4)}function si(e){return(e??`online`)!==`online`||oi.isOnline()}var ci=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function li(e){let t=!1,n=0,r,i=ii(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new ci(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Rr.isFocused()&&(e.networkMode===`always`||oi.isOnline())&&e.canRun(),u=()=>si(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??(ri.isServer()?0:3),o=e.retryDelay??fre,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),are(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 ui=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vr(this.gcTime)&&(this.#e=zr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ri.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(zr.clearTimeout(this.#e),this.#e=void 0)}};function pre(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=>{lre(e,()=>t.signal,()=>n=!0)},u=ti(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?cre:sre;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?fi:di,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:di(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 di(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 fi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function mre(e,t){return t?di(e,t)!=null:!1}function hre(e,t){return!t||!e.getPreviousPageParam?!1:fi(e,t)!=null}var gre=class extends ui{#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=hi(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=hi(this.options);e.data!==void 0&&(this.setState(mi(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=$r(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(Br).catch(Br):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=>Wr(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ei||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Ur(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:!Hr(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=ti(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`?pre(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=li({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ci&&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 ci){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,...pi(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...mi(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),ai.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function pi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:si(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function mi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function hi(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 gi=class extends Lr{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=ii(),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),_i(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return vi(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return vi(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 Wr(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&&!Yr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&yi(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Wr(this.options.enabled,this.#t)!==Wr(t.enabled,this.#t)||Ur(this.options.staleTime,this.#t)!==Ur(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Wr(this.options.enabled,this.#t)!==Wr(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 vre(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(Br)),t}#g(){this.#b();let e=Ur(this.options.staleTime,this.#t);if(ri.isServer()||this.#r.isStale||!Vr(e))return;let t=Hr(this.#r.dataUpdatedAt,e)+1;this.#d=zr.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,!(ri.isServer()||Wr(this.options.enabled,this.#t)===!1||!Vr(this.#p)||this.#p===0)&&(this.#f=zr.setInterval(()=>{(this.options.refetchIntervalInBackground||Rr.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(zr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(zr.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&&_i(e,t),o=i&&yi(e,n,t,r);(a||o)&&(l={...l,...pi(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=$r(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=$r(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:bi(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Wr(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=ii();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),!Yr(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){ai.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function _re(e,t){return Wr(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Wr(t.retryOnMount,e)!==!1)}function _i(e,t){return _re(e,t)||e.state.data!==void 0&&vi(e,t,t.refetchOnMount)}function vi(e,t,n){if(Wr(t.enabled,e)!==!1&&Ur(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&bi(e,t)}return!1}function yi(e,t,n,r){return(e!==t||Wr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&bi(e,n)}function bi(e,t){return Wr(t.enabled,e)!==!1&&e.isStaleByTime(Ur(t.staleTime,e))}function vre(e,t){return!Yr(e.getCurrentResult(),t)}var xi=F.createContext(void 0),Si=e=>{let t=F.useContext(xi);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},yre=({client:e,children:t})=>(F.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Fr.jsx)(xi.Provider,{value:e,children:t})),Ci=F.createContext(!1),wi=()=>F.useContext(Ci);Ci.Provider;function bre(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var xre=F.createContext(bre()),Ti=()=>F.useContext(xre),Ei=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ni(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Di=e=>{F.useEffect(()=>{e.clearReset()},[e])},Oi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ni(n,[e.error,r])),ki=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))}},Sre=(e,t)=>e.isLoading&&e.isFetching&&!t,Ai=(e,t)=>e?.suspense&&t.isPending,ji=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Mi(e,t,n){let r=wi(),i=Ti(),a=Si(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,ki(o),Ei(o,i,s),Di(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(ai.batchCalls(e)):Br;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),F.useEffect(()=>{u.setOptions(o)},[o,u]),Ai(o,d))throw ji(o,u,i);if(Oi({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&&!ri.isServer()&&Sre(d,r)&&(l?ji(o,u,i):s?.promise)?.catch(Br).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Ni(e,t){return Mi(e,gi,t)}function Cre(e){return e}var wre={[Symbol.iterator](){return Tre}},Tre={next(){return{done:!0,value:void 0}}},Ere=()=>wre,Dre=C,Pi=globalThis.Number,Ore=e=>{if(e===`NaN`)return ve(NaN);if(e===`Infinity`)return ve(1/0);if(e===`-Infinity`)return ve(-1/0);if(e.trim()===``)return ut();let t=Pi(e);return Pi.isNaN(t)?ut():ve(t)},kre=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Fi=`~effect/http/HttpClientRequest`,Are={[Fi]:Fi,...We,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Qee(this.headers),body:this.body.toJSON()}},pipe(){return Ae(this,arguments)}};function Ii(e,t,n,r,i,a){let o=Object.create(Are);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var jre=Ii(`GET`,``,hne,ut(),pn,Mte),Li=e=>(t,n)=>Nre(jre,{method:e,url:t,...n??void 0}),Mre=Li(`POST`),Nre=_e(2,(e,t)=>{let n=e;return t.method&&(n=Pre(n,t.method)),t.url&&(n=Lre(n,t.url)),t.headers&&(n=Ri(n,t.headers)),t.urlParams&&(n=Rre(n,t.urlParams)),t.hash&&(n=zre(n,t.hash)),t.body&&(n=Bi(n,t.body)),t.accept&&(n=zi(n,t.accept)),t.acceptJson&&(n=Ire(n)),n}),Pre=_e(2,(e,t)=>Ii(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Fre=_e(3,(e,t,n)=>Ii(e.method,e.url,e.urlParams,e.hash,xn(e.headers,t,n),e.body)),Ri=_e(2,(e,t)=>Ii(e.method,e.url,e.urlParams,e.hash,Xte(e.headers,t),e.body)),zi=_e(2,(e,t)=>Fre(e,`Accept`,t)),Ire=zi(`application/json`),Lre=_e(2,(e,t)=>{if(typeof t==`string`)return Ii(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Fte(n.searchParams),i=fte(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Ii(e.method,n.toString(),r,i,e.headers,e.body)}),Rre=_e(2,(e,t)=>Ii(e.method,e.url,Zte(e.urlParams,t),e.hash,e.headers,e.body)),zre=_e(2,(e,t)=>Ii(e.method,e.url,e.urlParams,ve(t),e.headers,e.body)),Bi=_e(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=un(un(n,`Content-Type`),`Content-length`):(t.contentType&&(n=xn(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=xn(n,`content-length`,t.contentLength.toString()))),Ii(e.method,e.url,e.urlParams,e.hash,n,t)}),Bre=e=>sr({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${o(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),Vi=`~effect/http/HttpClient`,Hi=Ot(`effect/HttpClient`),Ui=_e(2,(e,t)=>Wi(n=>t(e.postprocess(n)),e.preprocess)),Vre=Ui(bt(Rte)),Wi=(e,t)=>{let n=Object.create(Hre);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Hre={[Vi]:Vi,pipe(){return Ae(this,arguments)},...We,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(kre.map(([e,t])=>[t,function(t,n){return this.execute(Li(e)(t,n))}]))},Ure=e=>Wi(t=>bt(t,t=>Nt(n=>{let i=qre.get(t),a=i??new AbortController,o=Qte(t.url,t.urlParams,g(t.hash));if(rte(o))return r(new En({reason:new Tte({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Wee)||n.getRef(Gi)(t)){let r=e(t,s,a.signal,n);return i?r:Ct(e=>Ie(e(r),{onSuccess(e){return qi.register(e,a),et(new Ji(e,a))},onFailure(e){return _t(e)&&a.abort(),tt(e)}}))}return at(n.getRef(Gre)(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(Pte),l=Cn(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(Ki)?Ri(t,Bre(r)):t,Ct(o=>o(e(t,s,a.signal,n)).pipe(Lt(r,{captureStackTrace:!1}),Ie({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=Cn(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?et(e):(qi.register(e,a),et(new Ji(e,a)))},onFailure(e){return!i&&_t(e)&&a.abort(),tt(e)}})))})})),et),Wre=_e(2,(e,t)=>{let n=lee(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,a=i&&S(i),o=n?void 0:t.times;return Ui(e,Se(r===`errors-only`?Te:re({schedule:a,times:o,while:Xi}),r===`response-only`?Te:he({while:n||t.while===void 0?Yi:v(Yi,t.while),schedule:i,times:o})))}),Gi=xt(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>tee}),Ki=xt(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:Hee}),Gre=xt(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),Kre=e=>dt(Hi)(ie(t=>Ze(e,e=>Ui(e,gt(e=>ht(t,e)))))),qi=(()=>{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,Ji=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[hn]=hn;[cn]=cn;applyInterrupt(e){return Dt(()=>(qi.unregister(this.original),pt(e,()=>ct(()=>{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 xee(()=>(qi.unregister(this.original),Zee(this.original.stream,ct(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[qe](){return this.original[qe]()}pipe(){return Ae(this,arguments)}},Yi=e=>Aee(e)||Jre(e),Jre=e=>Qn(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Xi(e.reason.response)),Xi=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Zi=`~effect/FiberSet`,Yre=e=>mt(e,Zi),Xre={[Zi]:Zi,[Symbol.iterator](){return this.state._tag===`Closed`?Ere():this.state.backing[Symbol.iterator]()},...le,toJSON(){return{_id:`FiberMap`,state:this.state}}},Zre=(e,t)=>{let n=Object.create(Xre);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},Qre=()=>ke(ct(()=>Zre(new Set,Ge())),e=>Dt(()=>{let t=e.state;if(t._tag===`Closed`)return rt;e.state={_tag:`Closed`};let n=t.backing;return T(n).pipe(oe(e.deferred))})),Qi=-1,$re=me(D(Fee,j(Qi))),eie=_e(e=>Yre(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(Qi);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),yt(r)&&(n?.propagateInterruption===!0?!$re(r.cause):!ot(r.cause))&&Et(e.deferred,r))}))}),tie=function(){let e;return()=>(e===void 0&&(e=m(vt)),e)}(),nie=e=>()=>Ze(Tt(),t=>{let n=He(t);return(t,r)=>{if(e.state._tag===`Closed`)return tie();let i=n(t,r);return eie(e,i),i}}),$i=e=>ue(e.deferred),ea=`~effect/socket/Socket`,ta=Ot(`effect/socket/Socket`),rie=`~effect/socket/Socket/CloseEvent`,iie=e=>mt(e,rie),na=`~effect/socket/Socket/SocketError`,aie=e=>mt(e,na),ra=class extends On(`effect/socket/Socket/SocketReadError`)({_tag:mn(`SocketReadError`),cause:Rn}){message=`An error occurred during Read`},oie=class extends On(`effect/socket/Socket/SocketWriteError`)({_tag:mn(`SocketWriteError`),cause:Rn}){message=`An error occurred during Write`},ia=class extends On(`effect/socket/Socket/SocketOpenError`)({_tag:mn(`SocketOpenError`),kind:jn([`Unknown`,`Timeout`]),cause:Rn}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},aa=class extends On(`effect/socket/Socket/SocketCloseError`)({_tag:mn(`SocketCloseError`),code:Mn,closeReason:$t(Gn)}){static filterClean(e){return function(t){return sa.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?Eee(t.reason):Iee(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},oa=Dn([ra,oie,ia,aa]),sa=class extends ine(na)(`SocketError`,{_tag:mn(`SocketError`),reason:oa}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[na]=na;static is(e){return aie(e)}message=this.reason.message},sie=e=>!0,cie=class extends Ot()(`~effect/socket/Socket/WebSocket`){},ca=class extends Ot()(`@effect/platform/Socket/WebSocketConstructor`){},lie=(e,t)=>ca.use(n=>uie(ke((typeof e==`string`?et(e):e).pipe(Ze(e=>n(e,t?.protocols))),e=>ct(()=>e.close(1e3))),t)),uie=(e,t)=>Nt(n=>{let i,a=lt(!1),o=n.context,s=t?.closeCodeIsError??sie,c=(n,c)=>bee(Xe(function*(o){let l=yield*Qre().pipe(ee(o)),u=yield*ee(e,o),d=yield*De(nie(l)(),cie,u),f=!1;function p(e){if(e.data instanceof Blob){let t=bt(ft(()=>e.data.arrayBuffer()),e=>{let t=n(new Uint8Array(e));return it(t)?t:rt});return d(t)}let t=n(e.data);it(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),Et(l.deferred,r(new sa({reason:f?new ra({cause:e}):new ia({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),Et(l.deferred,r(new sa({reason:new aa({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=Ge();u.addEventListener(`open`,()=>{f=!0,Et(e,rt)},{once:!0}),yield*ue(e).pipe(jt({duration:t?.openTimeout??1e4,orElse:()=>r(new sa({reason:new ia({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),O($i(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*ce($i(l),aa.filterClean(e=>!s(e)),()=>rt)})).pipe(gt(e=>ht(o,e)),Ke(ct(()=>{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=et(e=>a.whenOpen(ct(()=>{let t=i;iie(e)?t.close(e.code,e.reason):t.send(e)})));return et(ta.of({[ea]:ea,run:u,runRaw:c,writer:d}))}),la=Se(lie,dt(ta)),ua=class extends Ot()(`effect/workers/Transferable/Collector`){},die=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ua.of({addAllUnsafe:t,addAll:e=>ct(()=>t(e)),readUnsafe:n,read:ct(n),clearUnsafe:r,clear:ct(r)})},fie=`~effect/workers/WorkerError`,pie=class extends On(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:mn(`WorkerSpawnError`),message:Gn,cause:$t(Rn)}){},mie=class extends On(`effect/workers/WorkerError/WorkerSendError`)({_tag:mn(`WorkerSendError`),message:Gn,cause:$t(Rn)}){},hie=class extends On(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:mn(`WorkerReceiveError`),message:Gn,cause:$t(Rn)}){},gie=class extends On(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:mn(`WorkerUnknownError`),message:Gn,cause:$t(Rn)}){},da=Dn([pie,mie,hie,gie]);On(fie)({_tag:mn(`WorkerError`),reason:da});var fa=`~effect/rpc/RpcClientError`,pa=class extends On(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:mn(`RpcClientDefect`),message:Gn,cause:Rn}){},ma=class extends On(fa)({_tag:mn(`RpcClientError`),reason:Dn([da,oa,Wte,pa])}){[fa]=fa;get message(){return`${this.reason._tag}: ${this.reason.message}`}},ha=e=>typeof e==`bigint`?e:BigInt(e),_ie={_tag:`Ping`},ga;try{ga=new TextDecoder}catch{}var I,_a,L=0,va=[],ya=va,ba=0,xa={},Sa,Ca,wa=0,Ta=0,Ea,Da,Oa=[],ka,Aa={useRecords:!1,mapsAsObjects:!0},ja=class{},Ma=new ja;Ma.name=`MessagePack 0xC1`;var Na=!1,Pa=2,Fa,Ia,La;try{Function(``)}catch{Pa=1/0}var Ra=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 so(()=>(co(),this?this.unpack(t,n):e.prototype.unpack.call(Aa,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(_a=n.end||t.length,L=n.start||0):(L=0,_a=n>-1?n:t.length),ba=0,Ta=0,Ca=null,ya=va,Ea=null,I=t;try{ka=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(xa=this,this.structures)return Sa=this.structures,za(n);(!Sa||Sa.length>0)&&(Sa=[])}else xa=Aa,(!Sa||Sa.length>0)&&(Sa=[]);return za(n)}unpackMultiple(e,t){let n,r=0;try{Na=!0;let i=e.length,a=this?this.unpack(e,i):uo.unpack(e,i);if(t){if(t(a,r,L)===!1)return;for(;L<i;)if(r=L,t(za(),r,L)===!1)return}else{for(n=[a];L<i;)r=L,n.push(za());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Na=!1,co()}}_mergeStructures(e,t){Ia&&(e=Ia.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 za(e){try{if(!xa.trusted&&!Na){let e=Sa.sharedLength||0;e<Sa.length&&(Sa.length=e)}let t;if(xa.randomAccessStructure&&I[L]<64&&I[L]>=32&&Fa?(t=Fa(I,L,_a,xa),I=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),L=_a):t=Va(),Ea&&=(L=Ea.postBundlePosition,null),Na&&(Sa.restoreStructures=null),L==_a)Sa&&Sa.restoreStructures&&Ba(),Sa=null,I=null,Da&&=null;else if(L>_a)throw Error(`Unexpected end of MessagePack data`);else if(!Na){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 Sa&&Sa.restoreStructures&&Ba(),co(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||L>_a)&&(e.incomplete=!0),e}}function Ba(){for(let e in Sa.restoreStructures)Sa[e]=Sa.restoreStructures[e];Sa.restoreStructures=null}function Va(){let e=I[L++];if(e<160)if(e<128){if(e<64)return e;{let t=Sa[e&63]||xa.getStructures&&Wa()[e&63];return t?(t.read||=Ha(t,e&63),t.read()):e}}else if(e<144){if(e-=128,xa.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=no();e===`__proto__`&&(e=`__proto_`),t[e]=Va()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Va(),Va());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=Va();return xa.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(Ta>=L)return Ca.slice(L-wa,(L+=t)-wa);if(Ta==0&&_a<140){let e=t<16?Za(t):Xa(t);if(e!=null)return e}return Ga(t)}{let t;switch(e){case 192:return null;case 193:return Ea?(t=Va(),t>0?Ea[1].slice(Ea.position1,Ea.position1+=t):Ea[0].slice(Ea.position0,Ea.position0-=t)):Ma;case 194:return!1;case 195:return!0;case 196:if(t=I[L++],t===void 0)throw Error(`Unexpected end of buffer`);return $a(t);case 197:return t=ka.getUint16(L),L+=2,$a(t);case 198:return t=ka.getUint32(L),L+=4,$a(t);case 199:return eo(I[L++]);case 200:return t=ka.getUint16(L),L+=2,eo(t);case 201:return t=ka.getUint32(L),L+=4,eo(t);case 202:if(t=ka.getFloat32(L),xa.useFloat32>2){let e=lo[(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=ka.getFloat64(L),L+=8,t;case 204:return I[L++];case 205:return t=ka.getUint16(L),L+=2,t;case 206:return t=ka.getUint32(L),L+=4,t;case 207:return xa.int64AsType===`number`?(t=ka.getUint32(L)*4294967296,t+=ka.getUint32(L+4)):xa.int64AsType===`string`?t=ka.getBigUint64(L).toString():xa.int64AsType===`auto`?(t=ka.getBigUint64(L),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=ka.getBigUint64(L),L+=8,t;case 208:return ka.getInt8(L++);case 209:return t=ka.getInt16(L),L+=2,t;case 210:return t=ka.getInt32(L),L+=4,t;case 211:return xa.int64AsType===`number`?(t=ka.getInt32(L)*4294967296,t+=ka.getUint32(L+4)):xa.int64AsType===`string`?t=ka.getBigInt64(L).toString():xa.int64AsType===`auto`?(t=ka.getBigInt64(L),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=ka.getBigInt64(L),L+=8,t;case 212:if(t=I[L++],t==114)return io(I[L++]&63);{let e=Oa[t];if(e)return e.read?(L++,e.read(Va())):e.noBuffer?(L++,e()):e(I.subarray(L,++L));throw Error(`Unknown extension `+t)}case 213:return t=I[L],t==114?(L++,io(I[L++]&63,I[L++])):eo(2);case 214:return eo(4);case 215:return eo(8);case 216:return eo(16);case 217:return t=I[L++],Ta>=L?Ca.slice(L-wa,(L+=t)-wa):yie(t);case 218:return t=ka.getUint16(L),L+=2,Ta>=L?Ca.slice(L-wa,(L+=t)-wa):bie(t);case 219:return t=ka.getUint32(L),L+=4,Ta>=L?Ca.slice(L-wa,(L+=t)-wa):xie(t);case 220:return t=ka.getUint16(L),L+=2,qa(t);case 221:return t=ka.getUint32(L),L+=4,qa(t);case 222:return t=ka.getUint16(L),L+=2,Ja(t);case 223:return t=ka.getUint32(L),L+=4,Ja(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 vie=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ha(e,t){function n(){if(n.count++>Pa){let n=e.read=Function(`r`,`return function(){return `+(xa.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:vie.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(Va);return e.highByte===0&&(e.read=Ua(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]=Va()}return xa.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Ua(t,n):n}var Ua=(e,t)=>function(){let n=I[L++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=Sa[r]||Wa()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=Ha(i,e),i.read()};function Wa(){let e=so(()=>(I=null,xa.getStructures()));return Sa=xa._mergeStructures(e,Sa)}var Ga=Ka,yie=Ka,bie=Ka,xie=Ka;function Ka(e){let t;if(e<16&&(t=Za(e)))return t;if(e>64&&ga)return ga.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+=Ya.apply(String,r),r.length=0)}return r.length>0&&(t+=Ya.apply(String,r)),t}function qa(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Va();return xa.freezeData?Object.freeze(t):t}function Ja(e){if(xa.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=no();e===`__proto__`&&(e=`__proto_`),t[e]=Va()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(Va(),Va());return t}}var Ya=String.fromCharCode;function Xa(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 Ya.apply(String,n)}function Za(e){if(e<4)if(e<2){if(e===0)return``;{let e=I[L++];if((e&128)>1){--L;return}return Ya(e)}}else{let t=I[L++],n=I[L++];if((t&128)>0||(n&128)>0){L-=2;return}if(e<3)return Ya(t,n);let r=I[L++];if((r&128)>0){L-=3;return}return Ya(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 Ya(t,n,r,i);{let e=I[L++];if((e&128)>0){L-=5;return}return Ya(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 Ya(t,n,r,i,a,o);let s=I[L++];if((s&128)>0){L-=7;return}return Ya(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 Ya(t,n,r,i,a,o,s,c);{let e=I[L++];if((e&128)>0){L-=9;return}return Ya(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 Ya(t,n,r,i,a,o,s,c,l,u);let d=I[L++];if((d&128)>0){L-=11;return}return Ya(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 Ya(t,n,r,i,a,o,s,c,l,u,d,f);{let e=I[L++];if((e&128)>0){L-=13;return}return Ya(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 Ya(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 Ya(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function Qa(){let e=I[L++],t;if(e<192)t=e-160;else switch(e){case 217:t=I[L++];break;case 218:t=ka.getUint16(L),L+=2;break;case 219:t=ka.getUint32(L),L+=4;break;default:throw Error(`Expected string`)}return Ka(t)}function $a(e){return xa.copyBuffers?Uint8Array.prototype.slice.call(I,L,L+=e):I.subarray(L,L+=e)}function eo(e){let t=I[L++];if(Oa[t]){let n;return Oa[t](I.subarray(L,n=L+=e),e=>{L=e;try{return Va()}finally{L=n}})}throw Error(`Unknown extension type `+t)}var to=Array(4096);function no(){let e=I[L++];if(e>=160&&e<192){if(e-=160,Ta>=L)return Ca.slice(L-wa,(L+=e)-wa);if(!(Ta==0&&_a<180))return Ga(e)}else return L--,ro(Va());let t=(e<<5^(e>1?ka.getUint16(L):e>0?I[L]:0))&4095,n=to[t],r=L,i=L+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=ka.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=[],to[t]=n,n.bytes=e;r<i;)a=ka.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=I[r++],n.push(a);let s=e<16?Za(e):Xa(e);return s==null?n.string=Ga(e):n.string=s}function ro(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(xa.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 io=(e,t)=>{let n=Va().map(ro),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=Sa[e];return i&&(i.isShared||Na)&&((Sa.restoreStructures||(Sa.restoreStructures=[]))[e]=i),Sa[e]=n,n.read=Ha(n,r),n.read()};Oa[0]=()=>{},Oa[0].noBuffer=!0,Oa[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 ao={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Oa[101]=()=>{let e=Va();if(!ao[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return ao[e[0]](e[1],{cause:e[2]})},Oa[105]=e=>{if(xa.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=ka.getUint32(L-4);Da||=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};Da.set(t,i);let a=Va();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},Oa[112]=e=>{if(xa.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=ka.getUint32(L-4),n=Da.get(t);return n.used=!0,n.target},Oa[115]=()=>new Set(Va());var oo=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),Sie=typeof globalThis==`object`?globalThis:window;Oa[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=oo[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 Sie[r](n)},Oa[120]=()=>{let e=Va();return new RegExp(e[0],e[1])};var Cie=[];Oa[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=L;return L+=t-e.length,Ea=Cie,Ea=[Qa(),Qa()],Ea.position0=0,Ea.position1=0,Ea.postBundlePosition=L,L=n,Va()},Oa[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 so(e){La&&La();let t=_a,n=L,r=ba,i=wa,a=Ta,o=Ca,s=ya,c=Da,l=Ea,u=new Uint8Array(I.slice(0,_a)),d=Sa,f=Sa.slice(0,Sa.length),p=xa,m=Na,h=e();return _a=t,L=n,ba=r,wa=i,Ta=a,Ca=o,ya=s,Da=c,Ea=l,I=u,Na=m,Sa=d,Sa.splice(0,Sa.length,...f),xa=p,ka=new DataView(I.buffer,I.byteOffset,I.byteLength),h}function co(){I=null,Da=null,Sa=null}var lo=Array(147);for(let e=0;e<256;e++)lo[e]=+(`1e`+Math.floor(45.15-e*.30103));var uo=new Ra({useRecords:!1});uo.unpack,uo.unpackMultiple,uo.unpack;var wie={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var fo;try{fo=new TextEncoder}catch{}var po,mo,ho=typeof Buffer<`u`,go=ho?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,_o=ho?Buffer:Uint8Array,vo=ho?4294967296:2144337920,R,yo,bo,z=0,xo,So=null,Tie,Eie=21760,Die=/[\u0080-\uFFFF]/,Co=Symbol(`record-id`),Oie=class extends Ra{constructor(e){super(e),this.offset=0;let t,n,r,i,a=_o.prototype.utf8Write?function(e,t){return R.utf8Write(e,t,R.byteLength-t)}:fo&&fo.encodeInto?function(e,t){return fo.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 go(8192),bo=R.dataView||(R.dataView=new DataView(R.buffer,0,8192)),z=0),xo=R.length-10,xo-z<2048?(R=new go(R.length),bo=R.dataView||(R.dataView=new DataView(R.buffer,0,R.length)),xo=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`?(So=[],So.size=1/0):So=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[Co]=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)&&!mo.some(t=>e instanceof t)?D(e.toJSON?e.toJSON():e):y(e):y(e);let n=So;if(So&&Do(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&&(bo.setUint32(n.position+t,bo.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&bo.setUint32(n.position+t,bo.getUint32(n.position+t)+a),z+=e.length*6,z>xo&&w(z),o.offset=z;let s=kie(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=Aie(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][Co]=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,bo.setUint32(z,t),z+=4);for(let n=0;n<t;n++)y(e[n])},y=e=>{z>xo&&(R=w(z));var n=typeof e,r;if(n===`string`){let n=e.length;if(So&&n>=4&&n<4096){if((So.size+=n)>Eie){let e,n=(So[0]?So[0].length*3+So[1].length:0)+10;z+n>xo&&(R=w(z+n));let r;So.position?(r=So,R[z]=200,z+=3,R[z++]=98,e=z-t,z+=4,Do(t,y,0),bo.setUint16(e+t-3,z-t-e)):(R[z++]=214,R[z++]=98,e=z-t,z+=4),So=[``,``],So.previous=r,So.size=0,So.position=e}let r=Die.test(e);So[+!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>xo&&(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,bo.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,bo.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,bo.setInt16(z,e),z+=2):(R[z++]=210,bo.setInt32(z,e),z+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){R[z++]=202,bo.setFloat32(z,e);let n;if(t<4||(n=e*lo[(R[z]&127)<<1|R[z+1]>>7])>>0===n){z+=4;return}z--}R[z++]=203,bo.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,bo.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,bo.setUint32(z,r),z+=4);for(let[t,n]of e)y(t),y(n)}else{for(let t=0,n=po.length;t<n;t++){let n=mo[t];if(e instanceof n){let n=po[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=bo,a=z;R=null;let o;try{o=n.pack.call(this,e,e=>(R=r,r=null,z+=e,z>xo&&w(z),{target:R,targetView:bo,position:z-e}),y)}finally{r&&(R=r,bo=i,z=a,xo=R.length-10)}o&&(o.length+z>xo&&w(o.length+z),z=Eo(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,bo.setBigInt64(z,e);else if(e<0x10000000000000000&&e>0)R[z++]=207,bo.setBigUint64(z,e);else if(this.largeBigIntToFloat)R[z++]=203,bo.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),ho)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>xo&&w(n.length+z),z=Eo(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,bo.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[Co];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[Co];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>vo)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(vo,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 go(n);return bo=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,xo=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[Co]=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()[Co]=0),m.push(e),y(t))},E=(e,n,r,i)=>{let a=R,o=z,s=xo,c=t;R=yo,z=0,t=0,R||(yo=R=new go(8192)),xo=R.length-10,T(e,n,i),yo=R;let l=z;if(R=a,z=o,xo=s,t=c,l>1){let e=z+l-1;e>xo&&w(e);let n=r+t;R.copyWithin(n+l,n+1,z),R.set(yo.slice(0,l),n),z=e}else R[r+t]=yo[0]},D=e=>{let i=Tie(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:bo,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)),bo=R.dataView,z=0}set position(e){z=e}get position(){return z}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};mo=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ja],po=[{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?wo(e,16,t):To(ho?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==_o&&this.moreTypes?wo(e,oo.indexOf(n.name),t):To(e,t)}},{pack(e,t){this.moreTypes?wo(e,17,t):To(ho?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function wo(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 To(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 Eo(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 kie(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 Do(e,t,n){if(So.length>0){bo.setUint32(So.position+e,z+n-So.position-e),So.stringsPosition=z-e;let r=So;So=null,t(r[0]),t(r[1])}}function Aie(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var Oo=new Oie({useRecords:!1});Oo.pack,Oo.pack;var{NEVER:jie,ALWAYS:Mie,DECIMAL_ROUND:Nie,DECIMAL_FIT:Pie}=wie,ko=class extends Ot()(`effect/rpc/RpcSerialization`){},Fie=ko.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)}}}),Ao=pe(ko)(Fie),Iie=e=>Dt(()=>{let t=new Set,n=new Map,r=new Map,i=(e,t)=>ie(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),rt});return Ze(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return nt(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*Ce(Dt(()=>i(e)),t)}return yield*ree(w,()=>(t.delete(e),r.delete(e),rt))})}}))}),Lie=BigInt(0),Rie=Xe(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Lie++),o=yield*Tt(),s=At(o,je),c=new Map,l=!1;yield*zt(s,Nt(e=>(l=!0,u(Lee(e.id)))));let u=Xe(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?Pt(n.queue):Pe(n.queue,e.cause):n.resume(e)}),d=e=>{let r=cne(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?vn(s.headers):pn,l=s?.context??Gee();if(!r){let r=t=>p(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):at(`${n}.${e._tag}`,{attributes:t.spanAttributes},r)}let u=m(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:lte(Ze(u,tte))}},p=(e,n,r,i,o,s,u)=>Nt(d=>{if(l)return vt;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(No),o)});if(u)return p;let m;return pt(Le(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?Lt(r,{captureStackTrace:!1}):Te,He(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),Rt(iee(m),_(f,Array.from(e),s))))}),m=Xe(function*(e,r,o,s,u,d){if(l)return yield*vt;let p=i?void 0:yield*pte(`${n}.${e._tag}`,{attributes:t.spanAttributes}),m=xe(),g=a(),v=Nee(m.context,je);yield*f(v,e=>c.has(g)?(c.delete(g),_(g,yt(e)?Array.from(wee(e.cause)):[],d)):rt);let y=yield*h(u);return c.set(g,{_tag:`Queue`,rpc:e,queue:y,scope:v,context:d}),yield*r(e=>t.onFromClient({message:e,context:d,discard:!1}),{_tag:`Request`,id:g,tag:e._tag,payload:o,...p?{traceId:p.traceId,spanId:p.spanId,sampled:p.sampled}:{},headers:en(m.getRef(No),s)}).pipe(p?Lt(p,{captureStackTrace:!1}):Te,Ue(e=>Pe(y,e)),st,Mt(v,{startImmediately:!0})),y}),g=e=>{let t=[];for(let n of e.middlewares.values()){let e=o.mapUnsafe.get(`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},_=(e,n,r)=>Le(i=>{let a=xe();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Mee(1e3),He(a.context)).addObserver(()=>{i(rt)})}),v=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?rt:we(i.queue,e.values).pipe(r?bt(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):Te,Ue(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),rt):e.exit._tag===`Success`?Pt(n.queue):Pe(n.queue,e.exit.cause)):rt}case`Defect`:return u(_ee(e.defect));case`ClientEnd`:return rt}},y;if(t.flatten){let t=new Map;y=function(n,r,i){let a=t.get(n);return a||(a=d(e.requests.get(n)),t.set(n,a)),a(r,i)}}else y={},e.requests.forEach(e=>{y[e._tag]=d(e)});return{client:y,write:v}}),zie=0,jo=Xe(function*(e,t){let n=zie++,{run:r,send:i,supportsAck:a,supportsTransferables:o}=yield*Po,s=new Map,{client:c,write:u}=yield*Rie(e,{...t,supportsAck:a,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),a=o?die():void 0,c=xe(),u={rpc:r,context:a?jee(c.context,ua,a):c.context,schemas:Bie(r)};return s.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(Ce(u.context),l,bt(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)}):rt;case`Interrupt`:return s.get(t.requestId)?(s.delete(t.requestId),i(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):rt;case`Eof`:return rt}}});return yield*r(n,e=>{switch(e._tag){case`Chunk`:{let t=ha(e.requestId),n=s.get(t);return!n||ote(n.schemas.decodeChunk)?rt:n.schemas.decodeChunk.value(e.values).pipe(Ce(n.context),l,bt(t=>u({_tag:`Chunk`,clientId:0,requestId:ha(e.requestId),values:t})),b(t=>u({_tag:`Exit`,clientId:0,requestId:ha(e.requestId),exit:Oe(t)})))}case`Exit`:{let t=ha(e.requestId),n=s.get(t);return n?(s.delete(t),n.schemas.decodeExit(e.exit).pipe(Ce(n.context),l,Ie({onSuccess:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>u({_tag:`Exit`,clientId:0,requestId:t,exit:Oe(e)})}))):rt}case`Defect`:return u({_tag:`Defect`,clientId:0,defect:Wie(e.defect)});case`ClientProtocolError`:{let t=Je(e.error);return kt(s.keys(),e=>u({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return rt}}).pipe(Ue(ate),st,$e),c}),Mo=new WeakMap,Bie=e=>{let t=Mo.get(e);if(t!==void 0)return t;let n=Ete(e.successSchema);return t={decodeChunk:Uee(n,e=>yn(gn(dne(e.success)))),encodePayload:qte(gn(e.payloadSchema)),decodeExit:yn(gn(lne(e)))},Mo.set(e,t),t},No=xt(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>pn}),Po=class extends Ot()(`effect/rpc/RpcClient/Protocol`){static make=Iie},Fo=e=>Po.make(Xe(function*(t,n){let i=yield*ta,a=yield*ko,o=yield*aee(Uie),s=new Map,c=yield*i.writer,d=a.makeUnsafe(),f=yield*Hie(c(d.encode(_ie))),p,m=Dt(()=>(p=void 0,x(o)?o.value.onConnect:rt)),h=e=>kt(n,n=>t(n,e));return yield*Dt(()=>(d=a.makeUnsafe(),f.reset(),i.runRaw(e=>{try{let n=d.decode(e);if(n.length===0)return;let r=0;return Cee({while:()=>r<n.length,body:()=>{let e=n[r++];if(e._tag===`Pong`)return f.onPong(),rt;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:Bee})}catch(e){return h({_tag:`ClientProtocolError`,error:new ma({reason:new pa({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(O(bt(f.timeout,()=>r(new sa({reason:new ia({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(bt(()=>r(new sa({reason:new aa({code:1e3})}))),x(o)?Ke(o.value.onDisconnect):Te,Yee(t=>{let n=Ree(t),r=Jee(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?rt:(p=new ma({reason:r?n.success.reason:new pa({message:`Unknown socket error`,cause:Fe(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),he(e?.retryPolicy??Vie),u({module:`RpcClient`,method:`makeProtocolSocket`}),$e),{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?rt:l(c(n))},supportsAck:!0,supportsTransferables:!1}})),Vie=_(500,1.5).pipe(see(nee(5e3))),Hie=Xe(function*(e){let t=!0,n=0,r=lt();return yield*Dt(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(vee(`5 seconds`),wt,Qe,st,$e),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Uie=class extends Ot()(`effect/rpc/RpcClient/ConnectionHooks`){},Wie=kn(Rn);function Io(e){return{id:e.id??`ws:${e.label}`,label:e.label,source:e.source??`manual`,target:e.target}}function Gie(e){return e?.target.wsBaseUrl??null}function Kie(e){return e?.target.httpBaseUrl??null}function qie(e,t){return{...e,environmentId:t.environmentId,label:t.label}}function Jie(e){return e.cloudMode?`cmmd-cloud-runtime`:`local-web`}function Yie(e){let t=Jie(e);return{topology:t,controlPlane:t!==`cmmd-cloud-runtime`,executionPlane:!0,workspaceProxy:!1}}function Xie(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 Zie(e){let t=e.executionPlane;return{agents:t,browser:t,github:t,terminal:t,providerEgress:e.topology===`cmmd-control-plane`}}function Qie(e,t){return{localProjects:t.executionPlane,cloudProjects:e.cloudMode}}function Lo(e){let t=e.capabilities,n=t.runtime??Yie(t);return{repositoryIdentity:t.repositoryIdentity,pullRequests:t.pullRequests??!1,cloudMode:t.cloudMode,posthogPublicKey:t.posthogPublicKey,posthogHost:t.posthogHost,runtime:n,auth:t.auth??Xie(n),tools:t.tools??Zie(n),projects:t.projects??Qie(t,n)}}function $ie(e){return e?Lo(e).projects.cloudProjects:!1}function eae(e){return e?Lo(e).runtime.workspaceProxy??!1:!1}function Ro(e,t){return{environmentId:e,projectId:t}}function zo(e,t){return{environmentId:e,threadId:t}}var Bo=`scoped:v1:`;function Vo(e){let t=`projectId`in e?e.projectId:e.threadId;return t.includes(`:`)||e.environmentId.startsWith(Bo)?`${Bo}${encodeURIComponent(e.environmentId)}:${encodeURIComponent(t)}`:`${e.environmentId}:${t}`}function Ho(e){return Vo(e)}function Uo(e){return Vo(e)}function tae(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 Wo(e){if(e.startsWith(Bo))return tae(e);let t=e.lastIndexOf(`:`);return t<=0||t>=e.length-1?null:{environmentId:e.slice(0,t),localId:e.slice(t+1)}}function Go(e){let t=Wo(e);return t?{environmentId:t.environmentId,projectId:t.localId}:null}function Ko(e){let t=Wo(e);return t?{environmentId:t.environmentId,threadId:t.localId}:null}var nae=1e3,rae=64e3;jo(Wn);function iae(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(nae*2**e),rae)}var qo=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function Jo(e){return Array.isArray(e)?e.map(Jo):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Jo(t)])):e}function aae(e){let t=JSON.stringify(Jo(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var oae={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function sae(e){return e._tag===`Ping`?oae:null}function cae(e){if(e.policy===null||e.policy.method!==e.method)throw new qo(`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 qo(`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 lae(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new qo(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new qo(`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 qo(`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 qo(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var uae=[{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.codeGraphSummary,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.codeGraphNeighborhood,requiredScope:`workspace.read`,deliveryClass:`read`},{method:M.codeGraphSearch,requiredScope:`workspace.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.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:ln.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:ln.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:ln.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:ln.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:ln.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:ln.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:ln.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:ln.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`}],dae=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,ln.dispatchCommand]),fae=uae.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?dae.has(e.method)?`frame`:`metadata-only`:`none`}}),pae=lae({registeredMethods:[...Wn.requests.keys()],policies:fae}),Yo={"project.create":{requiredScope:`project.write`,deliveryClass:`create-command`},"project.meta.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`}},mae=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function hae(e){if(e.method!==ln.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!mae.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 qo(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function Xo(e){let t=pae.get(e.method)??null,n=cae({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==ln.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new qo(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in Yo))throw new qo(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=Yo[r];if(!e.grantedScopes.includes(i.requiredScope))throw new qo(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var Zo=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},Qo=class extends Zo{},$o=class extends Zo{},es=class extends Zo{},gae=class extends Zo{},_ae=class extends Zo{},vae=class extends Zo{},yae=class extends Zo{},bae=class extends Zo{},xae=class extends Zo{},Sae=class extends Zo{},ts=class extends Zo{},ns=Cae(globalThis,{});function Cae(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 wae(){if(ns!==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-y4e5bF-h.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e.subtle}catch(e){throw new ts(e)}}var rs=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await wae())}},is={Base:0,Psk:1,Auth:2,AuthPsk:3},Tae={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},as={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},os={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},ss=new Uint8Array,cs=0n,ls=1n,us=2n,Eae=new Uint8Array([75,69,77,0,0]),ds=new Uint8Array([72,80,75,69,45,118,49]);function fs(e){return new Uint8Array(ps(e))}function ps(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 Dae=class extends rs{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:as.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:ss}),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(ds,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(ds,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):ps(e);if(n.byteLength!==this.hashSize)throw new Qo(`The salt length must be the same as the hashSize`);let r=ps(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=ps(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=ss,c=fs(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=ps(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:ps(e),info:ps(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===ss)throw Error(`Not initialized. Call init()`)}},Oae=class extends Dae{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:as.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}})}},ms=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function hs(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 gs(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function _s(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 kae(){if(ns!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:e}=await N(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-y4e5bF-h.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e}catch{throw Error(`failed to load Crypto`)}}function Aae(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 jae=new Uint8Array([101,97,101,95,112,114,107]),Mae=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Nae(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 Pae=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(Eae);r.set(hs(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(ps(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(ps(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=ps(e);if(t.byteLength>8192)throw new Qo(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():ms(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=ms(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=gs(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=gs(new Uint8Array(n),new Uint8Array(r));else{let t=ms(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Nae(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new gae(e)}}async decap(e){let t=ps(e.enc),n=await this._prim.deserializePublicKey(t),r=ms(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=ms(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)):gs(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=gs(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 _ae(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(jae,e),r=this._kdf.buildLabeledInfo(Mae,t,this.secretSize);return await this._kdf.extractAndExpand(ss,n,r,this.secretSize)}},vs=[`deriveBits`],Fae=new Uint8Array([100,107,112,95,112,114,107]),Iae=new Uint8Array([115,107]),ys=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=[])}},Lae=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 $o(e))}}async deserializePublicKey(e){try{return await this._importRawKey(ps(e),!0)}catch(e){throw new es(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new $o(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(ps(e),!1)}catch(e){throw new es(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 es(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new ys(this._algName,e,`private`,vs);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new ts(e)}}async deriveKeyPair(e){try{let t=ps(e),n=await this._hkdf.labeledExtract(ss.buffer,Fae,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,Iae,ss,this._nSk),i=new ys(this._algName,new Uint8Array(r),`private`,vs);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new Sae(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new ys(this._algName,t,`public`))}catch(e){return Promise.reject(new es(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new $o(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 ys(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:vs))})}_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 ys(this._algName,_s(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new ys(this._algName,_s(e.d),`private`,vs)))})}};function Rae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function bs(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function xs(e,t,n=``){let r=Rae(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 Ss(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 Cs(e,t){xs(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function zae(e){if(typeof e==`bigint`){if(!Ps(e))throw Error(`positive bigint expected, got `+e)}else bs(e);return e}function ws(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ts(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Bae=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Es(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ds(e,t){return e<<32-t|e>>>t}var Os=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Vae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Hae=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function Uae(e){if(xs(e),Os)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Vae[e[n]];return t}var ks={_0:48,_9:57,A:65,F:70,a:97,f:102};function As(e){if(e>=ks._0&&e<=ks._9)return e-ks._0;if(e>=ks.A&&e<=ks.F)return e-(ks.A-10);if(e>=ks.a&&e<=ks.f)return e-(ks.a-10)}function Wae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Os)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=As(e.charCodeAt(i)),a=As(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 Gae(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=cs;for(let n=0;n<e.length;n++){let r=As(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|Hae[r]}return t}function js(e){bs(e,`numberToBigint`);let t=e,n=cs,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function Ms(e){return Gae(Uae(Ns(xs(e)).reverse()))}function Kae(e,t){bs(t),e=zae(e);let n=Wae(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function qae(e,t){return Kae(e,t).reverse()}function Ns(e){return Uint8Array.from(e)}function Ps(e){return typeof e==`bigint`&&0n<=e}function Jae(e,t,n){return Ps(e)&&Ps(t)&&Ps(n)&&t<=e&&e<n}function Fs(e,t,n,r){if(!Jae(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Yae(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 Xae(e=32){let t=await kae(),n=new Uint8Array(e);return t.getRandomValues(n),n}function Zae(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function Qae(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);bs(e.outputLen),bs(e.blockLen)}function $ae(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 Is=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}),Qae(e),xs(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),Ts(r)}update(e){return Ss(this),this.iHash.update(e),this}digestInto(e){Ss(this),xs(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()}},Ls=(e,t,n)=>new Is(e,t).update(n).digest();Ls.create=(e,t)=>new Is(e,t);function eoe(e,t,n){return e&t^~e&n}function toe(e,t,n){return e&t^e&n^t&n}var noe=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=Es(this.buffer)}update(e){Ss(this),xs(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=Es(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){Ss(this),Cs(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Ts(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,js(this.length*8),i),this.process(n,0);let o=Es(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()}},Rs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),roe=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]),zs=new Uint32Array(64),ioe=class extends noe{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)zs[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=zs[e-15],n=zs[e-2],r=Ds(t,7)^Ds(t,18)^t>>>3,i=Ds(n,17)^Ds(n,19)^n>>>10;zs[e]=i+zs[e-7]+r+zs[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=Ds(o,6)^Ds(o,11)^Ds(o,25),u=l+t+eoe(o,s,c)+roe[e]+zs[e]|0,d=(Ds(n,2)^Ds(n,13)^Ds(n,22))+toe(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(){Ts(zs)}destroy(){this.set(0,0,0,0,0,0,0,0),Ts(this.buffer)}},aoe=class extends ioe{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Rs[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Rs[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Rs[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Rs[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Rs[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Rs[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Rs[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Rs[7]|0})}},Bs=$ae(()=>new aoe,Zae(1));function Vs(e,t){let n=e%t;return n>=0n?n:t+n}function Hs(e,t,n){let r=e;for(;t-->cs;)r*=r,r%=n;return r}function ooe(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function soe(e){return Yae(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function coe(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=soe(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||Xae,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?us**254n:us**447n,p=f+(o?8n*us**251n-ls:4n*us**445n-ls)+ls,m=e=>Vs(e,t),h=g(u);function g(e){return qae(m(e),l)}function _(e){let t=Ns(xs(e,l,`uCoordinate`));return o&&(t[31]&=127),m(Ms(t))}function v(e){return Ms(r(Ns(xs(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){Fs(`u`,e,cs,t),Fs(`scalar`,n,f,p);let r=n,a=e,o=ls,s=cs,l=e,u=ls,h=cs;for(let e=c-1n;e>=cs;e--){let t=r>>e&ls;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)),xs(e,T.seed,`seed`),e),D={randomSecretKey:E};return Object.freeze({keygen:ooe(E,x),getSharedSecret:S,getPublicKey:x,scalarMult:y,scalarMultBase:b,utils:D,GuBytes:h.slice(),lengths:T})}function Us(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var loe=(e,t)=>{function n(n,...r){if(xs(n,void 0,`key`),!Bae)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];xs(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&xs(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`);xs(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,xs(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(xs(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 uoe(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function doe(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 Ws(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&&!poe(t))throw Error(`invalid output, must be aligned`);return t}function foe(e,t,n){Us(n);let r=new Uint8Array(16),i=Es(r);return i.setBigUint64(0,js(t),n),i.setBigUint64(8,js(e),n),r}function poe(e){return e.byteOffset%4==0}var Gs=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),moe=Gs(`expand 16-byte k`),hoe=Gs(`expand 32-byte k`),goe=ws(moe),_oe=ws(hoe);function Ks(e,t){return e<<t|e>>>32-t}function qs(e){return e.byteOffset%4==0}var Js=64,voe=16,Ys=2**32-1,Xs=Uint32Array.of();function yoe(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Js),u=ws(l),d=qs(i)&&qs(a),f=d?ws(i):Xs,p=d?ws(a):Xs;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Ys)throw Error(`arx: counter overflow`);let h=Math.min(Js,c-m);if(d&&h===Js){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<voe;t++)n=e+t,p[n]=f[n]^u[t];m+=Js;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function boe(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=uoe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return bs(i),bs(o),Us(a),Us(n),(t,s,c,l,u=0)=>{xs(t,void 0,`key`),xs(s,void 0,`nonce`),xs(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),xs(l,void 0,`output`),bs(u),u<0||u>=Ys)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=Ns(t)),h=_oe;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=goe,f.push(m);else throw xs(t,32,`arx key`),Error(`invalid key size`);qs(s)||f.push(s=Ns(s));let g=ws(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,ws(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=ws(s);return yoe(e,h,g,v,c,l,u,o),Ts(...f),l}}function Zs(e,t){return e[t++]&255|(e[t++]&255)<<8}var xoe=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=Ns(xs(e,32,`key`));let t=Zs(e,0),n=Zs(e,2),r=Zs(e,4),i=Zs(e,6),a=Zs(e,8),o=Zs(e,10),s=Zs(e,12),c=Zs(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]=Zs(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=Zs(e,t+0),_=Zs(e,t+2),v=Zs(e,t+4),y=Zs(e,t+6),b=Zs(e,t+8),x=Zs(e,t+10),S=Zs(e,t+12),C=Zs(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),O=i[4]+((y>>>4|b<<12)&8191),ee=i[5]+(b>>>1&8191),te=i[6]+((b>>>14|x<<2)&8191),k=i[7]+((x>>>11|S<<5)&8191),A=i[8]+((S>>>8|C<<8)&8191),ne=i[9]+(C>>>5|r),j=0,re=j+w*o+5*h*T+5*m*E+5*p*D+5*f*O;j=re>>>13,re&=8191,re+=5*d*ee+5*u*te+5*l*k+5*c*A+5*s*ne,j+=re>>>13,re&=8191;let ie=j+w*s+T*o+5*h*E+5*m*D+5*p*O;j=ie>>>13,ie&=8191,ie+=5*f*ee+5*d*te+5*u*k+5*l*A+5*c*ne,j+=ie>>>13,ie&=8191;let ae=j+w*c+T*s+E*o+5*h*D+5*m*O;j=ae>>>13,ae&=8191,ae+=5*p*ee+5*f*te+5*d*k+5*u*A+5*l*ne,j+=ae>>>13,ae&=8191;let oe=j+w*l+T*c+E*s+D*o+5*h*O;j=oe>>>13,oe&=8191,oe+=5*m*ee+5*p*te+5*f*k+5*d*A+5*u*ne,j+=oe>>>13,oe&=8191;let se=j+w*u+T*l+E*c+D*s+O*o;j=se>>>13,se&=8191,se+=5*h*ee+5*m*te+5*p*k+5*f*A+5*d*ne,j+=se>>>13,se&=8191;let ce=j+w*d+T*u+E*l+D*c+O*s;j=ce>>>13,ce&=8191,ce+=ee*o+5*h*te+5*m*k+5*p*A+5*f*ne,j+=ce>>>13,ce&=8191;let le=j+w*f+T*d+E*u+D*l+O*c;j=le>>>13,le&=8191,le+=ee*s+te*o+5*h*k+5*m*A+5*p*ne,j+=le>>>13,le&=8191;let ue=j+w*p+T*f+E*d+D*u+O*l;j=ue>>>13,ue&=8191,ue+=ee*c+te*s+k*o+5*h*A+5*m*ne,j+=ue>>>13,ue&=8191;let de=j+w*m+T*p+E*f+D*d+O*u;j=de>>>13,de&=8191,de+=ee*l+te*c+k*s+A*o+5*h*ne,j+=de>>>13,de&=8191;let fe=j+w*h+T*m+E*p+D*f+O*d;j=fe>>>13,fe&=8191,fe+=ee*u+te*l+k*c+A*s+ne*o,j+=fe>>>13,fe&=8191,j=(j<<2)+j|0,j=j+re|0,re=j&8191,j>>>=13,ie+=j,i[0]=re,i[1]=ie,i[2]=ae,i[3]=oe,i[4]=se,i[5]=ce,i[6]=le,i[7]=ue,i[8]=de,i[9]=fe}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;Ts(n)}update(e){Ss(this),xs(e),e=Ns(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(){Ts(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ss(this),Cs(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 Soe(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 Coe=Soe(e=>new xoe(e));function woe(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,O=f,ee=p,te=m,k=h,A=g,ne=_,j=v,re=y,ie=b,ae=x;for(let e=0;e<a;e+=2)S=S+E|0,j=Ks(j^S,16),te=te+j|0,E=Ks(E^te,12),S=S+E|0,j=Ks(j^S,8),te=te+j|0,E=Ks(E^te,7),C=C+D|0,re=Ks(re^C,16),k=k+re|0,D=Ks(D^k,12),C=C+D|0,re=Ks(re^C,8),k=k+re|0,D=Ks(D^k,7),w=w+O|0,ie=Ks(ie^w,16),A=A+ie|0,O=Ks(O^A,12),w=w+O|0,ie=Ks(ie^w,8),A=A+ie|0,O=Ks(O^A,7),T=T+ee|0,ae=Ks(ae^T,16),ne=ne+ae|0,ee=Ks(ee^ne,12),T=T+ee|0,ae=Ks(ae^T,8),ne=ne+ae|0,ee=Ks(ee^ne,7),S=S+D|0,ae=Ks(ae^S,16),A=A+ae|0,D=Ks(D^A,12),S=S+D|0,ae=Ks(ae^S,8),A=A+ae|0,D=Ks(D^A,7),C=C+O|0,j=Ks(j^C,16),ne=ne+j|0,O=Ks(O^ne,12),C=C+O|0,j=Ks(j^C,8),ne=ne+j|0,O=Ks(O^ne,7),w=w+ee|0,re=Ks(re^w,16),te=te+re|0,ee=Ks(ee^te,12),w=w+ee|0,re=Ks(re^w,8),te=te+re|0,ee=Ks(ee^te,7),T=T+E|0,ie=Ks(ie^T,16),k=k+ie|0,E=Ks(E^k,12),T=T+E|0,ie=Ks(ie^T,8),k=k+ie|0,E=Ks(E^k,7);let oe=0;r[oe++]=o+S|0,r[oe++]=s+C|0,r[oe++]=c+w|0,r[oe++]=l+T|0,r[oe++]=u+E|0,r[oe++]=d+D|0,r[oe++]=f+O|0,r[oe++]=p+ee|0,r[oe++]=m+te|0,r[oe++]=h+k|0,r[oe++]=g+A|0,r[oe++]=_+ne|0,r[oe++]=v+j|0,r[oe++]=y+re|0,r[oe++]=b+ie|0,r[oe++]=x+ae|0}var Toe=boe(woe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Eoe=new Uint8Array(16),Qs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Eoe.subarray(n))},Doe=new Uint8Array(32);function $s(e,t,n,r,i){i!==void 0&&xs(i,void 0,`AAD`);let a=e(t,n,Doe),o=foe(r.length,i?i.length:0,!0),s=Coe.create(a);i&&Qs(s,i),Qs(s,r),s.update(o);let c=s.digest();return Ts(a,o),c}var ec=loe({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=Ws(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=$s(e,t,n,s,r);return a.set(c,o),Ts(c),a},decrypt(i,a){a=Ws(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=$s(e,t,n,o,r);if(!doe(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Ts(c),a}}))(Toe)),Ooe=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(ps(e))}async seal(e,t,n){return await this._seal(ps(e),ps(t),ps(n))}async open(e,t,n){return await this._open(ps(e),ps(t),ps(n))}_seal(e,t,n){return new Promise(r=>{r(ec(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(ec(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},koe=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:os.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 Ooe(e)}};function tc(){return new Promise((e,t)=>{t(new ts(`Not supported`))})}var Aoe=new Uint8Array([115,101,99]),nc=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 tc()}async open(e,t){return await tc()}async export(e,t){let n=ps(e);if(n.byteLength>8192)throw new Qo(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,Aoe,new Uint8Array(n),t)}catch(e){throw new vae(e)}}},joe=class extends nc{},Moe=class extends nc{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}},rc=class extends nc{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=hs(e.seq,e.baseNonce.byteLength);return Aae(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new xae(`Message limit reached`);e.seq+=1}},Noe=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)},Poe=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},ic,ac=class{constructor(){ic.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Noe(this,ic,`f`);return Poe(this,ic,t,`f`),await n,e}};ic=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)},Foe=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,Ioe=class extends rc{constructor(){super(...arguments),sc.set(this,void 0)}async open(e,t=ss.buffer){Foe(this,sc,oc(this,sc,`f`)??new ac,`f`);let n=await oc(this,sc,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),ps(e),ps(t))}catch(e){throw new bae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};sc=new WeakMap;var cc=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)},Loe=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},lc,Roe=class extends rc{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),lc.set(this,void 0),this.enc=r}async seal(e,t=ss.buffer){Loe(this,lc,cc(this,lc,`f`)??new ac,`f`);let n=await cc(this,lc,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),ps(e),ps(t))}catch(e){throw new yae(e)}finally{n()}return this.incrementSeq(this._ctx),r}};lc=new WeakMap;var zoe=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Boe=new Uint8Array([101,120,112]),Voe=new Uint8Array([105,110,102,111,95,104,97,115,104]),Hoe=new Uint8Array([107,101,121]),Uoe=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),Woe=new Uint8Array([115,101,99,114,101,116]),Goe=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Koe=class extends rs{constructor(e){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof e.kem==`number`)throw new Qo(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new Qo(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new Qo(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array(Goe),this._suiteId.set(hs(this._kem.id,2),4),this._suiteId.set(hs(this._kdf.id,2),6),this._suiteId.set(hs(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?is.Base:is.Auth:e.senderKey===void 0?is.Psk:is.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?is.Base:is.Auth:e.senderPublicKey===void 0?is.Psk:is.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=ss.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=ss.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?ss:fs(n.psk.id),i=await this._kdf.labeledExtract(ss,Uoe,r),a=n.info===void 0?ss:fs(n.info),o=await this._kdf.labeledExtract(ss,Voe,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?ss:fs(n.psk.key),l=this._kdf.buildLabeledIkm(Woe,c),u=this._kdf.buildLabeledInfo(Boe,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===os.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(Hoe,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(zoe,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 Moe(this._api,this._kdf,i.exporterSecret,n):new Roe(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 joe(this._api,this._kdf,r.exporterSecret):new Ioe(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new Qo(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new Qo(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new Qo(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new Qo(`Too long psk.id`)}}},qoe=class extends Koe{},Joe=1n,uc=2n,Yoe=3n,Xoe=5n,dc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function Zoe(e){let t=10n,n=80n,r=dc,i=e*e%r*e%r,a=Hs(Hs(i,uc,r)*i%r,Joe,r)*e%r,o=Hs(a,Xoe,r)*a%r,s=Hs(o,t,r)*o%r,c=Hs(s,20n,r)*s%r,l=Hs(c,40n,r)*c%r;return{pow_p_5_8:Hs(Hs(Hs(Hs(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,uc,r)*e%r,b2:i}}function Qoe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var $oe=(()=>{let e=dc;return coe({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=Zoe(t);return Vs(Hs(n,Yoe,e)*r,e)},adjustScalarBytes:Qoe})})(),ese=class extends Lae{constructor(e){super(`X25519`,32,$oe,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new $o(e))}}},fc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,tse=2**31,nse=65536,rse=16,pc=32,mc=(1n<<255n)-19n,hc=new TextEncoder,gc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function _c(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 ise=new Set([0n,1n,_c(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),_c(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),mc-1n]),ase=new Uint8Array,vc=class extends Oae{async extract(e,t){return ps(Ls(Bs,e.byteLength===0?new Uint8Array(this.hashSize):fs(e),fs(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=fs(e),i=fs(t),a=new Uint8Array(n),o=ase;for(let e=1,t=0;t<a.byteLength;e+=1){let n=Sc([o,i,Uint8Array.of(e)]);o=new Uint8Array(Ls(Bs,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 ps(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},yc=new qoe({kem:new class extends Pae{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(Tae.DhkemX25519HkdfSha256,new ese(e),e)}}(new vc),kdf:new vc,aead:new koe}),bc=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function xc(e){return new Uint8Array(e.slice(0))}function ose(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Sc(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 Cc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new bc(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function wc(e){if(!Number.isSafeInteger(e)||e<0)throw new bc(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function sse(e){return Sc([Cc(e.byteLength),e])}function Tc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function cse(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function Ec(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+=gc[o>>>18&63],t+=gc[o>>>12&63],n+1<e.byteLength&&(t+=gc[o>>>6&63]),n+2<e.byteLength&&(t+=gc[o&63])}return t}function Dc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new bc(`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=gc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(Ec(t)!==e)throw new bc(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function lse(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 ise.has(n%mc)}var use={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new bc(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return xc(await globalThis.crypto.subtle.digest(`SHA-256`,ose(e)))}},Oc={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new bc(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function kc(e,t){let n=hc.encode(e).byteLength;if(n===0||n>256)throw new bc(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function dse(e){let t=hc.encode(e).byteLength;if(t===0||t>65536)throw new bc(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${nse} UTF-8 bytes.`)}async function Ac(e,t=use){dse(e.exactCompactTicket),kc(e.channelId,`Channel ID`),kc(e.runtimeId,`Runtime ID`),wc(e.connectionEpoch);let n=await t.sha256(hc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new bc(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function fse(e){return Ec(e.ticketDigest)}async function pse(e=Oc){let t=new Uint8Array(await e.randomBytes(pc));if(t.byteLength!==pc)throw new bc(`endpoint_key_invalid`,`The endpoint random source must return ${pc} bytes.`);try{return Ec(t)}finally{t.fill(0)}}function jc(e){return Sc([hc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,Tc(e.direction)])}function Mc(e){return Sc([hc.encode(`forge-relay`),Cc(4),e.binding.ticketDigest,hc.encode(e.binding.channelId),Tc(e.binding.direction),cse(e.frameClass),wc(e.sequence),hc.encode(e.binding.runtimeId),wc(e.binding.connectionEpoch),Cc(e.ciphertextLength)].map(sse))}async function mse(e=Oc){let t=new Uint8Array(await e.randomBytes(pc));if(t.byteLength!==pc)throw new bc(`endpoint_key_invalid`,`The endpoint random source must return ${pc} bytes.`);try{return await yc.kem.deriveKeyPair(t)}catch(e){throw new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function Nc(e){try{return Ec(xc(await yc.kem.serializePublicKey(e)))}catch(e){throw new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function hse(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new bc(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function gse(e){try{let t=Dc(e);if(t.byteLength!==pc)throw Error(`Invalid endpoint key length.`);if(lse(t))throw new bc(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await yc.kem.deserializePublicKey(t)}catch(e){throw e instanceof bc?e:new bc(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var Pc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Fc=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=tse||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new bc(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function _se(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 bc(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var vse=class{binding;context;encapsulatedKey;queue=new Pc;budget=new Fc;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=Ec(xc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new bc(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+rse;this.budget.assertAvailable(t);let n=this.sequence,r=Mc({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=xc(await this.context.seal(e.plaintext,r))}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new bc(`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:Ec(i)}})}},yse=class{binding;context;queue=new Pc;budget=new Fc;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(_se(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new bc(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Dc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Mc({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=xc(await this.context.open(t,n))}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new bc(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function bse(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Oc).randomBytes(pc)),t.byteLength!==pc)throw Error(`The endpoint random source must return ${pc} bytes.`);let n=await yc.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:jc(e.binding),ekm:t});return new vse(e.binding,n)}catch(e){throw new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function xse(e){try{let t=await yc.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Dc(e.encapsulatedKey),info:jc(e.binding)});return new yse(e.binding,t)}catch(e){throw e instanceof bc?e:new bc(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var Sse=128,Cse=2097152,wse=864e5,Ic=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function Lc(e){return typeof e==`string`&&e.length>0}function Rc(e){return Lc(e)&&Number.isFinite(Date.parse(e))}function Tse(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function Ese(e){return Lc(e.transportRequestId)&&Lc(e.runtimeId)&&Lc(e.actorSessionId)&&Lc(e.durableRequestId)&&Lc(e.method)}function Dse(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function Ose(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!Lc(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function kse(e){return!Tse(e.status)||e.errorCode!==null&&!Lc(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&Lc(e.errorCode):e.errorCode===null}function Ase(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Ese(t)&&Dse(t)&&Ose(t)&&kse(t)&&Rc(t.createdAt)&&Rc(t.updatedAt)}function jse(e){try{return JSON.parse(e)}catch{throw new Ic(`Forge relay control journal is corrupt.`)}}function Mse(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&Lc(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(Ase)}function Nse(e){let t=new Set(e.map(zc)),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 Pse(e){let t=jse(e);if(!Mse(t))throw new Ic(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!Nse(n)||t.nextSequence<=r)throw new Ic(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function Fse(){return crypto.randomUUID()}function zc(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var Bc={pending:1,retrying:2,"outcome-unknown":3,failed:4};function Ise(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)=>Bc[t.status]>Bc[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function Vc(e){let t=e.randomUUID??Fse,n=e.now??(()=>new Date),r=e.maxRecords??Sse,i=e.maxBytes??Cse,a=e.maxReplayAgeMs??wse;if(r<1||i<1||a<1)throw new Ic(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?Pse(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 Ic(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new Ic(`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=zc(e);return{key:t,existing:c.records.find(e=>zc(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 Ic(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new Ic(`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 Ic(`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 Ic(`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(zc({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 Ic(`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(zc({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 Ic(`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(zc(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 Lse(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var Rse=tn(rne),zse=ir(tne),Bse=ir(er),Vse=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Hc(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 Uc(e,t){let n=JSON.parse(e),r=sae(n);if(r!==null)return{messageType:`request`,...r};let i=Hse(n,t);if(i!==null)return i;let a=Use(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function Hse(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=Xo({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Hc(e.headers,An.requestId)??e.id,method:e.tag,...n}}function Use(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 Wc(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 Wse=new Set([`network`,`server`,`auth`,`permission`,`client`]),Gse=new Set([`network`,`server`]);function Kse(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`&&Wse.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function Jse(e){if(e.retryable===!0||typeof e.kind==`string`&&Gse.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Gc(e){let t=Kse(e);return{code:qse(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:Jse(t)}}function Kc(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 Yse(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values(An).includes(e[0])}function qc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Xse(e){if(!Array.isArray(e))return null;for(let t of e){let e=qc(t);if(e?._tag!==`Fail`)continue;let n=qc(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function Zse(e){let t=qc(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:Xse(t.cause)??`RELAY_RPC_FAILED`}function Jc(e){if(typeof e!=`string`)return null;try{let t=Rse(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function Qse(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 Yc(e,t,n){if(typeof e==`string`)try{let r=qc(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=Zse(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 $se(e){let t=Hc(e,An.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function ece(e){return{issuedAt:Hc(e,An.issuedAt)??new Date().toISOString(),expiresAt:Hc(e,An.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function tce(e){if(e!==2&&e!==3&&e!==4)throw new qo(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function nce(e){let t=hae({method:e.identity.method,payload:e.payload});if(t===null)return;let n=rce(e.context);if(e.acquire===void 0)throw new qo(`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 rce(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new qo(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Xc(e.channelId),channelTicketDigest:Xc(e.channelTicketDigest),runtimeEndpointKeyId:Xc(e.runtimeEndpointKeyId),controlEndpointKeyId:Xc(e.controlEndpointKeyId)}}function Xc(e){if(typeof e==`string`&&e.length>0)return e;throw new qo(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function ice(e){return e===void 0?{}:{sequence:e}}function Zc(e){return e===void 0?{}:{actionGrant:e}}async function ace(e){let t=Uc(e.data,e.context.scopes),n=JSON.parse(e.data),r=ece(n.headers),i=$se(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await nce({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=tce(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,...ice(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...Zc(o)}:{protocolVersion:4,...c,...Zc(o)}}function Qc(e){return typeof e==`string`&&e.length>0}function oce(e){return[e.protocolVersion===4,Qc(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===fc,Qc(e.channelId),Qc(e.runtimeEndpointKeyId),Qc(e.runtimeEndpointPublicKey),Qc(e.controlEndpointKeyId),Qc(e.controlEndpointPublicKey),Qc(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function $c(e){if(!oce(e))throw new qo(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function sce(e){if(await Nc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new qo(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await gse(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Ac({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Ac({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 bse({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function el(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function cce(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 lce(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 uce(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new qo(`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 qo(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await xse({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var dce=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=Kc(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`,Kc(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=Uc(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=Gc(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`,Wc(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 ace({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 qo(`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 vce({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=>!Yse(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&&Yc(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=Gc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Wc(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 sce($c(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Vse,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Gc(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Wc(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Jc(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`,Wc(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=Qse(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=$c(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:fse(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=$c(this.route);if(t===null||n===null||!el(e,r,`handshake`))throw new qo(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await uce({channel:t,route:r,message:e})).open(e),a=zse(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!cce({confirmation:a,expectedPhase:o,route:r,context:n}))throw new qo(`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=Jc(e);if(t?.type!==`relay.encrypted-frame`)throw new qo(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!el(t,$c(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new qo(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=Bse(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!lce({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new qo(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);Yc(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 fce(e,t,n=tl,r=Vc({storage:Lse(),randomUUID:n.randomUUID}),i={},a){return new dce(e,t,n,r,i,a).asWebSocket()}var pce=jo(one);async function mce(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 tl={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:mce},nl=`forge-relay-binding=`,hce=3e4;function gce(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(nl))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 _ce(e){let t=e.crypto??tl,n=e.bindingTtlMs??hce,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=`${nl}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=gce(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?.(),fce(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}async function vce(e){let t=e.issuedAt??new Date,n=e.crypto??tl;return{[An.requestId]:e.requestId??n.randomUUID(),[An.sequence]:String(e.sequence),[An.issuedAt]:t.toISOString(),[An.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[An.payloadHash]:await n.sha256Base64Url(aae(e.payload))}}function yce(e,t){return $te(une,({rpc:t,request:n,next:r})=>nt(function*(){return Xo({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function bce(e,t=tl){return pce.pipe(be(yce(e,t)))}function xce(e){let t=e.crypto??tl,n=_ce({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),r=ft(n.acquireSocketUrl).pipe(l),i=pe(ca,n.constructSocket),a=la(r).pipe(E(i)),o=e.delayForRetry??iae,s=It(y(e.maxRetries??10),e=>et(Ve(o(e)??0)));return dt(Po,Fo({retryPolicy:s,retryTransientErrors:!0})).pipe(E(Ee(a,Ao)))}var rl=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Sce(e){let t=await mse(e),n=await Nc(t.publicKey);return{keyPair:t,publicKey:n,keyId:hse(`control`,n),channelNonce:await pse(e)}}function Cce(e){return{hpkeSuite:fc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function wce(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 rl(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:fc,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 il=`~effect/ManagedRuntime`,al=(e,t)=>{let n=t?.memoMap??eee(),r=pee(`parallel`),i=k(r,`sequential`),a={onFiberStart:fe(r)},o=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Nt(t=>(c||=m(Dee(s(e,n,i),e=>ct(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),zee(ge(c)))),u={[il]:il,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?ne(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return ne(u.disposeEffect)},disposeEffect:Dt(()=>(u.contextEffect=gee(`ManagedRuntime disposed`),u.cachedContext=void 0,Be(u.scope,St))),runFork(e,t){return u.cachedContext===void 0?m(ol(u,e),o(t)):He(u.cachedContext)(e,o(t))},runCallback(e,t){return u.cachedContext===void 0?oee(ol(u,e),o(t)):Bt(u.cachedContext)(e,o(t))},runSyncExit(e){return u.cachedContext===void 0?Xee(ol(u,e)):se(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?de(ol(u,e)):yee(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?uee(ol(u,e),o(t)):hee(u.cachedContext)(e,o(t))},runPromise(e,t){return u.cachedContext===void 0?ne(ol(u,e),o(t)):te(u.cachedContext)(e,o(t))}};return u};function ol(e,t){return bt(e.contextEffect,e=>Ce(t,e))}function sl(e,t=nr){return`${e}\0${t}`}function Tce(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=sl(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(sl(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(sl(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 cl={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function ll(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Ece(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?ll(t.keyframe):null}function Dce(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?cl:t.streamGeneration>e.streamGeneration?ll(t.keyframe):null}function Oce(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return ll(t.keyframe);if(t.sequence<=e.observedSequence)return cl;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function kce(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return cl;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?cl:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Ace(e,t){return Ece(e,t)??Dce(e,t)??Oce(e,t)??kce(e,t)}function jce(e,t){let n=Ace(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}}ir(fne);var ul=mte(),dl=`Forge`,fl=`Alpha`,pl=dl,ml=`0.9.10`;function hl(e){return{_tag:`Value`,value:e}}function gl(e,t){return{_tag:`Record`,keys:e,value:t}}function _l(e,t){return{_tag:`Array`,length:e,value:t}}qn(`SourceError`);var vl=xt(`effect/ConfigProvider`,{defaultValue:()=>xl()}),yl={...le,toJSON(){return{_id:`ConfigProvider`}}};function bl(e,t,n){let r=Object.create(yl);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 xl(e){let t=e?.env??{APP_VERSION:`0.9.10`,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:``,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.9.10`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Sl(t);return bl(e=>et(wl(n,t,e)))}function Sl(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 Cl=/^(0|[1-9][0-9]*)$/;function wl(e,t,n){let r=t[n.map(String).join(`_`)],i=Tl(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:hl(r):a.every(e=>Cl.test(e))?_l(Math.max(...a.map(e=>parseInt(e,10)))+1,r):gl(new Set(a),r)}function Tl(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 El=`~effect/Config`,Dl=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Ol={...le,...ae,[El]:El,asEffect(){return bt(vl.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function kl(e){let t=Object.create(Ol);return t.parse=e,t}var Al=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*Al(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*Al(e,[...t,i]));return r}}}),jl=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*jl(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=Lte(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*jl(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*jl(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*Al(t,n);case`Suspend`:return yield*jl(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 Ml(e,t){let n=Vte(e),r=Gte(n),i=Ote(n.ast),a=typeof t==`string`?[t]:t??[];return kl(e=>{let t=e.prefix?[...e.prefix,...a]:a;return jl(i,e,a).pipe(ete(e=>r(e).pipe(Ft(e=>new Nte(t.length>0?new Yte(t,e):e)))),Ft(e=>new Dl(e)))})}var Nl=(e,t,n)=>{let r=Pn(e,t),i=Gn.pipe(ar(Pn(Gn,Gn),Jte(n)),ar(r));return Dn([r,i])},Pl=_te(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),Fl=!1,Il=!1,Ll=null,Rl=null,zl=null,Bl=!1,Vl=new Set;function Mce(e){if(Fl||Il)return;if(!e.publicKey||!e.host){Il=!0;return}if(Ll)return;if(typeof window>`u`||typeof location>`u`){Il=!0;return}let t=e.publicKey,n=e.host;Ll=N(async()=>{let{default:e}=await import(`./module-44GyzBiP.js`);return{default:e}},[]).then(({default:e})=>{Rl=e,e.init(t,{api_host:n,person_profiles:`identified_only`,capture_pageview:!1,capture_pageleave:!1,autocapture:!1,disable_session_recording:!0,loaded:()=>{Fl=!0,zl&&Hl(zl),Ul(),Vl.forEach(e=>e())}})}).catch(()=>{Il=!0,Rl=null})}function Hl(e){if(zl=e,!Fl||!Rl)return;let t={};e.email!==void 0&&(t.email=e.email),e.displayName!==void 0&&(t.name=e.displayName),Rl.identify(e.cmmdUserId,t)}function Nce(e){return!Fl||!Rl?!1:Rl.isFeatureEnabled(e)===!0}function Ul(){!Rl||Bl||(Bl=!0,Rl.onFeatureFlags(()=>{Vl.forEach(e=>e())}))}function Pce(e){return Vl.add(e),Fl&&Rl&&(Ul(),e()),()=>{Vl.delete(e)}}var Wl=`token`;function Gl(e){return new URLSearchParams(e.hash.startsWith(`#`)?e.hash.slice(1):e.hash)}function Kl(e){let t=Gl(e).get(Wl)?.trim()??``;if(t.length>0)return t;let n=e.searchParams.get(Wl)?.trim()??``;return n.length>0?n:null}function Fce(e){let t=new URL(e.toString()),n=Gl(t);return n.has(Wl)&&(n.delete(Wl),t.hash=n.toString()),t.searchParams.delete(Wl),t}function ql(e,t){let n=new URL(e.toString());return n.searchParams.delete(Wl),n.hash=new URLSearchParams([[Wl,t]]).toString(),n}function Ice(e,t){let n=new URL(e);return n.pathname=`/login`,ql(n,t).toString()}function Lce(e){return ql(new URL(`/login`,window.location.href),e).toString()}function Rce(e){let t=new URL(e),n=Kl(t),r=new URL(`forge:///pair`);return r.searchParams.set(`serverUrl`,t.origin),n&&r.searchParams.set(Wl,n),r.toString()}var B=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,V=globalThis,Jl=`10.70.0`;function Yl(){return Xl(V),V}function Xl(e){let t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||`10.70.0`,t[Jl]=t[`10.70.0`]||{}}function Zl(e,t,n=V){let r=n.__SENTRY__=n.__SENTRY__||{},i=r[Jl]=r[`10.70.0`]||{};return i[e]||(i[e]=t())}var Ql=[`debug`,`info`,`warn`,`error`,`log`,`assert`,`trace`],zce=`Sentry Logger `,$l={};function eu(e){if(!(`console`in V))return e();let t=V.console,n={},r=Object.keys($l);r.forEach(e=>{let r=$l[e];n[e]=t[e],t[e]=r});try{return e()}finally{r.forEach(e=>{t[e]=n[e]})}}function Bce(){ru().enabled=!0}function Vce(){ru().enabled=!1}function tu(){return ru().enabled}function Hce(...e){nu(`log`,...e)}function Uce(...e){nu(`warn`,...e)}function Wce(...e){nu(`error`,...e)}function nu(e,...t){B&&tu()&&eu(()=>{V.console[e](`${zce}[${e}]:`,...t)})}function ru(){return B?Zl(`loggerSettings`,()=>({enabled:!1})):{enabled:!1}}var H={enable:Bce,disable:Vce,isEnabled:tu,log:Hce,warn:Uce,error:Wce},iu=50,au=/\(error: (.*)\)/,ou=/captureMessage|captureException/;function su(...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=au.test(n)?n.replace(au,`$1`):n;if(!o.includes(`Error: `)){for(let e of t){let t=e(o);if(t){i.push(t);break}}if(i.length>=iu+r)break}}return Kce(i.slice(r))}}function Gce(e){return Array.isArray(e)?su(...e):e}function Kce(e){if(!e.length)return[];let t=Array.from(e);return/sentryWrapped/.test(cu(t).function||``)&&t.pop(),t.reverse(),ou.test(cu(t).function||``)&&(t.pop(),ou.test(cu(t).function||``)&&t.pop()),t.slice(0,iu).map(e=>({...e,filename:e.filename||cu(t).filename,function:e.function||`?`}))}function cu(e){return e[e.length-1]||{}}var lu=`<anonymous>`;function uu(e){try{return!e||typeof e!=`function`?lu:e.name||lu}catch{return lu}}function du(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 qce(e){let t=e?.startsWith(`file://`)?e.slice(7):e;return t?.match(/\/[A-Z]:/)&&(t=t.slice(1)),t}var fu={},pu={};function mu(e,t){return fu[e]=fu[e]||[],fu[e].push(t),()=>{let n=fu[e];if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}function hu(e,t){if(!pu[e]){pu[e]=!0;try{t()}catch(t){B&&H.error(`Error while instrumenting ${e}`,t)}}}function gu(e,t){let n=e&&fu[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: ${uu(r)}
@@ -1002,33 +1002,33 @@ or you can use record.mirror to access the mirror instance during recording.`,RH
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.`,QW={map:{},getId(){return console.error(ZW),-1},getNode(){return console.error(ZW),null},removeNodeFromMap(){console.error(ZW)},has(){return console.error(ZW),!1},reset(){console.error(ZW)}};typeof window<`u`&&window.Proxy&&window.Reflect&&(QW=new Proxy(QW,{get(e,t,n){return t===`map`&&console.error(ZW),Reflect.get(e,t,n)}}));function $W(e,t,n,r,i=window){let a=i.Object.getOwnPropertyDescriptor(e,t);return i.Object.defineProperty(e,t,r?n:{set(e){aG(()=>{n.set.call(this,e)},0),a&&a.set&&a.set.call(this,e)}}),()=>$W(e,t,a||{},!0)}function eG(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 NHe(e){if(!e)return null;try{return e.nodeType===e.ELEMENT_NODE?e:e.parentElement}catch{return null}}function tG(e,t,n,r,i){if(!e)return!1;let a=NHe(e);if(!a)return!1;let o=XW(t,n);if(!i){let e=r&&a.matches(r);return o(a)&&!e}let s=YW(a,o),c=-1;return s<0?!1:(r&&(c=YW(a,XW(null,r))),s>-1&&c<0||s<c)}var nG={};function rG(e){let t=nG[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 nG[e]=r.bind(window)}function iG(...e){return rG(`requestAnimationFrame`)(...e)}function aG(...e){return rG(`setTimeout`)(...e)}var oG=(e=>(e[e[`2D`]=0]=`2D`,e[e.WebGL=1]=`WebGL`,e[e.WebGL2=2]=`WebGL2`,e))(oG||{}),sG;function PHe(e){sG=e}for(var cG=e=>sG?((...t)=>{try{return e(...t)}catch(e){if(sG&&sG(e)===!0)return()=>{};throw e}}):e,lG=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,FHe=typeof Uint8Array>`u`?[]:new Uint8Array(256),uG=0;uG<lG.length;uG++)FHe[lG.charCodeAt(uG)]=uG;var IHe=function(e){var t=new Uint8Array(e),n,r=t.length,i=``;for(n=0;n<r;n+=3)i+=lG[t[n]>>2],i+=lG[(t[n]&3)<<4|t[n+1]>>4],i+=lG[(t[n+1]&15)<<2|t[n+2]>>6],i+=lG[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},dG=new Map;function LHe(e,t){let n=dG.get(e);return n||(n=new Map,dG.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}var fG=(e,t,n)=>{if(!e||!(hG(e,t)||typeof e==`object`))return;let r=e.constructor.name,i=LHe(n,r),a=i.indexOf(e);return a===-1&&(a=i.length,i.push(e)),a};function pG(e,t,n){if(e instanceof Array)return e.map(e=>pG(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:IHe(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[pG(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:[pG(e.data,t,n),e.width,e.height]}:hG(e,t)||typeof e==`object`?{rr_type:e.constructor.name,index:fG(e,t,n)}:e}var mG=(e,t,n)=>e.map(e=>pG(e,t,n)),hG=(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 RHe(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=eG(t.CanvasRenderingContext2D.prototype,s,function(a){return function(...o){return tG(this.canvas,n,r,i,!0)||aG(()=>{let n=mG(o,t,this);e(this.canvas,{type:oG[`2D`],property:s,args:n})},0),a.apply(this,o)}});a.push(o)}catch{let n=$W(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:oG[`2D`],property:s,args:[t],setter:!0})}});a.push(n)}return()=>{a.forEach(e=>e())}}function zHe(e){return e===`experimental-webgl`?`webgl`:e}function gG(e,t,n,r,i){let a=[];try{let o=eG(e.HTMLCanvasElement.prototype,`getContext`,function(e){return function(a,...o){if(!tG(this,t,n,r,!0)){let e=zHe(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 _G(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=eG(e,o,function(e){return function(...c){let l=e.apply(this,c);if(fG(l,s,this),`tagName`in this.canvas&&!tG(this.canvas,r,i,a,!0)){let e=mG(c,s,this),r={type:t,property:o,args:e};n(this.canvas,r)}return l}});c.push(l)}catch{let r=$W(e,o,{set(e){n(this.canvas,{type:t,property:o,args:[e],setter:!0})}});c.push(r)}return c}function BHe(e,t,n,r,i,a){let o=[];return o.push(..._G(t.WebGLRenderingContext.prototype,oG.WebGL,e,n,r,i,a,t)),t.WebGL2RenderingContext!==void 0&&o.push(..._G(t.WebGL2RenderingContext.prototype,oG.WebGL2,e,n,r,i,a,t)),()=>{o.forEach(e=>e())}}var VHe=`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 HHe(){let e=new Blob([VHe]);return URL.createObjectURL(e)}var UHe=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&&PHe(a),(i&&typeof n==`number`||t)&&(this.worker=this.initFPSWorker()),this.addWindow(r),!t&&cG(()=>{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}cG(()=>{if(a&&t===`all`&&this.initCanvasMutationObserver(e,n,r,i),a&&typeof t==`number`){let t=gG(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}iG(t=>this.takeSnapshot(t,!0,e))}initFPSWorker(){let e=new Worker(HHe());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:oG[`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=iG(t)};e=iG(t),this.restoreHandlers.push(()=>{e&&cancelAnimationFrame(e)})}initCanvasMutationObserver(e,t,n,r){let i=gG(e,t,n,r,!1),a=RHe(this.processMutation.bind(this),e,t,n,r),o=BHe(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=>{tG(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=>{cG(()=>{throw this.snapshotInProgressMap.delete(n),e})()})}}),!0)}startPendingCanvasMutationFlusher(){iG(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){let e=t=>{this.rafStamps.latestId=t,iG(e)};iG(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{let n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),iG(()=>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)}jHe();var WHe;(function(e){e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`})(WHe||={});var vG={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}}},GHe=`ReplayCanvas`,yG=1280,KHe=aP(((e={})=>{let[t,n]=e.maxCanvasSize||[],r={quality:e.quality||`medium`,enableManualSnapshot:e.enableManualSnapshot,maxCanvasSize:[t?Math.min(t,yG):yG,n?Math.min(n,yG):yG]},i,a,o=new Promise(e=>a=e);return{name:GHe,getOptions(){let{quality:e,enableManualSnapshot:t,maxCanvasSize:n}=r;return{enableManualSnapshot:t,recordCanvas:!0,getCanvasManager:e=>{let r=new UHe({...e,enableManualSnapshot:t,maxCanvasSize:n,errorHandler:e=>{try{typeof e==`object`&&(e.__rrweb__=!0)}catch{}}});return i=r,a(r),r},...vG[e]||vG.medium}},async snapshot(e,t){(i||await o).snapshot(e,t)}}}));function qHe(e){return e.split(`,`).some(e=>e.trim().startsWith(`sentry-`))}function bG(e){try{return new URL(e,Z.location.origin).href}catch{return}}function JHe(e){return e.entryType===`resource`&&`initiatorType`in e&&typeof e.nextHopProtocol==`string`&&(e.initiatorType===`fetch`||e.initiatorType===`xmlhttprequest`)}function xG(e){try{return new Headers(e)}catch{return}}var SG={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function CG(e,t){let{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:i,enableHTTPTimings:a,tracePropagationTargets:o,onRequestSpanStart:s,onRequestSpanEnd:c}={...SG,...t},l=typeof i==`function`?i:e=>!0,u=e=>XHe(e,o),d={},f=e.getOptions().propagateTraceparent;n&&WL(t=>{let n=xje(t,l,u,d,{propagateTraceparent:f,onRequestSpanEnd:c});if(n){let r=bG(t.fetchData.url),i=r?dF(r).host:void 0,o=r?pF(r):void 0;n.setAttributes({"http.url":o,"url.full":o,"server.address":i}),a&&wG(n,e),s?.(n,{headers:t.headers})}}),r&&pV(t=>{let n=ZHe(t,l,u,d,f,c);n&&(a&&wG(n,e),s?.(n,{headers:xG(t.xhr.__sentry_xhr_v3__?.request_headers)}))})}var YHe=300;function wG(e,t){let{url:n}=yj(e).data;if(!n||typeof n!=`string`)return;let r=()=>void setTimeout(i);if(lM(t)){let t=e.end.bind(e);e.end=e=>{let n=e??cA(),a=!1,o=()=>{a||(a=!0,setTimeout(i),t(n),clearTimeout(s))};r=o;let s=setTimeout(o,YHe)}}let i=DB(`resource`,({entries:t})=>{t.forEach(t=>{JHe(t)&&t.name.endsWith(n)&&(e.setAttributes(WB(t)),r())})})}function XHe(e,t){let n=XL();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?Qk(r.toString(),t)||a&&Qk(r.pathname,t):a}{let n=!!e.match(/^\/(?!\/)/);return t?Qk(e,t):n}}function ZHe(e,t,n,r,i,a){let o=e.xhr,s=o?.[fV];if(!o||o.__sentry_own_request__||!s)return;let{url:c,method:l}=s,u=zj()&&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&&(qA(n,s.status_code),n.end(),a?.(n,{headers:xG(_V(o)),error:e.error})),delete r[t]);return}let d=bG(c),f=dF(d||c),p=d?pF(d):void 0,m=pF(fF(c)),h=X(),g=!!Fj(),_=g||!!h&&lM(h),v=u&&_?vM({name:`${l} ${m}`,attributes:{url:pF(c),type:`xhr`,"http.method":l,"http.url":p,"url.full":p,"server.address":f?.host,[zA]:`auto.http.browser`,[RA]:`http.client`,...f?.search&&{"http.query":f?.search},...f?.hash&&{"http.fragment":f?.hash}}}):new Uj,y=kM(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)&&QHe(o,zj()&&_?y:void 0,i),h&&h.emit(`beforeOutgoingRequestSpan`,v,e),v}function QHe(e,t,n){let{"sentry-trace":r,baggage:i,traceparent:a}=_F({span:t,propagateTraceparent:n});r&&$He(e,r,i,a)}function $He(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||!qHe(t))&&e.setRequestHeader(`baggage`,n)}}catch{}}var TG=new WeakMap,EG=new WeakMap,eUe=9e4,tUe=[`text/event-stream`,`application/x-ndjson`,`application/stream+json`],DG=aP(()=>({name:`FetchStreamPerformance`,setup(){UNe(e=>{if(e.response){let t=TG.get(e.response);if(t&&e.endTimestamp){t.end(e.endTimestamp);let n=EG.get(e.response);n&&clearTimeout(n)}}}),WL(e=>{if(e.endTimestamp&&e.response){let t=e.response.headers?.get(`content-type`)||``;if(e.response.headers?.get(`content-length`)||!tUe.some(e=>t.startsWith(e)))return;let n=e.fetchData?.url||``,r=e.fetchData?.method||`GET`,i=lF(n),a=vM({name:`${r} ${n.startsWith(`data:`)?pF(n):i?uF(i):n}`,startTime:e.endTimestamp,attributes:{url:pF(n),"http.method":r,type:`fetch`,[RA]:`http.client.stream`,[zA]:`auto.http.browser.stream`}});TG.set(e.response,a);let o=setTimeout(()=>{a.isRecording()&&a.end()},eUe);EG.set(e.response,o)}})}})),nUe=`WebVitals`,OG=aP((e={})=>{let t=new Set(e.ignore??[]);return{name:nUe,setup(n){let r=lM(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=OIe({recordClsStandaloneSpans:o,recordLcpStandaloneSpans:s,client:n}),l=new WeakSet;n.on(`afterStartPageLoadSpan`,e=>{l.add(e)}),n.on(`spanEnd`,e=>{l.delete(e)&&(c(),LIe(e,{recordClsOnPageloadSpan:o===!1,recordLcpOnPageloadSpan:s===!1,spanStreamingEnabled:r}))}),r?(t.has(`lcp`)||nLe(n),t.has(`cls`)||iLe(n),t.has(`inp`)||oLe()):t.has(`inp`)||ZIe()},afterAllSetup(){t.has(`inp`)||tLe()}}});function rUe(){Z.document?Z.document.addEventListener(`visibilitychange`,()=>{let e=Fj();if(!e)return;let t=Nj(e);if(Z.document.hidden&&t){let e=`cancelled`,{op:n,status:r}=yj(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 kG=`sentry_previous_trace`,iUe=`sentry.previous_trace`;function aUe(e,{linkPreviousTrace:t,consistentTraceSampling:n}){let r=t===`session-storage`,i=r?cUe():void 0;e.on(`spanStart`,e=>{if(Nj(e)!==e)return;let t=jA().getPropagationContext();i=oUe(i,e,t),r&&sUe(i)});let a=!0;n&&e.on(`beforeSampling`,e=>{if(!i)return;let t=jA(),n=t.getPropagationContext();if(a&&n.parentSpanId){a=!1;return}t.setPropagationContext({...n,dsc:{...n.dsc,sample_rate:String(i.sampleRate),sampled:String(AG(i.spanContext))},sampleRand:i.sampleRand}),e.parentSampled=AG(i.spanContext),e.parentSampleRate=i.sampleRate,e.spanAttributes={...e.spanAttributes,[pOe]:i.sampleRate}})}function oUe(e,t,n){let r=yj(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:{[SOe]:`previous_trace`}}),t.setAttribute(iUe,`${o.traceId}-${o.spanId}-${+!!AG(o)}`)),a)}function sUe(e){try{Z.sessionStorage.setItem(kG,JSON.stringify(e))}catch(e){Q&&Y.warn(`Could not store previous trace in sessionStorage`,e)}}function cUe(){try{let e=Z.sessionStorage?.getItem(kG);return JSON.parse(e)}catch{return}}function AG(e){return e.traceFlags===1}var lUe=`BrowserTracing`,uUe=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function jG(){let e=Z.navigator;return e?.userAgent?uUe.test(e.userAgent):!1}var dUe={...AM,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:`in-memory`,consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...SG},MG=((e={})=>{`enableElementTiming`in e&&JO(()=>{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:O}={...dUe,...e},ee=jG(),te,k;function A(e,r,i=!0,a){let o=r.op===`pageload`,s=r.name,c=l?l(r):r,p=lF(a||XL()),m={...p?.pathname&&{"url.path":p.pathname},...p&&!cF(p)&&{"url.full":p.href},...c.attributes};if(s!==c.name&&(m[IA]=`custom`),c.attributes=m,!i){let e=sA();vM({...c,startTime:e}).end(e);return}t.name=c.name,t.source=m[IA];let h=jM(c,{idleTimeout:u,finalTimeout:d,childSpanTimeout:f,disableAutoFinish:o,beforeSpanEnd:t=>{IIe(t,{ignoreResourceSpans:y,ignorePerformanceApiSpans:b,spanStreamingEnabled:lM(e)}),zG(e,void 0);let n=jA(),r=n.getPropagationContext();n.setPropagationContext({...r,traceId:h.spanContext().traceId,sampled:Tj(h),dsc:Yj(t)}),o&&(k=void 0)},trimIdleSpanEndTimestamp:!E});o&&E&&(k=h),zG(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:lUe,setup(e){if(ee){Q&&Y.log(`[Tracing] Skipping browserTracingIntegration setup for bot user agent.`);return}if(Rj(),a&&J.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes(`long-animation-frame`)?AIe():i&&kIe(),o&&jIe(),C&&n){let e=()=>{te=cA()};addEventListener(`click`,e,{capture:!0}),addEventListener(`keydown`,e,{capture:!0,passive:!0})}function t(){let t=RG(e);t&&!yj(t).timestamp&&(Q&&Y.log(`[Tracing] Finishing current active span with op: ${yj(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.`),A(e,{op:`navigation.redirect`,...n},!1,r.url);return}te=void 0,t(),MA().setPropagationContext({traceId:pA(),sampleRand:Math.random(),propagationSpanId:zj()?void 0:mA()});let i=jA();i.setPropagationContext({traceId:pA(),sampleRand:Math.random(),propagationSpanId:zj()?void 0:mA()}),i.setSDKProcessingMetadata({normalizedRequest:void 0}),A(e,{op:`navigation`,...n,parentSpan:null,forceTransaction:!0},!0,r?.url)}),e.on(`startPageLoadSpan`,(n,r={})=>{if(X()!==e)return;t();let i=uj(r.sentryTrace||FG(`sentry-trace`)||IG(`sentry-trace`),r.baggage||FG(`baggage`)||IG(`baggage`)),a=jA();a.setPropagationContext(i),zj()||(a.getPropagationContext().propagationSpanId=mA()),a.setSDKProcessingMetadata({normalizedRequest:Pz()}),A(e,{op:`pageload`,...n})}),e.on(`endPageloadSpan`,()=>{E&&k&&(k.setAttribute(BA,`reportPageLoaded`),k.end())})},afterAllSetup(e){if(ee)return;e.addIntegration&&!e.getIntegrationByName?.(`WebVitals`)&&e.addIntegration(OG({ignore:r?[]:[`inp`],_experiments:{enableStandaloneClsSpans:s,enableStandaloneLcpSpans:c}}));let n=XL();if(w!==`off`&&aUe(e,{linkPreviousTrace:w,consistentTraceSampling:T}),Z.location){if(x){let t=uA();NG(e,{name:Z.location.pathname,startTime:t?t/1e3:void 0,attributes:{[IA]:`url`,[zA]:`auto.pageload.browser`}})}S&&cV(({to:t,from:r})=>{if(r===void 0&&n?.indexOf(t)!==-1){n=void 0;return}n=void 0;let i=lF(t),a=RG(e),o=a&&C&&pUe(a,te);PG(e,{name:i?.pathname||Z.location.pathname,attributes:{[IA]:`url`,[zA]:`auto.navigation.browser`}},{url:t,isRedirect:o})})}p&&rUe(),o&&fUe(e,u,d,f,t),CG(e,{traceFetch:m,traceXHR:h,tracePropagationTargets:e.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:_,enableHTTPTimings:v,onRequestSpanStart:D,onRequestSpanEnd:O}),g&&e.addIntegration(DG())}}});function NG(e,t,n){e.emit(`startPageLoadSpan`,t,n),jA().setTransactionName(t.name);let r=RG(e);return r&&e.emit(`afterStartPageLoadSpan`,r),r}function PG(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=jA();return a.setTransactionName(t.name),r&&!i&&a.setSDKProcessingMetadata({normalizedRequest:{...Pz(),url:r}}),RG(e)}function FG(e){return(Z.document?.querySelector(`meta[name=${e}]`))?.getAttribute(`content`)||void 0}function IG(e){return(Z.performance?.getEntriesByType?.(`navigation`)[0])?.serverTiming?.find(t=>t.name===e)?.description}function fUe(e,t,n,r,i){let a=Z.document,o;a&&addEventListener(`click`,()=>{let a=`ui.action.click`,s=RG(e);if(s){let e=yj(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=jM({name:i.name,op:a,attributes:{[IA]:i.source||`url`}},{idleTimeout:t,finalTimeout:n,childSpanTimeout:r})},{capture:!0})}var LG=`_sentry_idleSpan`;function RG(e){return e[LG]}function zG(e,t){Mk(e,LG,t)}var BG=1.5;function pUe(e,t){let n=yj(e),r=sA();return!(r-n.start_timestamp>BG||t&&r-t<=BG)}function mUe(e=X()){e?.emit(`endPageloadSpan`)}function hUe(e){let t=Fj();if(t===e)return;let n=jA();e.end=new Proxy(e.end,{apply(e,r,i){return vA(n,t),Reflect.apply(e,r,i)}}),vA(n,e)}var gUe=aP(()=>({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(!lM(e)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} \`traceLifecycle\` to be set to "stream"! ${n}`);return}let i=r.beforeSendSpan;if(i&&!Xj(i)){r.traceLifecycle=`static`,Q&&Y.warn(`${t} a beforeSendSpan callback using \`withStreamedSpan\`! ${n}`);return}let a=new zNe(e);e.on(`afterSpanEnd`,t=>{Tj(t)&&a.add(YM(t,e))}),e.on(`afterSegmentSpanEnd`,e=>{let t=e.spanContext().traceId;setTimeout(()=>{a.flush(t)},500)})}})),VG=1e6,_Ue=`window`in J&&J.window===J&&typeof importScripts>`u`,HG=`0`,UG=_Ue?`main`:`worker`,WG=Z.navigator,GG=``,KG=``,qG=``,JG=WG?.userAgent||``,YG=``,vUe=WG?.language||WG?.languages?.[0]||``;function yUe(e){return typeof e==`object`&&!!e&&`getHighEntropyValues`in e}var XG=WG?.userAgentData;yUe(XG)&&XG.getHighEntropyValues([`architecture`,`model`,`platform`,`platformVersion`,`fullVersionList`]).then(e=>{if(GG=e.platform||``,qG=e.architecture||``,YG=e.model||``,KG=e.platformVersion||``,e.fullVersionList?.length){let t=e.fullVersionList[e.fullVersionList.length-1];JG=`${t.brand} ${t.version}`}}).catch(e=>void 0);function bUe(e){return!(`thread_metadata`in e)}function xUe(e){return bUe(e)?DUe(e):e}function SUe(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 CUe(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=SUe(r),a=xUe(n),o=t||(typeof r.start_timestamp==`number`?r.start_timestamp*1e3:cA()*1e3),s=typeof r.timestamp==`number`?r.timestamp*1e3:cA()*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:GG,version:KG,build_number:JG},device:{locale:vUe,model:YG,manufacturer:JG,architecture:qG,is_emulator:!1},debug_meta:{images:$G(n.resources)},profile:a,transactions:[{name:r.transaction||``,id:r.event_id||eA(),trace_id:i,active_thread_id:HG,relative_start_ns:`0`,relative_end_ns:((s-o)*1e6).toFixed(0)}]}}function wUe(e,t,n){if(e==null)throw TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${e} instead.`);let r=EUe(e),i=t.getOptions(),a=t.getSdkMetadata?.()?.sdk;return{chunk_id:eA(),client_sdk:{name:a?.name??`sentry.javascript.browser`,version:a?.version??`0.0.0`},profiler_id:n||eA(),platform:`javascript`,version:`2`,release:i.release??``,environment:i.environment??`production`,debug_meta:{images:$G(e.resources)},profile:r}}function TUe(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 EUe(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=uA(),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:HG,timestamp:r}}return{frames:t,stacks:n,samples:o,thread_metadata:{[HG]:{name:UG}}}}function ZG(e){return yj(e).op===`pageload`}function DUe(e){let t,n=0,r={samples:[],stacks:[],frames:[],thread_metadata:{[HG]:{name:UG}}},i=e.samples[0];if(!i)return r;let a=i.timestamp,o=uA(),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)*VG).toFixed(0),stack_id:t,thread_id:HG};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)*VG).toFixed(0),stack_id:n,thread_id:HG};r.stacks[n]=l,r.samples[o]=u,n++}),r}function QG(e,t){if(!t.length)return e;for(let n of t)e[1].push([{type:`profile`},n]);return e}function OUe(e){let t=[];return $j(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 $G(e){let t=X()?.getOptions()?.stackParser;return t?mN(t,e):[]}function eK(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 kUe(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 tK=!1,nK=3e4;function AUe(e){return typeof e==`function`}function rK(){let e=Z.Profiler;if(!AUe(e)){Q&&Y.log(`[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.`);return}let t=Math.floor(nK/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.`)),tK=!0}}function iK(e){if(tK)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 eK(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 jUe(e){if(tK)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 eK(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 aK(e){return e.profilesSampleRate!==void 0}function MUe(e,t,n,r){return kUe(n)?CUe(e,t,n,r):null}var oK=new Map;function NUe(){return oK.size}function PUe(e){let t=oK.get(e);return t&&oK.delete(e),t}function FUe(e,t){if(oK.set(e,t),oK.size>30){let e=oK.keys().next().value;e!==void 0&&oK.delete(e)}}var sK=new WeakSet;function cK(e){e.setAttribute(`thread.id`,HG),e.setAttribute(`thread.name`,UG)}function lK(e){let t;ZG(e)&&(t=cA()*1e3);let n=rK();if(!n)return;Q&&Y.log(`[Profiling] started profiling span: ${yj(e).description}`);let r=eA(),i=null;jA().setContext(`profile`,{profile_id:r,start_timestamp:t}),sK.add(e),cK(e);async function a(){if(e&&n){if(i){Q&&Y.log(`[Profiling] profile for:`,yj(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: ${yj(e).description}`),!t){Q&&Y.log(`[Profiling] profiler returned null profile for: ${yj(e).description}`,`this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started`);return}i=t,FUe(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:`,yj(e).description),a()},nK),s=e.end.bind(e);function c(){return e?(a().then(()=>{s()},()=>{s()}),e):s()}e.end=c}var IUe=6e4,LUe=3e5,RUe=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=jUe(e.getOptions());Q&&Y.log(`[Profiling] Initializing profiler (lifecycle='${t}').`),n||Q&&Y.log(`[Profiling] Session not sampled. Skipping lifecycle profiler initialization.`),this._profilerId=eA(),this._client=e,this._sessionSampled=n,this._lifecycleMode=t,t===`trace`&&this._setupTraceLifecycleListeners(e),e.on(`spanStart`,e=>{this._isRunning&&cK(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&&cK(e)}_beginProfiling(){if(!this._isRunning){if(this._isRunning=!0,Q&&Y.log(`[Profiling] Started profiling with profiler ID:`,this._profilerId),NA().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`&&NA().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!==Nj(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,NA().setContext(`profile`,{})}_clearAllRootSpanTimeouts(){this._rootSpanTimeouts.forEach(e=>clearTimeout(e)),this._rootSpanTimeouts.clear()}_registerTraceRootSpan(e){this._activeRootSpanIds.add(e);let t=setTimeout(()=>this._onRootSpanTimeout(e),LUe);this._rootSpanTimeouts.set(e,t)}_startProfilerInstance(){if(this._profiler?.stopped===!1)return;let e=rK();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()}},IUe))}_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=wUe(await e.stop(),this._client,this._profilerId),n=TUe(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=iM(t.getSdkMetadata?.()),r=t.getDsn(),i=t.getOptions().tunnel,a=Zj({event_id:eA(),sent_at:new Date().toISOString(),...n&&{sdk:n},...!!i&&r&&{dsn:ij(r)}},[[{type:`profile_chunk`,platform:`javascript`},e]]);t.sendEnvelope(a).then(null,e=>{Q&&Y.error(`Error while sending profile chunk envelope:`,e)})}},zUe=`BrowserProfiling`,BUe=aP((()=>({name:zUe,setup(e){let t=e.getOptions(),n=new RUe;if(!aK(t)&&!t.profileLifecycle&&(t.profileLifecycle=`manual`),aK(t)&&!t.profilesSampleRate){Q&&Y.log(`[Profiling] Profiling disabled, no profiling options found.`);return}let r=Fj(),i=r&&Nj(r);if(aK(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."),aK(t))i&&ZG(i)&&iK(i)&&lK(i),e.on(`spanStart`,e=>{let t=Nj(e);e===t?iK(e)&&lK(e):sK.has(t)&&cK(e)}),e.on(`beforeEnvelope`,e=>{if(!NUe())return;let t=OUe(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=PUe(r);if(!a){Q&&Y.log(`[Profiling] Could not retrieve profile for span: ${r}`);continue}let o=MUe(r,i,a,e);o&&n.push(o)}QG(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(!zj(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=Fj(),t=e&&Nj(e);t&&n.notifyRootSpanActive(t)},0)}}}}))),VUe=`SpotlightBrowser`,HUe=[{op:`ui.interaction.click`,name:`#sentry-spotlight`}],UUe=((e={})=>{let t=e.sidecarUrl||`http://localhost:8969/stream`;return{name:VUe,setup:()=>{Q&&Y.log(`Using Sidecar URL`,t)},beforeSetup(e){let t=e.getOptions();t.ignoreSpans=[...t.ignoreSpans||[],...HUe]},afterAllSetup:e=>{WUe(e,t)}}});function WUe(e,t){let n=uV(`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:tM(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 GUe=aP(UUe),KUe=aP(()=>({name:`LaunchDarkly`,processEvent(e,t,n){return $F(e)}}));function qUe(){return{name:`sentry-flag-auditor`,type:`flag-used`,synchronous:!0,method:(e,t,n)=>{eI(e,t.value),tI(e,t.value)}}}var JUe=aP(()=>({name:`OpenFeature`,processEvent(e,t,n){return $F(e)}})),YUe=class{after(e,t){eI(t.flagKey,t.value),tI(t.flagKey,t.value)}error(e,t,n){eI(e.flagKey,e.defaultValue),tI(e.flagKey,e.defaultValue)}},XUe=aP(({featureFlagClientClass:e})=>({name:`Unleash`,setupOnce(){let t=e.prototype;jk(t,`isEnabled`,ZUe)},processEvent(e,t,n){return $F(e)}}));function ZUe(e){return function(...t){let n=t[0],r=e.apply(this,t);return typeof n==`string`&&typeof r==`boolean`?(eI(n,r),tI(n,r)):Q&&Y.error(`[Feature Flags] UnleashClient.isEnabled does not match expected signature. arg0: ${n} (${typeof n}), result: ${r} (${typeof r})`),r}}var QUe=(({growthbookClass:e})=>vje({growthbookClass:e})),$Ue=aP(({featureFlagClient:e})=>({name:`Statsig`,setup(t){e.on(`gate_evaluation`,e=>{eI(e.gate.name,e.gate.value),tI(e.gate.name,e.gate.value)})},processEvent(e,t,n){return $F(e)}})),eWe=`WebWorker`,tWe=aP(({worker:e})=>({name:eWe,setupOnce:()=>{(Array.isArray(e)?e:[e]).forEach(e=>uK(e))},addWorker:e=>uK(e)}));function uK(e){e.addEventListener(`message`,e=>{if(iWe(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=>Tk(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),nWe(e.data._sentryWorkerError))}})}function nWe(e){let t=X();if(!t)return;let n=t.getOptions().stackParser,r=t.getOptions().attachStacktrace,i=e.reason,a=wk(i)?kV(i):Uz(n,i,void 0,r,!0);a.level=`error`,e.filename&&(a.contexts={...a.contexts,worker:{filename:e.filename}}),ON(a,{originalException:i,mechanism:{handled:!1,type:`auto.browser.web_worker.onunhandledrejection`}}),Q&&Y.log(`Captured worker unhandled rejection`,i)}function rWe({self:e}){e.postMessage({_sentryMessage:!0,_sentryDebugIds:e._sentryDebugIds??void 0,_sentryModuleMetadata:e._sentryModuleMetadata??void 0}),e.addEventListener(`unhandledrejection`,t=>{let n={reason:OV(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 iWe(e){if(!Tk(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&&!(Tk(e._sentryDebugIds)||e._sentryDebugIds===void 0)||n&&!(Tk(e._sentryModuleMetadata)||e._sentryModuleMetadata===void 0)||r&&!Tk(e._sentryWorkerError)||i&&(!Array.isArray(e._sentryWasmImages)||!e._sentryWasmImages.every(e=>Tk(e)&&typeof e.code_file==`string`)))}var aWe=50,[,oWe]=yV,[,sWe]=XNe(),dK=(e,t=0)=>{let n=[];for(let r of e.split(`
1004
1004
  `).slice(t)){let e=oWe(r),t=sWe(r);if(e&&t?.in_app!==!1?n.push(e):t&&(t.module===void 0&&delete t.module,n.push(t)),n.length>=aWe)break}return nk(n)},cWe=aP(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=$L(r);a.sendStatus({status:document.visibilityState,config:i}),setInterval(()=>{a.sendStatus({status:`alive`,config:i})},i.pollInterval)}}});function fK(){let e=NA().getScopeData(),t=MA().getScopeData(),n=jA().getScopeData();return BM(e,t),BM(e,n),e.eventProcessors=[],e}function lWe(e){MA().addScopeListener(t=>{e(fK(),t)}),jA().addScopeListener(t=>{e(fK(),t)}),NA().addScopeListener(t=>{e(fK(),t)})}var pK=aP(()=>({name:`ScopeToMain`,setup(e){let t=$L(e);lWe((e,n)=>{t.sendScope(JSON.stringify(Uk(e,20,2e3))),n.clearBreadcrumbs(),n.clearAttachments()})}}));function mK(e){let t;return zP(e,async e=>(t||=$L(),t.sendEnvelope(e.body),{statusCode:200}))}function hK(e){return[...FV(e).filter(e=>e.name!==`BrowserSession`&&e.name!==`CultureContext`),pK()]}function gK(e={},t=fRe){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=hK(e)),e.stackParser===void 0&&(e.stackParser=dK),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=mK),delete e.initialScope,t(e)}var _K=e({BrowserClient:()=>Gz,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>Zke,OpenFeatureIntegrationHook:()=>YUe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>RA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>zA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>LA,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>IA,Scope:()=>bA,addBreadcrumb:()=>vF,addEventProcessor:()=>VN,addIntegration:()=>iP,bindScopeToEmitter:()=>Tke,breadcrumbsIntegration:()=>SV,browserApiErrorsIntegration:()=>CV,browserProfilingIntegration:()=>BUe,browserSessionIntegration:()=>TV,browserTracingIntegration:()=>MG,buildLaunchDarklyFlagUsedHandler:()=>qUe,captureConsoleIntegration:()=>EAe,captureEvent:()=>ON,captureException:()=>EN,captureFeedback:()=>aI,captureMessage:()=>DN,captureSession:()=>GN,chromeStackLineParser:()=>yV,consoleLoggingIntegration:()=>Aje,contextLinesIntegration:()=>jRe,continueTrace:()=>fke,createConsolaReporter:()=>Nje,createLangChainCallbackHandler:()=>NL,createTransport:()=>zP,createUserFeedbackEnvelope:()=>FLe,dedupeIntegration:()=>RF,defaultRequestInstrumentationOptions:()=>SG,defaultStackParser:()=>dK,elementTimingIntegration:()=>XIe,endSession:()=>UN,eventFiltersIntegration:()=>xF,eventFromException:()=>Vz,eventFromMessage:()=>Hz,eventLoopBlockIntegration:()=>cWe,exceptionFromError:()=>Lz,extraErrorDataIntegration:()=>NAe,featureFlagsIntegration:()=>_je,feedbackAsyncIntegration:()=>NFe,feedbackIntegration:()=>Iz,feedbackSyncIntegration:()=>Iz,fetchStreamPerformanceIntegration:()=>DG,forceLoad:()=>pRe,functionToStringIntegration:()=>bF,getAbsoluteUrl:()=>bLe,getActiveSpan:()=>Fj,getClient:()=>X,getCurrentScope:()=>jA,getDefaultIntegrations:()=>hK,getFeedback:()=>BPe,getGlobalScope:()=>NA,getIsolationScope:()=>MA,getReplay:()=>DHe,getRootSpan:()=>Nj,getSpanDescendants:()=>Mj,getSpanStatusFromHttpCode:()=>KA,getTraceData:()=>_F,globalHandlersIntegration:()=>DV,graphqlClientIntegration:()=>zRe,growthbookIntegration:()=>QUe,httpClientIntegration:()=>yRe,httpContextIntegration:()=>MV,inboundFiltersIntegration:()=>SF,init:()=>gK,instrumentAnthropicAiClient:()=>YMe,instrumentCreateReactAgent:()=>NNe,instrumentGoogleGenAIClient:()=>sNe,instrumentLangChainEmbeddings:()=>SNe,instrumentLangGraph:()=>PNe,instrumentOpenAiClient:()=>AMe,instrumentOutgoingRequests:()=>CG,instrumentSupabaseClient:()=>XF,isBotUserAgent:()=>jG,isEnabled:()=>BN,isInitialized:()=>zN,lastEventId:()=>RN,launchDarklyIntegration:()=>KUe,linkedErrorsIntegration:()=>NV,logger:()=>nPe,makeRendererTransport:()=>mK,metrics:()=>lPe,moduleMetadataIntegration:()=>CAe,normalizeStringifyValue:()=>PV,onLoad:()=>mRe,openFeatureIntegration:()=>JUe,parameterize:()=>gF,registerSpanErrorInstrumentation:()=>Rj,registerWebWorker:()=>rWe,replayCanvasIntegration:()=>KHe,replayIntegration:()=>KW,reportPageLoaded:()=>mUe,reportingObserverIntegration:()=>_Re,rewriteFramesIntegration:()=>VAe,scopeToMainIntegration:()=>pK,sendFeedback:()=>pR,setActiveSpanInBrowser:()=>hUe,setAttribute:()=>FN,setAttributes:()=>PN,setContext:()=>kN,setConversationId:()=>LN,setCurrentClient:()=>iF,setExtra:()=>jN,setExtras:()=>AN,setHttpStatus:()=>qA,setMeasurement:()=>oM,setTag:()=>NN,setTags:()=>MN,setUser:()=>IN,showReportDialog:()=>IV,spanStreamingIntegration:()=>gUe,spanToBaggageHeader:()=>JOe,spanToJSON:()=>yj,spanToTraceHeader:()=>mj,spotlightBrowserIntegration:()=>GUe,startBrowserTracingNavigationSpan:()=>PG,startBrowserTracingPageLoadSpan:()=>NG,startInactiveSpan:()=>vM,startNewTrace:()=>xM,startSession:()=>HN,startSpan:()=>gM,startSpanManual:()=>_M,statsigIntegration:()=>$Ue,supabaseIntegration:()=>tje,suppressTracing:()=>pke,thirdPartyErrorFilterIntegration:()=>uje,uiProfiler:()=>TLe,unleashIntegration:()=>XUe,updateSpanName:()=>UOe,viewHierarchyIntegration:()=>BRe,webVitalsIntegration:()=>OG,webWorkerIntegration:()=>tWe,withActiveSpan:()=>yM,withIsolationScope:()=>fOe,withScope:()=>PA,withStreamedSpan:()=>YOe,zodErrorsIntegration:()=>lje}),uWe=100,dWe=5,fWe=[`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 vK(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function pWe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),vK(e.extra),vK(e.tags)}function mWe(e){let t=bK(e.version)??`0.0.0`,n=bK(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function yK(e,t){for(let n of t){let t=bK(e[n]);if(t)return t}}function hWe(e){return xK(e.enabled)??e.defaultEnabled??!1}function gWe(e){let t=bK(e.dsn);return!t||hWe(e)===!1?null:{dsn:t,environment:bK(e.environment)??bK(e.defaultEnvironment)??`production`,release:bK(e.release)??bK(e.defaultRelease)??void 0,debug:xK(e.debug)??e.defaultDebug??!1,tracesSampleRate:CK(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:SK(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:SK(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:SK(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:uWe,normalizeDepth:dWe,tags:_We(e)}}function _We(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=bK(r);e&&(t[n]=e)}return t}function bK(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function xK(e){if(typeof e==`boolean`)return e;let t=bK(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function SK(e,t){if(t!==void 0||e!==void 0)return CK(e,t??0)}function CK(e,t){let n=vWe(e);return n===null||n<0||n>1?t:n}function vWe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=bK(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}var wK=Qt(`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`),yWe=`no-drag-region flex h-full min-w-0 items-center gap-1 md:gap-1.5`,TK=`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`,bWe={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`};function EK(e){let t=(0,ul.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,Fr.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=Qt(`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,Fr.jsx)(`span`,{className:m,children:dl}),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,Fr.jsx)(`span`,{className:_,children:fl}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Fr.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,Fr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":pl,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,Fr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":pl,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function DK(e){let t=(0,ul.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Qt(`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,Fr.jsx)(EK,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Fr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}var xWe=[/\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/,/https?:\/\/[^\s'"<>)]*\/api\/provider-egress\/[^\s'"<>)]*/i,/https?:\/\/[^\s'"<>)]*(?:apex|deepseek|moonshot|kimi)[^\s'"<>)]*/i],SWe=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function CWe(e){if(!e)return null;let t=e.toLowerCase();return/\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.`:/\b(rate[\s-]?limit|too\s+many\s+requests|quota|insufficient_quota)\b/.test(t)||/\b429\b/.test(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}function wWe(e){return e?xWe.some(t=>t.test(e)):!1}function OK(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:wWe(n)?CWe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var TWe=[/\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 kK(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&TWe.some(e=>e.test(t))}function AK(e){return kK(e)?null:OK(e,{fallback:SWe})}var jK=`forge-web`,MK=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],NK=[`VITE_SENTRY_RELEASE`],EWe=[`VITE_SENTRY_DSN`],DWe=[`VITE_SENTRY_DEBUG`],OWe=[`VITE_SENTRY_ENABLED`],kWe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],AWe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],jWe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],MWe=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],NWe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],PK=!1,FK={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 PWe(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 FWe(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 IWe(e){return PWe(e).some(kK)||FWe(e)}function LWe(){let e=new URL(window.location.href);Ir?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function RWe(){let e=Ir?`electron-renderer`:`browser`,t={APP_VERSION:`0.9.10`,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:``,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.9.10`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=yK(t,[...NK])??mWe({appName:jK,version:`0.9.10`,commitHash:yK(t,[...NWe])});return gWe({appName:jK,runtime:e,defaultEnvironment:yK(t,[...MK])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:yK(t,[...OWe]),dsn:yK(t,[...EWe]),environment:yK(t,[...MK]),release:yK(t,[...NK]),debug:yK(t,[...DWe]),tracesSampleRate:yK(t,[...kWe]),profilesSampleRate:yK(t,[...AWe]),replaysSessionSampleRate:yK(t,[...jWe]),replaysOnErrorSampleRate:yK(t,[...MWe]),tags:{platform:Ir?`desktop`:`web`}})}function IK(e){return pWe(e),IWe(e)?null:e}function zWe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function LK(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...fWe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...zWe(e)}}function BWe(e){let t=[];e.tracesSampleRate>0&&t.push(MG()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(KW());let n=Iz(FK);t.push(n);try{gK({...LK(e),beforeSend:e=>IK(e),integrations:t})}catch{return null}return PK=!0,_K}function VWe(e){let t=[];e.tracesSampleRate>0&&t.push(NE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(qT());let n=hb(FK);t.push(n);try{pD({...LK(e),beforeSend:e=>IK(e),integrations:t})}catch{return null}return PK=!0,VO}function RK(){if(PK)return Ir?_K:VO;let e=RWe();return e?Ir?BWe(e):VWe(e):null}function zK(e){if(RK()){if(Ir){IN(e);return}Cm(e)}}function BK(e,t,n){if(!RK())return;let r=HWe(e);if(Ir){PA(e=>{t&&e.setTags(t);let i=EN(r);n?.showReportDialog&&IV({eventId:i})});return}Bd(e=>{t&&e.setTags(t);let i=ym(r);n?.showReportDialog&&LS({eventId:i})})}function HWe(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 UWe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){BK(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Fr.jsxs)(`div`,{className:`forge-app-shell flex min-h-svh w-full min-w-0 flex-col bg-background text-foreground`,children:[(0,Fr.jsxs)(`header`,{className:wK,children:[(0,Fr.jsx)(`div`,{className:`no-drag-region flex min-w-0 items-center pl-1 md:pl-2.5`,children:(0,Fr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:LWe,className:`${TK} hover:bg-accent/70`,children:(0,Fr.jsx)(DK,{})})}),(0,Fr.jsx)(`div`,{})]}),(0,Fr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Fr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Fr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Fr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Fr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:()=>window.location.reload(),type:`button`,children:`Reload app`})]})})]}):this.props.children}};function VK(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var WWe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},GWe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},HK=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function UK(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 WK(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 GK(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 KK(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 KWe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function qK(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 JK(e){let t=`${KK(e,`firstName`)??``} ${KK(e,`lastName`)??``}`.trim()||KK(e,`username`)||KK(e,`email`)||`Unknown`;return{id:qK(e,`userId`)??qK(e,`id`)??t,name:t,email:KK(e,`email`),role:KK(e,`role`),avatarUrl:KK(e,`profileImage`)??KK(e,`avatar`)}}function qWe(e){let t=XK(e,`user`)??e;return JK({...typeof t==`object`&&t?t:{},userId:qK(e,`userId`)??qK(t,`id`),role:KK(e,`role`)})}function YK(e){let t=KK(e,`authorFirstName`)??``,n=KK(e,`authorLastName`)??``,r=KK(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:qK(e,`id`)??``,status:i,body:KK(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:KK(e,`authorProfileImage`)??null,createdAt:KK(e,`createdAt`)??``,updatedAt:KK(e,`updatedAt`)??KK(e,`createdAt`)??``,canEdit:KWe(e,`canEdit`)??!1}}function JWe(e,t,n){let r=Array.isArray(e.data)?e.data.map(YK):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function XK(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var YWe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function ZK(e,t){let n=XK(e,t);if(!n)return null;for(let e of YWe){let t=KK(n,e);if(t)return t}return null}function QK(e,t){let n=XK(e,t);return n?qK(n,`id`):null}function $K(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function XWe(e){let t={...e,id:qK(e,`id`)??e.id,title:e.title??KK(e,`name`)??``},n=qK(e,`workspaceId`)??qK(e,`workspace_id`)??QK(e,`workspace`)??e.workspaceId??null;return n!==null||$K(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??KK(e,`start_date`)??null,endDate:e.endDate??KK(e,`end_date`)??null}:t}function eq(e){let t=e.ownerAvatarUrl??KK(e,`owner_avatar_url`)??KK(e,`ownerProfileImage`)??KK(e,`owner_profile_image`)??KK(e,`ownerImage`)??KK(e,`owner_image`)??KK(e,`ownerImageUrl`)??KK(e,`owner_image_url`)??KK(e,`createdByAvatarUrl`)??KK(e,`created_by_avatar_url`)??KK(e,`createdByProfileImage`)??KK(e,`created_by_profile_image`)??ZK(e,`owner`)??ZK(e,`createdBy`)??ZK(e,`created_by`)??null,n={...e,id:qK(e,`id`)??e.id},r=qK(e,`campaignId`)??qK(e,`campaign_id`)??QK(e,`campaign`)??e.campaignId??null;(r!==null||$K(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??KK(e,`campaignTitle`)??KK(e,`campaign_title`)??KK(XK(e,`campaign`),`title`)??KK(XK(e,`campaign`),`name`)??null;(i!==null||$K(e,`campaignTitle`))&&(n.campaignTitle=i);let a=qK(e,`workspaceId`)??qK(e,`workspace_id`)??QK(e,`workspace`)??e.workspaceId??null;(a!==null||$K(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??KK(e,`workspace_name`)??KK(XK(e,`workspace`),`name`)??null;(o!==null||$K(e,`workspaceName`))&&(n.workspaceName=o);let s=KK(e,`workspaceIconUrl`)??KK(e,`workspace_icon_url`)??KK(XK(e,`workspace`),`iconUrl`)??null;(s!==null||$K(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=qK(e,`ownerId`)??qK(e,`owner_id`)??QK(e,`owner`)??e.ownerId??null;(c!==null||$K(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??KK(e,`owner_name`)??KK(XK(e,`owner`),`name`)??null;(l!==null||$K(e,`ownerName`))&&(n.ownerName=l),(t!==null||$K(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=qK(e,`teamId`)??qK(e,`team_id`)??QK(e,`team`)??e.teamId??null;(u!==null||$K(e,`teamId`))&&(n.teamId=u);let d=e.teamName??KK(e,`team_name`)??KK(XK(e,`team`),`name`)??null;(d!==null||$K(e,`teamName`))&&(n.teamName=d);let f=e.startDate??KK(e,`start_date`)??null;(f!==null||$K(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??KK(e,`target_end_date`)??null;return(p!==null||$K(e,`targetEndDate`))&&(n.targetEndDate=p),n}function tq(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 ZWe(e){return tq(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 QWe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function nq(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function rq(e){try{return await e}catch(e){throw e instanceof vr?e.kind===`auth`?new WWe(e.message):new GWe(e.message,e.status??502):e}}var iq=class e{cfg;commentEditIdempotencyKeys=new Map;commentDeleteIdempotencyKeys=new Map;constructor(e={}){let t=e.forgeOrigin===void 0,n=e.forgeOrigin??`http://localhost:13773`;this.cfg={resolveUrl:t?hr:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??gr,...t?{resolveBearerToken:()=>fr()?.bearerToken??null}:{}}}async getTask(e){return rq(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 rq(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await rq(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await rq(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return rq(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return rq(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await rq(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return rq(P({method:`GET`,path:`/api/cmmd/organizations/${e}/members`},this.cfg))}async getWebSocketToken(e){return P({method:`GET`,path:`/api/cmmd/ws-token`,...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async getProjectComments(e,t){let n={};return t?.organizationId&&(n.organizationId=t.organizationId),(await P({method:`GET`,path:`/api/cmmd/projects/${e}/comments`,query:n},this.cfg))?.comments??[]}async getProjectLink(e){return P({method:`GET`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd}},this.cfg)}async listProjectLinks(){return P({method:`GET`,path:`/.well-known/forge/project-links`,suppressBearerToken:!0},this.cfg)}async listProjectContextLinks(e){let t={};e.environmentId&&(t.forgeEnvironmentId=e.environmentId),e.projectId&&(t.forgeProjectId=e.projectId),e.githubRepoFullName&&(t.githubRepoFullName=e.githubRepoFullName),e.cmmdOrganizationId&&(t.cmmdOrganizationId=e.cmmdOrganizationId);let n=await P({method:`GET`,path:`/.well-known/forge/cmmd/project-links`,query:t},this.cfg),r=tn(gne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return tq(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return ZWe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return tq(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),rq(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return rq(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 rq(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 rq(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 vr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of mne){let r=t[e];r!==void 0&&(n[e]=Zn[e]===`nullableId`?nq(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),rq(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)}async getBilling(){return P({method:`GET`,path:`/api/cmmd/billing`},this.cfg)}async getBillingSeries(e){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:e.timeZone}},this.cfg)}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 AUTH_RUNTIME_PATH=`/api/cmmd/auth-runtime`;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`;static USER_CODEX_CREDENTIAL_PATH=`/api/cmmd/providers/codex/credential`;static USER_CLAUDE_CREDENTIAL_PATH=`/api/cmmd/providers/claude/credential`;async provisionAuthRuntime(){return P({method:`POST`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async getAuthRuntimeState(){return P({method:`GET`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async destroyAuthRuntime(){return P({method:`DELETE`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async connectAuthRuntime(){return P({method:`POST`,path:`${e.AUTH_RUNTIME_PATH}/connect`},this.cfg)}async getUserCodexCredential(){return P({method:`GET`,path:e.USER_CODEX_CREDENTIAL_PATH},this.cfg)}async disconnectUserCodexCredential(){return P({method:`DELETE`,path:e.USER_CODEX_CREDENTIAL_PATH},this.cfg)}async getUserClaudeCredential(){return P({method:`GET`,path:e.USER_CLAUDE_CREDENTIAL_PATH},this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(t){return P({method:`DELETE`,path:`${e.PROVIDER_ACCOUNTS_PATH}/${t}`},this.cfg)}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)}async disconnectUserClaudeCredential(){return P({method:`DELETE`,path:e.USER_CLAUDE_CREDENTIAL_PATH},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)}async renameDevice(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(e))}/rename`,body:{displayName:t}},this.cfg)}async revokeDevice(e){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(e))}/revoke`},this.cfg)}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`),UK(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map(XWe)}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`),UK(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(eq)}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 eq(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(JK):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map(qWe):[]}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 JWe(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 YK(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return YK(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 WK(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return WK(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 WK(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=GK(t);return WK(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=GK(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=GK(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=GK(t,t?.taskId);return WK(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=GK(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=GK(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=GK(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=GK(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=GK(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=GK(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:VK(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:VK(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new HK(`createSubtask`)}async createBoardTask(e){throw new HK(`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=nq(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=nq(e.organizationId)),QWe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:nq(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=nq(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 HK(`uploadBrainDoc`)}};function aq(e){return new iq(e)}var oq=new iq({onAuthExpired:gr}),sq=class extends qn(`BootstrapHttpError`){},cq=e=>cee(e,`BootstrapHttpError`);function lq(e){return typeof e!=`object`||!e?!1:!!(cq(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof vr&&e.kind===`auth`)}function uq(e={resolveUrl:hr}){let t=fr()?.bearerToken;return t?{...e,bearerToken:t}:e}var dq=null,fq=null,pq=null,mq=new Set,hq=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function $We(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();zK({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),Hl({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function gq(){if(typeof window>`u`||pq)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(pq=e(e=>{dq=null,fq=null,e.sessionLifecycle.status!==`ready`&&zK(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&Ene().catch(e=>{BK(e,{route:`desktop-auth-session-expired`})})}))}function eGe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function _q(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new sq({message:`${t} returned a non-JSON response (${eGe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function tGe(){return Kl(new URL(window.location.href))}function vq(){let e=new URL(window.location.href),t=Fce(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function nGe(){return Dq(async()=>{let e=hr(`/api/auth/session`),t=await fetch(e,lr({credentials:`include`}));if(!t.ok)throw new sq({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return _q(t,e)})}async function rGe(e,t){return await e.text()||t}var yq=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function iGe(e){return Dq(async()=>{let t={credential:e},n=hr(`/api/auth/bootstrap`),r=await fetch(n,lr({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new sq({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return _q(r,n)})}function bq(e){return new URL(e,window.location.origin).toString()}function xq(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function Sq(){return typeof window>`u`?null:xq(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function aGe(){return typeof window>`u`?!1:One()===`session-expired`}function Cq(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(hq),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function wq(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(hq);return}window.sessionStorage.setItem(hq,JSON.stringify([...e]))}catch{}}function oGe(){let e=Sq();if(!e)return;let t=new Set(Cq());t.add(e),wq(t)}function sGe(e){return Cq().has(e)}function Tq(){let e=Sq();if(!e){wq(new Set);return}let t=new Set(Cq());t.delete(e),wq(t)}async function Eq(){let e=bq(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?_q(t,e):null}async function cGe(e){if(typeof window>`u`)return;let t=xq(e);if(!t||aGe()||mq.has(t)||sGe(t))return;if((await Eq().catch(()=>null))?.authenticated){mq.add(t);return}let n=bq(`/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 sq({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await _q(r,n),mq.add(t)}async function lGe(){let e=await nGe();if(e.authenticated)return e;let t=fr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await Eq().catch(()=>null);return n?.authenticated?n:e}var uGe=new Set([404,502,503,504]),dGe=15e3,fGe=500;function pGe(e){fr()?.source===`paired-bearer`&&lq(e)&&_r(`http`)}async function Dq(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(pGe(e),!hGe(e))throw e;if(Date.now()-t>=dGe)throw BK(e,{route:`bootstrap-retry-exhausted`}),e;await mGe(fGe)}}function mGe(e){return new Promise(t=>{setTimeout(t,e)})}function hGe(e){return cq(e)?uGe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function gGe(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 _Ge(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return gGe(await t(),e)}catch(e){return BK(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function vGe(e,t){return zK(null),kne(t),await ur().catch(e=>{BK(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Dne(t)??`Forge Desktop requires CMMD authentication.`}}async function yGe(){let e=await lGe();if(e.authenticated){if(e.cmmdIdentity){let t=await _Ge(e.cmmdIdentity);return t?(pr(),vGe(e,t)):(pr(),$We(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function bGe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);fq=null,Tq(),await iGe(t),dq=null,vq()}function Oq(){Tq(),fq=null,dq=null}async function kq(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=hr(`/api/auth/bootstrap/command`),s=await fetch(o,lr({body:JSON.stringify({accessToken:r,...i?{refreshToken:i}:{},...a?{mcpToken:a}:{},...t===void 0?{}:{user:t}}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!s.ok)throw new sq({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await _q(s,o),Oq()}async function xGe(){let e=hr(`/api/auth/ws-token`),t=await fetch(e,lr({credentials:`include`,method:`POST`}));if(!t.ok)throw new sq({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return _q(t,e)}async function SGe(e){let t=await xGe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function CGe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=hr(`/api/auth/pairing-token`),a=await fetch(i,lr({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await rGe(a,`Failed to create pairing credential (${a.status}).`));return _q(a,i)}async function wGe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new sq({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return TGe(await _q(t,e))}function TGe(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=EGe(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 EGe(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 DGe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},uq())}catch(e){throw e instanceof vr&&e.kind!==`auth`&&e.code!==null&&yq.has(e.code)?new vr({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 OGe(e={}){return DGe(e.forceFresh===!0)}async function Aq(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},uq())}catch(e){throw e instanceof vr&&e.kind!==`auth`&&e.code!==null&&yq.has(e.code)?new vr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function kGe(e){try{return await Aq(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof vr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof vr||t instanceof Error)return Aq(`/api/command/tasks/update`,e);throw t}}async function AGe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function jGe(){let e=await Promise.allSettled([ur(),AGe()]);zK(null),oGe(),dq=null,fq=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function MGe(){if(gq(),fq?.status===`authenticated`)return pr(),fq;if(dq)return dq;let e=jq();return dq=e,e.then(e=>(e.status===`authenticated`&&(fq=e),e)).finally(()=>{dq===e&&(dq=null)})}async function jq(){return mr().then(e=>cGe(e)).then(()=>yGe())}async function NGe(){gq(),dq=null,fq=null;let e=await jq();return e.status===`authenticated`&&(fq=e,pr()),e}async function PGe(e){let t=e.email.trim();if(!t||!e.password)throw Error(`Enter your CMMD email and password.`);let n=hr(`/api/auth/cmmd-password/token`),r=await fetch(n,lr({body:JSON.stringify({email:t,password:e.password}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new sq({message:await r.text()||`CMMD login failed (${r.status}).`,status:r.status});let i=await _q(r,n);if(i.authenticated===!0)return Oq(),{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 kq(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 FGe=`/.well-known/forge/environment`,Mq=Kt()(e=>({descriptor:null,setDescriptor:t=>e({descriptor:t}),reset:()=>e({descriptor:null})})),Nq=null;function IGe(e){let t=Pq();return t?qie(Io({id:t.environmentId,label:t.label,source:e.source,target:e.target}),t):null}async function LGe(){return Dq(async()=>{await mr();let e=fr()?.bearerToken,t=hr(FGe),n=e?await fetch(t,{headers:{Authorization:`Bearer ${e}`}}):await fetch(t);if(!n.ok)throw new sq({message:`Failed to load server environment descriptor (${n.status}).`,status:n.status});let r=await _q(n,t);return Fq(r),r})}function Pq(){return Mq.getState().descriptor}function RGe(){return Mq(zGe)}function zGe(e){return e.descriptor?.environmentId??null}function BGe(){return Mq(VGe)}function VGe(e){return e.descriptor}function HGe(){return Mq(UGe)}function UGe(e){return $ie(e.descriptor)}function WGe(){return Mq(GGe)}function GGe(e){return eae(e.descriptor)}function Fq(e){Mq.getState().setDescriptor(e)}function KGe(e,t){return t?.primaryMode!==`cloud`||e.environmentId===t.environmentId}function Iq(){let e=fr();return e?IGe({source:e.source,target:e.target}):null}function qGe(){return JGe()}async function JGe(){let e=await mr(),t=Pq();if(t&&KGe(t,e))return Promise.resolve(t);if(t&&Fq(null),Nq)return Nq;let n=LGe();return Nq=n,n.finally(()=>{Nq===n&&(Nq=null)})}function YGe(e,t){return e.reasoningEffortLevels.some(e=>e.value===t)}function Lq(e){return e.reasoningEffortLevels.find(e=>e.isDefault)?.value??null}function Rq(e,t){let n=Lq(e),r=typeof t==`string`?t.trim():null;return r&&!e.promptInjectedEffortLevels.includes(r)&&YGe(e,r)?r:n??void 0}function zq(e,t){return e.contextWindowOptions.some(e=>e.value===t)}function Bq(e){return e.contextWindowOptions.find(e=>e.isDefault)?.value??null}function XGe(e,t){let n=Bq(e);return t&&zq(e,t)?t:n??void 0}function ZGe(e,t){let n=Rq(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 QGe(e,t){let n=Rq(e,t?.effort),r=e.supportsThinkingToggle?t?.thinking:void 0,i=e.supportsFastMode?t?.fastMode:void 0,a=XGe(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 Vq(e){return typeof e==`string`&&/\bultrathink\b/i.test(e)}function Hq(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 Uq(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=Hq(r,e),s=n.find(e=>e.slug===o);return s?s.slug:null}var $Ge=[`codex`,`claudeAgent`];function Wq(e,t){return $Ge.filter(e=>e!==t).some(t=>ene(t,e)!==void 0)}function eKe(e,t){let n=Hq(e,t);return!n||Wq(n,t)?Un[t]:n}function Gq(e,t){return eKe(t,e)}function tKe(e){return typeof e==`string`&&e.trim()||null}function nKe(e,t){let n=e.trim();return!n||t!==`ultrathink`||n.startsWith(`Ultrathink:`)?n:`Ultrathink:\n${n}`}function rKe(){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 Kq=typeof window<`u`?window.localStorage:rKe(),iKe=(e,t)=>kn(rn(e))(t),aKe=(e,t)=>Ate(rn(e))(t),qq=(e,t)=>{let n=Kq.getItem(e);return n?iKe(t,n):null},Jq=(e,t,n)=>{let r=aKe(n,t);Kq.setItem(e,r)},Yq=e=>{Kq.removeItem(e)},Xq=`forge:local_storage_change`;function oKe(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(Xq,{detail:{key:e}}))}function sKe(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return qq(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?Yq(e):Jq(e,i,n),queueMicrotask(()=>oKe(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=qq(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=qq(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(Xq,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(Xq,o)}},[e,t,n]),[r,a]}var Zq=`full-access`,Qq=`default`,$q=`default`,cKe=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,lKe=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function eJ(e){return e.replace(/\r\n/g,`
1006
- `).replace(/^\n+|\n+$/g,``)}function tJ(e){return eJ(e.text).length>0}function uKe(e){return!tJ(e)}function dKe(e){return e.filter(e=>tJ(e))}function fKe(e){let t=eJ(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 pKe(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function nJ(e){return`${e.terminalLabel} ${pKe(e)}`}function rJ(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function mKe(e){return eJ(e.text).split(`
1007
- `).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function hKe(e){let t=e.map(e=>fKe(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(`- ${nJ(r)}:`),n.push(...mKe(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
1008
- `)}function gKe(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+=rJ(e))}return r}function _Ke(e,t){let n=gKe(e,t).trim(),r=hKe(t);return r.length===0?n:n.length>0?`${n}\n\n${r}`:r}function vKe(e){let t=cKe.exec(e);if(!t)return{promptText:e,contextCount:0,previewTitle:null,contexts:[]};let n=e.slice(0,t.index).replace(/\n+$/,``),r=xKe(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=hK(e)),e.stackParser===void 0&&(e.stackParser=dK),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=mK),delete e.initialScope,t(e)}var _K=e({BrowserClient:()=>Gz,MULTIPLEXED_TRANSPORT_EXTRA_KEY:()=>Zke,OpenFeatureIntegrationHook:()=>YUe,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>RA,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>zA,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>LA,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>IA,Scope:()=>bA,addBreadcrumb:()=>vF,addEventProcessor:()=>VN,addIntegration:()=>iP,bindScopeToEmitter:()=>Tke,breadcrumbsIntegration:()=>SV,browserApiErrorsIntegration:()=>CV,browserProfilingIntegration:()=>BUe,browserSessionIntegration:()=>TV,browserTracingIntegration:()=>MG,buildLaunchDarklyFlagUsedHandler:()=>qUe,captureConsoleIntegration:()=>EAe,captureEvent:()=>ON,captureException:()=>EN,captureFeedback:()=>aI,captureMessage:()=>DN,captureSession:()=>GN,chromeStackLineParser:()=>yV,consoleLoggingIntegration:()=>Aje,contextLinesIntegration:()=>jRe,continueTrace:()=>fke,createConsolaReporter:()=>Nje,createLangChainCallbackHandler:()=>NL,createTransport:()=>zP,createUserFeedbackEnvelope:()=>FLe,dedupeIntegration:()=>RF,defaultRequestInstrumentationOptions:()=>SG,defaultStackParser:()=>dK,elementTimingIntegration:()=>XIe,endSession:()=>UN,eventFiltersIntegration:()=>xF,eventFromException:()=>Vz,eventFromMessage:()=>Hz,eventLoopBlockIntegration:()=>cWe,exceptionFromError:()=>Lz,extraErrorDataIntegration:()=>NAe,featureFlagsIntegration:()=>_je,feedbackAsyncIntegration:()=>NFe,feedbackIntegration:()=>Iz,feedbackSyncIntegration:()=>Iz,fetchStreamPerformanceIntegration:()=>DG,forceLoad:()=>pRe,functionToStringIntegration:()=>bF,getAbsoluteUrl:()=>bLe,getActiveSpan:()=>Fj,getClient:()=>X,getCurrentScope:()=>jA,getDefaultIntegrations:()=>hK,getFeedback:()=>BPe,getGlobalScope:()=>NA,getIsolationScope:()=>MA,getReplay:()=>DHe,getRootSpan:()=>Nj,getSpanDescendants:()=>Mj,getSpanStatusFromHttpCode:()=>KA,getTraceData:()=>_F,globalHandlersIntegration:()=>DV,graphqlClientIntegration:()=>zRe,growthbookIntegration:()=>QUe,httpClientIntegration:()=>yRe,httpContextIntegration:()=>MV,inboundFiltersIntegration:()=>SF,init:()=>gK,instrumentAnthropicAiClient:()=>YMe,instrumentCreateReactAgent:()=>NNe,instrumentGoogleGenAIClient:()=>sNe,instrumentLangChainEmbeddings:()=>SNe,instrumentLangGraph:()=>PNe,instrumentOpenAiClient:()=>AMe,instrumentOutgoingRequests:()=>CG,instrumentSupabaseClient:()=>XF,isBotUserAgent:()=>jG,isEnabled:()=>BN,isInitialized:()=>zN,lastEventId:()=>RN,launchDarklyIntegration:()=>KUe,linkedErrorsIntegration:()=>NV,logger:()=>nPe,makeRendererTransport:()=>mK,metrics:()=>lPe,moduleMetadataIntegration:()=>CAe,normalizeStringifyValue:()=>PV,onLoad:()=>mRe,openFeatureIntegration:()=>JUe,parameterize:()=>gF,registerSpanErrorInstrumentation:()=>Rj,registerWebWorker:()=>rWe,replayCanvasIntegration:()=>KHe,replayIntegration:()=>KW,reportPageLoaded:()=>mUe,reportingObserverIntegration:()=>_Re,rewriteFramesIntegration:()=>VAe,scopeToMainIntegration:()=>pK,sendFeedback:()=>pR,setActiveSpanInBrowser:()=>hUe,setAttribute:()=>FN,setAttributes:()=>PN,setContext:()=>kN,setConversationId:()=>LN,setCurrentClient:()=>iF,setExtra:()=>jN,setExtras:()=>AN,setHttpStatus:()=>qA,setMeasurement:()=>oM,setTag:()=>NN,setTags:()=>MN,setUser:()=>IN,showReportDialog:()=>IV,spanStreamingIntegration:()=>gUe,spanToBaggageHeader:()=>JOe,spanToJSON:()=>yj,spanToTraceHeader:()=>mj,spotlightBrowserIntegration:()=>GUe,startBrowserTracingNavigationSpan:()=>PG,startBrowserTracingPageLoadSpan:()=>NG,startInactiveSpan:()=>vM,startNewTrace:()=>xM,startSession:()=>HN,startSpan:()=>gM,startSpanManual:()=>_M,statsigIntegration:()=>$Ue,supabaseIntegration:()=>tje,suppressTracing:()=>pke,thirdPartyErrorFilterIntegration:()=>uje,uiProfiler:()=>TLe,unleashIntegration:()=>XUe,updateSpanName:()=>UOe,viewHierarchyIntegration:()=>BRe,webVitalsIntegration:()=>OG,webWorkerIntegration:()=>tWe,withActiveSpan:()=>yM,withIsolationScope:()=>fOe,withScope:()=>PA,withStreamedSpan:()=>YOe,zodErrorsIntegration:()=>lje}),uWe=100,dWe=5,fWe=[`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 vK(e){if(e)for(let t of Object.keys(e))/token|secret|password|api[_-]?key/i.test(t)&&(e[t]=`[redacted]`)}function pWe(e){e.request?.url&&(e.request.url=e.request.url.replace(/([?&](?:code|token|access_token|state)=)[^&]+/gi,`$1[redacted]`)),vK(e.extra),vK(e.tags)}function mWe(e){let t=bK(e.version)??`0.0.0`,n=bK(e.commitHash);return n?`${e.appName}@${t}+${n}`:`${e.appName}@${t}`}function yK(e,t){for(let n of t){let t=bK(e[n]);if(t)return t}}function hWe(e){return xK(e.enabled)??e.defaultEnabled??!1}function gWe(e){let t=bK(e.dsn);return!t||hWe(e)===!1?null:{dsn:t,environment:bK(e.environment)??bK(e.defaultEnvironment)??`production`,release:bK(e.release)??bK(e.defaultRelease)??void 0,debug:xK(e.debug)??e.defaultDebug??!1,tracesSampleRate:CK(e.tracesSampleRate,e.defaultTracesSampleRate??.1),profilesSampleRate:SK(e.profilesSampleRate,e.defaultProfilesSampleRate),replaysSessionSampleRate:SK(e.replaysSessionSampleRate,e.defaultReplaysSessionSampleRate),replaysOnErrorSampleRate:SK(e.replaysOnErrorSampleRate,e.defaultReplaysOnErrorSampleRate),attachStacktrace:!0,maxBreadcrumbs:uWe,normalizeDepth:dWe,tags:_We(e)}}function _We(e){let t={app:e.appName,runtime:e.runtime};for(let[n,r]of Object.entries(e.tags??{})){let e=bK(r);e&&(t[n]=e)}return t}function bK(e){if(e==null)return null;let t=e.trim();return t.length>0?t:null}function xK(e){if(typeof e==`boolean`)return e;let t=bK(e);if(t){if(t===`1`||t.toLowerCase()===`true`)return!0;if(t===`0`||t.toLowerCase()===`false`)return!1}}function SK(e,t){if(t!==void 0||e!==void 0)return CK(e,t??0)}function CK(e,t){let n=vWe(e);return n===null||n<0||n>1?t:n}function vWe(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;let t=bK(e);if(!t)return null;let n=Number.parseFloat(t);return Number.isFinite(n)?n:null}var wK=Qt(`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`),yWe=`no-drag-region flex h-full min-w-0 items-center gap-1 md:gap-1.5`,TK=`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`,bWe={width:`calc(100% - var(--forge-right-panel-reserved-width, 0px))`};function EK(e){let t=(0,ul.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,Fr.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=Qt(`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,Fr.jsx)(`span`,{className:m,children:dl}),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,Fr.jsx)(`span`,{className:_,children:fl}),t[8]=_,t[9]=v);let y=v;if(a){let e;t[10]!==d||t[11]!==g?(e=(0,Fr.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,Fr.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md`,"aria-label":pl,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,Fr.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,"aria-label":pl,children:[d,g]}),t[16]=d,t[17]=g,t[18]=b):b=t[18],b}function DK(e){let t=(0,ul.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Qt(`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,Fr.jsx)(EK,{}),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,Fr.jsx)(`div`,{className:r,children:i}),t[3]=r,t[4]=a),a}var xWe=[/\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/,/https?:\/\/[^\s'"<>)]*\/api\/provider-egress\/[^\s'"<>)]*/i,/https?:\/\/[^\s'"<>)]*(?:apex|deepseek|moonshot|kimi)[^\s'"<>)]*/i],SWe=`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`;function CWe(e){if(!e)return null;let t=e.toLowerCase();return/\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.`:/\b(rate[\s-]?limit|too\s+many\s+requests|quota|insufficient_quota)\b/.test(t)||/\b429\b/.test(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}function wWe(e){return e?xWe.some(t=>t.test(e)):!1}function OK(e,t={}){if(e==null)return null;let n=e.trim();return n.length===0?null:wWe(n)?CWe(n)??t.fallback??`CMMD is temporarily unavailable. Check the workspace AI connection and retry.`:n}var TWe=[/\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 kK(e){if(typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&TWe.some(e=>e.test(t))}function AK(e){return kK(e)?null:OK(e,{fallback:SWe})}var jK=`forge-web`,MK=[`VITE_SENTRY_ENVIRONMENT`,`MODE`],NK=[`VITE_SENTRY_RELEASE`],EWe=[`VITE_SENTRY_DSN`],DWe=[`VITE_SENTRY_DEBUG`],OWe=[`VITE_SENTRY_ENABLED`],kWe=[`VITE_SENTRY_TRACES_SAMPLE_RATE`],AWe=[`VITE_SENTRY_PROFILES_SAMPLE_RATE`],jWe=[`VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`],MWe=[`VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE`],NWe=[`VITE_SENTRY_COMMIT_SHA`,`VITE_COMMIT_SHA`],PK=!1,FK={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 PWe(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 FWe(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 IWe(e){return PWe(e).some(kK)||FWe(e)}function LWe(){let e=new URL(window.location.href);Ir?e.hash=`/new`:(e.pathname=`/new`,e.search=``,e.hash=``),window.location.assign(e.toString())}function RWe(){let e=Ir?`electron-renderer`:`browser`,t={APP_VERSION:`0.9.10`,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:``,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.9.10`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=yK(t,[...NK])??mWe({appName:jK,version:`0.9.10`,commitHash:yK(t,[...NWe])});return gWe({appName:jK,runtime:e,defaultEnvironment:yK(t,[...MK])??`development`,defaultRelease:n,defaultEnabled:!0,defaultTracesSampleRate:0,defaultReplaysSessionSampleRate:0,defaultReplaysOnErrorSampleRate:0,enabled:yK(t,[...OWe]),dsn:yK(t,[...EWe]),environment:yK(t,[...MK]),release:yK(t,[...NK]),debug:yK(t,[...DWe]),tracesSampleRate:yK(t,[...kWe]),profilesSampleRate:yK(t,[...AWe]),replaysSessionSampleRate:yK(t,[...jWe]),replaysOnErrorSampleRate:yK(t,[...MWe]),tags:{platform:Ir?`desktop`:`web`}})}function IK(e){return pWe(e),IWe(e)?null:e}function zWe(e){return{...e.replaysOnErrorSampleRate===void 0?{}:{replaysOnErrorSampleRate:e.replaysOnErrorSampleRate},...e.replaysSessionSampleRate===void 0?{}:{replaysSessionSampleRate:e.replaysSessionSampleRate}}}function LK(e){return{attachStacktrace:e.attachStacktrace,debug:e.debug,dsn:e.dsn,environment:e.environment,ignoreErrors:[...fWe],initialScope:{tags:e.tags},maxBreadcrumbs:e.maxBreadcrumbs,normalizeDepth:e.normalizeDepth,sendDefaultPii:!1,tracesSampleRate:e.tracesSampleRate,...e.release===void 0?{}:{release:e.release},...zWe(e)}}function BWe(e){let t=[];e.tracesSampleRate>0&&t.push(MG()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(KW());let n=Iz(FK);t.push(n);try{gK({...LK(e),beforeSend:e=>IK(e),integrations:t})}catch{return null}return PK=!0,_K}function VWe(e){let t=[];e.tracesSampleRate>0&&t.push(NE()),((e.replaysSessionSampleRate??0)>0||(e.replaysOnErrorSampleRate??0)>0)&&t.push(qT());let n=hb(FK);t.push(n);try{pD({...LK(e),beforeSend:e=>IK(e),integrations:t})}catch{return null}return PK=!0,VO}function RK(){if(PK)return Ir?_K:VO;let e=RWe();return e?Ir?BWe(e):VWe(e):null}function zK(e){if(RK()){if(Ir){IN(e);return}Cm(e)}}function BK(e,t,n){if(!RK())return;let r=HWe(e);if(Ir){PA(e=>{t&&e.setTags(t);let i=EN(r);n?.showReportDialog&&IV({eventId:i})});return}Bd(e=>{t&&e.setTags(t);let i=ym(r);n?.showReportDialog&&LS({eventId:i})})}function HWe(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 UWe=class extends F.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){BK(e,{origin:`react-boundary`},{showReportDialog:!0})}render(){return this.state.hasError?(0,Fr.jsxs)(`div`,{className:`forge-app-shell flex min-h-svh w-full min-w-0 flex-col bg-background text-foreground`,children:[(0,Fr.jsxs)(`header`,{className:wK,children:[(0,Fr.jsx)(`div`,{className:`no-drag-region flex min-w-0 items-center pl-1 md:pl-2.5`,children:(0,Fr.jsx)(`button`,{type:`button`,"aria-label":`Go to new chat`,onClick:LWe,className:`${TK} hover:bg-accent/70`,children:(0,Fr.jsx)(DK,{})})}),(0,Fr.jsx)(`div`,{})]}),(0,Fr.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-4`,children:(0,Fr.jsxs)(`div`,{className:`max-w-md rounded-xl border border-border bg-card p-6 text-center shadow-lg`,children:[(0,Fr.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`Something went wrong.`}),(0,Fr.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:`Forge hit an unexpected error and reported it.`}),(0,Fr.jsx)(`button`,{className:`mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-accent`,onClick:()=>window.location.reload(),type:`button`,children:`Reload app`})]})})]}):this.props.children}};function WWe(e,t,n){return P({method:`POST`,path:`/api/cmmd/forge-runtimes/${encodeURIComponent(t)}/rename`,body:{displayName:n}},e)}function GWe(e,t,n){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/rename`,body:{displayName:n}},e)}function KWe(e,t){return P({method:`POST`,path:`/api/cmmd/devices/${encodeURIComponent(String(t))}/revoke`},e)}function VK(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor?{cursor:e.cursor}:{}}}var qWe=class extends Error{constructor(e){super(e),this.name=`CmmdApiAuthError`}},JWe=class extends Error{status;constructor(e,t){super(e),this.name=`CmmdApiServerError`,this.status=t}},HK=class extends Error{constructor(e){super(`CmmdApiClient.${e} is not implemented yet`),this.name=`CmmdApiNotImplementedError`}};function UK(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 WK(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 GK(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 KK(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 YWe(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return typeof n==`boolean`?n:null}function qK(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 JK(e){let t=`${KK(e,`firstName`)??``} ${KK(e,`lastName`)??``}`.trim()||KK(e,`username`)||KK(e,`email`)||`Unknown`;return{id:qK(e,`userId`)??qK(e,`id`)??t,name:t,email:KK(e,`email`),role:KK(e,`role`),avatarUrl:KK(e,`profileImage`)??KK(e,`avatar`)}}function XWe(e){let t=XK(e,`user`)??e;return JK({...typeof t==`object`&&t?t:{},userId:qK(e,`userId`)??qK(t,`id`),role:KK(e,`role`)})}function YK(e){let t=KK(e,`authorFirstName`)??``,n=KK(e,`authorLastName`)??``,r=KK(e,`status`),i=r===`at_risk`||r===`off_track`||r===`complete`?r:`on_track`;return{id:qK(e,`id`)??``,status:i,body:KK(e,`body`)??``,authorName:`${t} ${n}`.trim()||null,authorAvatarUrl:KK(e,`authorProfileImage`)??null,createdAt:KK(e,`createdAt`)??``,updatedAt:KK(e,`updatedAt`)??KK(e,`createdAt`)??``,canEdit:YWe(e,`canEdit`)??!1}}function ZWe(e,t,n){let r=Array.isArray(e.data)?e.data.map(YK):[];return{updates:r,pagination:e.pagination??{page:t,limit:n,total:r.length,hasMore:!1}}}function XK(e,t){if(!e||typeof e!=`object`)return null;let n=e[t];return n&&typeof n==`object`?n:null}var QWe=[`avatarUrl`,`avatar_url`,`profileImage`,`profile_image`,`profileImageUrl`,`profile_image_url`,`image`,`imageUrl`,`image_url`,`picture`];function ZK(e,t){let n=XK(e,t);if(!n)return null;for(let e of QWe){let t=KK(n,e);if(t)return t}return null}function QK(e,t){let n=XK(e,t);return n?qK(n,`id`):null}function $K(e,t){return!!(e&&typeof e==`object`&&Object.hasOwn(e,t))}function $We(e){let t={...e,id:qK(e,`id`)??e.id,title:e.title??KK(e,`name`)??``},n=qK(e,`workspaceId`)??qK(e,`workspace_id`)??QK(e,`workspace`)??e.workspaceId??null;return n!==null||$K(e,`workspaceId`)?{...t,workspaceId:n,startDate:e.startDate??KK(e,`start_date`)??null,endDate:e.endDate??KK(e,`end_date`)??null}:t}function eq(e){let t=e.ownerAvatarUrl??KK(e,`owner_avatar_url`)??KK(e,`ownerProfileImage`)??KK(e,`owner_profile_image`)??KK(e,`ownerImage`)??KK(e,`owner_image`)??KK(e,`ownerImageUrl`)??KK(e,`owner_image_url`)??KK(e,`createdByAvatarUrl`)??KK(e,`created_by_avatar_url`)??KK(e,`createdByProfileImage`)??KK(e,`created_by_profile_image`)??ZK(e,`owner`)??ZK(e,`createdBy`)??ZK(e,`created_by`)??null,n={...e,id:qK(e,`id`)??e.id},r=qK(e,`campaignId`)??qK(e,`campaign_id`)??QK(e,`campaign`)??e.campaignId??null;(r!==null||$K(e,`campaignId`))&&(n.campaignId=r);let i=e.campaignTitle??KK(e,`campaignTitle`)??KK(e,`campaign_title`)??KK(XK(e,`campaign`),`title`)??KK(XK(e,`campaign`),`name`)??null;(i!==null||$K(e,`campaignTitle`))&&(n.campaignTitle=i);let a=qK(e,`workspaceId`)??qK(e,`workspace_id`)??QK(e,`workspace`)??e.workspaceId??null;(a!==null||$K(e,`workspaceId`))&&(n.workspaceId=a);let o=e.workspaceName??KK(e,`workspace_name`)??KK(XK(e,`workspace`),`name`)??null;(o!==null||$K(e,`workspaceName`))&&(n.workspaceName=o);let s=KK(e,`workspaceIconUrl`)??KK(e,`workspace_icon_url`)??KK(XK(e,`workspace`),`iconUrl`)??null;(s!==null||$K(e,`workspaceIconUrl`))&&(n.workspaceIconUrl=s);let c=qK(e,`ownerId`)??qK(e,`owner_id`)??QK(e,`owner`)??e.ownerId??null;(c!==null||$K(e,`ownerId`))&&(n.ownerId=c);let l=e.ownerName??KK(e,`owner_name`)??KK(XK(e,`owner`),`name`)??null;(l!==null||$K(e,`ownerName`))&&(n.ownerName=l),(t!==null||$K(e,`ownerAvatarUrl`))&&(n.ownerAvatarUrl=t);let u=qK(e,`teamId`)??qK(e,`team_id`)??QK(e,`team`)??e.teamId??null;(u!==null||$K(e,`teamId`))&&(n.teamId=u);let d=e.teamName??KK(e,`team_name`)??KK(XK(e,`team`),`name`)??null;(d!==null||$K(e,`teamName`))&&(n.teamName=d);let f=e.startDate??KK(e,`start_date`)??null;(f!==null||$K(e,`startDate`))&&(n.startDate=f);let p=e.targetEndDate??KK(e,`target_end_date`)??null;return(p!==null||$K(e,`targetEndDate`))&&(n.targetEndDate=p),n}function tq(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 eGe(e){return tq(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 tGe(e){if(e&&typeof e==`object`){let t=e;if(t.project&&typeof t.project==`object`)return t.project}return e}function nq(e){if(e===null||e.trim()===``)return null;let t=Number(e);return Number.isSafeInteger(t)?t:e}async function rq(e){try{return await e}catch(e){throw e instanceof vr?e.kind===`auth`?new qWe(e.message):new JWe(e.message,e.status??502):e}}var iq=class e{cfg;commentEditIdempotencyKeys=new Map;commentDeleteIdempotencyKeys=new Map;constructor(e={}){let t=e.forgeOrigin===void 0,n=e.forgeOrigin??`http://localhost:13773`;this.cfg={resolveUrl:t?hr:e=>`${n}${e}`,maxRetries:e.maxRetries??3,onAuthExpired:e.onAuthExpired??gr,...t?{resolveBearerToken:()=>fr()?.bearerToken??null}:{}}}async getTask(e){return rq(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 rq(P({method:`GET`,path:`/api/cmmd/tasks/search`,query:t},this.cfg))).tasks??[]}async getTaskComments(e){return(await rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async listProjectTaskComments(e){return(await rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/comments`},this.cfg))).comments??[]}async createProjectTaskComment(e,t){return(await rq(P({method:`POST`,path:`/api/cmmd/tasks/comment`,body:{taskId:e,content:t.content}},this.cfg))).details}async updateProjectTaskComment(e,t,n){return(await rq(P({method:`PATCH`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))).comment}async deleteProjectTaskComment(e,t,n){return rq(P({method:`DELETE`,path:`/api/cmmd/tasks/${e}/comments/${encodeURIComponent(t)}`,body:n},this.cfg))}async getTaskAttachments(e){return rq(P({method:`GET`,path:`/api/cmmd/tasks/${e}/attachments`},this.cfg))}async getProjectRepository(e){return rq(P({method:`GET`,path:`/api/cmmd/projects/${e}/repository`},this.cfg))}async listProjectRepositories(e){return(await rq(P({method:`GET`,path:`/api/cmmd/projects/${e}/repositories`},this.cfg))).repositories}async getWorkspaceMembers(e){return rq(P({method:`GET`,path:`/api/cmmd/organizations/${e}/members`},this.cfg))}async getWebSocketToken(e){return P({method:`GET`,path:`/api/cmmd/ws-token`,...e?.signal===void 0?{}:{signal:e.signal}},this.cfg)}async getProjectComments(e,t){let n={};return t?.organizationId&&(n.organizationId=t.organizationId),(await P({method:`GET`,path:`/api/cmmd/projects/${e}/comments`,query:n},this.cfg))?.comments??[]}async getProjectLink(e){return P({method:`GET`,path:`/.well-known/forge/project-link`,query:{environmentId:e.environmentId,projectId:e.projectId,cwd:e.cwd}},this.cfg)}async listProjectLinks(){return P({method:`GET`,path:`/.well-known/forge/project-links`,suppressBearerToken:!0},this.cfg)}async listProjectContextLinks(e){let t={};e.environmentId&&(t.forgeEnvironmentId=e.environmentId),e.projectId&&(t.forgeProjectId=e.projectId),e.githubRepoFullName&&(t.githubRepoFullName=e.githubRepoFullName),e.cmmdOrganizationId&&(t.cmmdOrganizationId=e.cmmdOrganizationId);let n=await P({method:`GET`,path:`/.well-known/forge/cmmd/project-links`,query:t},this.cfg),r=tn(gne)(n);return r._tag===`Some`?r.value.links:[]}async listCmmdWorkspaces(){return tq(await P({method:`GET`,path:`/.well-known/forge/cmmd/workspaces`},this.cfg))}async listCmmdCampaigns(e){return eGe(await P({method:`GET`,path:`/.well-known/forge/cmmd/campaigns`,query:{workspaceId:e.workspaceId}},this.cfg))}async listCmmdProjects(e){return tq(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),rq(P({method:`POST`,path:`/api/cmmd/tasks/update`,body:n},this.cfg))}async createComment(e){return rq(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 rq(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 rq(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 vr({kind:`server`,message:`CMMD did not return the created project comment.`});return n}async updateProject(e,t){let n={};for(let e of mne){let r=t[e];r!==void 0&&(n[e]=Zn[e]===`nullableId`?nq(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),rq(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)}async getBilling(){return P({method:`GET`,path:`/api/cmmd/billing`},this.cfg)}async getBillingSeries(e){return P({method:`GET`,path:`/api/cmmd/billing/series`,query:{timeZone:e.timeZone}},this.cfg)}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 AUTH_RUNTIME_PATH=`/api/cmmd/auth-runtime`;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`;static USER_CODEX_CREDENTIAL_PATH=`/api/cmmd/providers/codex/credential`;static USER_CLAUDE_CREDENTIAL_PATH=`/api/cmmd/providers/claude/credential`;async provisionAuthRuntime(){return P({method:`POST`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async getAuthRuntimeState(){return P({method:`GET`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async destroyAuthRuntime(){return P({method:`DELETE`,path:e.AUTH_RUNTIME_PATH},this.cfg)}async connectAuthRuntime(){return P({method:`POST`,path:`${e.AUTH_RUNTIME_PATH}/connect`},this.cfg)}async getUserCodexCredential(){return P({method:`GET`,path:e.USER_CODEX_CREDENTIAL_PATH},this.cfg)}async disconnectUserCodexCredential(){return P({method:`DELETE`,path:e.USER_CODEX_CREDENTIAL_PATH},this.cfg)}async getUserClaudeCredential(){return P({method:`GET`,path:e.USER_CLAUDE_CREDENTIAL_PATH},this.cfg)}async getProviderAccounts(){return P({method:`GET`,path:e.PROVIDER_ACCOUNTS_PATH},this.cfg)}async removeLinkedProviderAccount(t){return P({method:`DELETE`,path:`${e.PROVIDER_ACCOUNTS_PATH}/${t}`},this.cfg)}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)}async disconnectUserClaudeCredential(){return P({method:`DELETE`,path:e.USER_CLAUDE_CREDENTIAL_PATH},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 WWe(this.cfg,e,t)}renameDevice(e,t){return GWe(this.cfg,e,t)}revokeDevice(e){return KWe(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`),UK(await P({method:`GET`,path:`/api/cmmd/campaigns`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`campaigns`).map($We)}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`),UK(await P({method:`GET`,path:`/api/cmmd/projects`,query:t,...e?.signal?{signal:e.signal}:{}},this.cfg),`projects`).map(eq)}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 eq(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(JK):[]}async listWorkspaceMembers(){let e=await P({method:`GET`,path:`/api/cmmd/members`},this.cfg);return Array.isArray(e)?e.map(XWe):[]}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 ZWe(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 YK(await P({method:`POST`,path:`/api/cmmd/projects/${e}/updates`,body:t},this.cfg))}async updateProjectUpdate(e,t,n){return YK(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 WK(await P({method:`GET`,path:`/api/cmmd/automations/presets`},this.cfg),`presets`)}async listUserForgeAutomationRules(){return WK(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 WK(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=GK(t);return WK(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/rules`,...n?{query:n}:{}},this.cfg),`rules`)}async createForgeAutomationRule(e,t,n){let r=GK(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=GK(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=GK(t,t?.taskId);return WK(await P({method:`GET`,path:`/api/cmmd/automations/projects/${e}/runs`,...n?{query:n}:{}},this.cfg),`runs`)}async getForgeAutomationRun(e,t){let n=GK(t);return P({method:`GET`,path:`/api/cmmd/automations/runs/${e}`,...n?{query:n}:{}},this.cfg)}async startForgeAutomationRun(e,t,n,r){let i=GK(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=GK(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=GK(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=GK(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=GK(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:VK(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:VK(n)},this.cfg)}async createTask(e){return P({method:`POST`,path:`/api/cmmd/tasks`,body:e},this.cfg)}async createSubtask(e){throw new HK(`createSubtask`)}async createBoardTask(e){throw new HK(`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=nq(e.campaignId)),e.organizationId!==void 0&&e.organizationId!==null&&(t.organizationId=nq(e.organizationId)),tGe(await P({method:`POST`,path:`/api/cmmd/projects`,body:t},this.cfg))}async moveProject(e,t){let n={targetOrgId:nq(t.targetOrgId)};return t.campaignStrategy!==void 0&&(n.campaignStrategy=t.campaignStrategy),t.targetCampaignId!==void 0&&(n.targetCampaignId=nq(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 HK(`uploadBrainDoc`)}};function aq(e){return new iq(e)}var oq=new iq({onAuthExpired:gr}),sq=class extends qn(`BootstrapHttpError`){},cq=e=>cee(e,`BootstrapHttpError`);function lq(e){return typeof e!=`object`||!e?!1:!!(cq(e)&&e.status===401||e instanceof Error&&e.name===`RemoteEnvironmentAuthHttpError`&&`status`in e&&e.status===401||e instanceof vr&&e.kind===`auth`)}function uq(e={resolveUrl:hr}){let t=fr()?.bearerToken;return t?{...e,bearerToken:t}:e}var dq=null,fq=null,pq=null,mq=new Set,hq=`cmmd-forge.loggedOutLocalBootstrapCredentials.v1`;function nGe(e){let t=`${e.firstName??``} ${e.lastName??``}`.trim();zK({id:e.id,email:e.email,...t.length>0?{username:t}:{}}),Hl({cmmdUserId:e.id,...e.email?{email:e.email}:{},...t.length>0?{displayName:t}:{}})}function gq(){if(typeof window>`u`||pq)return;let e=window.desktopBridge?.desktopAuth?.onStateChange;e&&(pq=e(e=>{dq=null,fq=null,e.sessionLifecycle.status!==`ready`&&zK(null),(e.sessionLifecycle.status===`expired`||e.sessionLifecycle.status===`signed-out`&&e.sessionLifecycle.reason===`refresh-revoked`)&&Ene().catch(e=>{BK(e,{route:`desktop-auth-session-expired`})})}))}function rGe(e){let t=e.replace(/\s+/g,` `).trim();return t.length===0?`<empty response>`:t.slice(0,120)}async function _q(e,t){let n=await e.text();try{return JSON.parse(n)}catch{throw new sq({message:`${t} returned a non-JSON response (${rGe(n)}). Ensure the Forge server is running and this route is proxied correctly.`,status:e.status})}}function iGe(){return Kl(new URL(window.location.href))}function vq(){let e=new URL(window.location.href),t=Fce(e);t.toString()!==e.toString()&&window.history.replaceState({},document.title,t.toString())}async function aGe(){return Dq(async()=>{let e=hr(`/api/auth/session`),t=await fetch(e,lr({credentials:`include`}));if(!t.ok)throw new sq({message:`Failed to load server auth session state (${t.status}).`,status:t.status});return _q(t,e)})}async function oGe(e,t){return await e.text()||t}var yq=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`]);async function sGe(e){return Dq(async()=>{let t={credential:e},n=hr(`/api/auth/bootstrap`),r=await fetch(n,lr({body:JSON.stringify(t),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new sq({message:await r.text()||`Failed to bootstrap auth session (${r.status}).`,status:r.status});return _q(r,n)})}function bq(e){return new URL(e,window.location.origin).toString()}function xq(e){let t=(e?.primaryMode===`cloud`?null:e)?.bootstrapToken?.trim();return t&&t.length>0?t:null}function Sq(){return typeof window>`u`?null:xq(window.desktopBridge?.getLocalEnvironmentBootstrap?.()??null)}function cGe(){return typeof window>`u`?!1:One()===`session-expired`}function Cq(){if(typeof window>`u`)return new Set;try{let e=window.sessionStorage.getItem(hq),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function wq(e){if(!(typeof window>`u`))try{if(e.size===0){window.sessionStorage.removeItem(hq);return}window.sessionStorage.setItem(hq,JSON.stringify([...e]))}catch{}}function lGe(){let e=Sq();if(!e)return;let t=new Set(Cq());t.add(e),wq(t)}function uGe(e){return Cq().has(e)}function Tq(){let e=Sq();if(!e){wq(new Set);return}let t=new Set(Cq());t.delete(e),wq(t)}async function Eq(){let e=bq(`/api/auth/session`),t=await fetch(e,{credentials:`include`});return t.ok?_q(t,e):null}async function dGe(e){if(typeof window>`u`)return;let t=xq(e);if(!t||cGe()||mq.has(t)||uGe(t))return;if((await Eq().catch(()=>null))?.authenticated){mq.add(t);return}let n=bq(`/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 sq({message:await r.text()||`Failed to bootstrap local web owner session (${r.status}).`,status:r.status})}await _q(r,n),mq.add(t)}async function fGe(){let e=await aGe();if(e.authenticated)return e;let t=fr();if(t?.source!==`desktop-managed`||!t.bearerToken)return e;let n=await Eq().catch(()=>null);return n?.authenticated?n:e}var pGe=new Set([404,502,503,504]),mGe=15e3,hGe=500;function gGe(e){fr()?.source===`paired-bearer`&&lq(e)&&_r(`http`)}async function Dq(e){let t=Date.now();for(;;)try{return await e()}catch(e){if(gGe(e),!vGe(e))throw e;if(Date.now()-t>=mGe)throw BK(e,{route:`bootstrap-retry-exhausted`}),e;await _Ge(hGe)}}function _Ge(e){return new Promise(t=>{setTimeout(t,e)})}function vGe(e){return cq(e)?pGe.has(e.status):e instanceof TypeError||e instanceof DOMException&&e.name===`AbortError`}function yGe(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 bGe(e){if(typeof window>`u`||!window.desktopBridge)return null;let t=window.desktopBridge.desktopAuth?.getState;if(!t)return`desktop-state-unavailable`;try{return yGe(await t(),e)}catch(e){return BK(e,{route:`desktop-auth-gate-state`}),`desktop-state-unavailable`}}async function xGe(e,t){return zK(null),kne(t),await ur().catch(e=>{BK(e,{route:`desktop-auth-gate-logout`})}),{status:`requires-auth`,auth:e.auth,errorMessage:Dne(t)??`Forge Desktop requires CMMD authentication.`}}async function SGe(){let e=await fGe();if(e.authenticated){if(e.cmmdIdentity){let t=await bGe(e.cmmdIdentity);return t?(pr(),xGe(e,t)):(pr(),nGe(e.cmmdIdentity),{status:`authenticated`})}return{status:`requires-auth`,auth:e.auth}}return{status:`requires-auth`,auth:e.auth}}async function CGe(e){let t=e.trim();if(!t)throw Error(`Enter a pairing token to continue.`);fq=null,Tq(),await sGe(t),dq=null,vq()}function Oq(){Tq(),fq=null,dq=null}async function kq(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=hr(`/api/auth/bootstrap/command`),s=await fetch(o,lr({body:JSON.stringify({accessToken:r,...i?{refreshToken:i}:{},...a?{mcpToken:a}:{},...t===void 0?{}:{user:t}}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!s.ok)throw new sq({message:await s.text()||`Failed to bootstrap with CMMD OAuth token (${s.status}).`,status:s.status});await _q(s,o),Oq()}async function wGe(){let e=hr(`/api/auth/ws-token`),t=await fetch(e,lr({credentials:`include`,method:`POST`}));if(!t.ok)throw new sq({message:await t.text()||`Failed to issue websocket token (${t.status}).`,status:t.status});return _q(t,e)}async function TGe(e){let t=await wGe(),n=new URL(e,window.location.origin);return n.searchParams.set(`wsToken`,t.token),n.toString()}async function EGe(e,t){let n=e?.trim(),r={...n?{label:n}:{},...t?{role:t}:{}},i=hr(`/api/auth/pairing-token`),a=await fetch(i,lr({body:JSON.stringify(r),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!a.ok)throw Error(await oGe(a,`Failed to create pairing credential (${a.status}).`));return _q(a,i)}async function DGe(){let e=new URL(`/api/auth/session`,window.location.origin).toString(),t=await fetch(e,{credentials:`include`});if(!t.ok)throw new sq({message:`Failed to load current app auth session state (${t.status}).`,status:t.status});return OGe(await _q(t,e))}function OGe(e){if(!e.authenticated||!e.role)throw Error(`Authenticated session is required.`);let t=kGe(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 kGe(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 AGe(e){let t=`/api/cmmd/work-intake`,n;try{n=await P({method:`GET`,path:t,allowRetry:!1,...e?{query:{fresh:1}}:{}},uq())}catch(e){throw e instanceof vr&&e.kind!==`auth`&&e.code!==null&&yq.has(e.code)?new vr({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 jGe(e={}){return AGe(e.forceFresh===!0)}async function Aq(e,t){try{return await P({method:`POST`,path:e,body:t,allowRetry:!1},uq())}catch(e){throw e instanceof vr&&e.kind!==`auth`&&e.code!==null&&yq.has(e.code)?new vr({kind:`auth`,message:e.message,status:e.status??401,code:e.code}):e}}async function MGe(e){try{return await Aq(`/api/cmmd/tasks/update`,e)}catch(t){if(t instanceof vr&&(t.kind===`auth`||t.kind===`permission`))throw t;if(t instanceof vr||t instanceof Error)return Aq(`/api/command/tasks/update`,e);throw t}}async function NGe(){typeof window>`u`||await window.desktopBridge?.desktopAuth?.logoutCloud?.()}async function PGe(){let e=await Promise.allSettled([ur(),NGe()]);zK(null),lGe(),dq=null,fq=null;let t=e.find(e=>e.status===`rejected`);if(t)throw t.reason}async function FGe(){if(gq(),fq?.status===`authenticated`)return pr(),fq;if(dq)return dq;let e=jq();return dq=e,e.then(e=>(e.status===`authenticated`&&(fq=e),e)).finally(()=>{dq===e&&(dq=null)})}async function jq(){return mr().then(e=>dGe(e)).then(()=>SGe())}async function IGe(){gq(),dq=null,fq=null;let e=await jq();return e.status===`authenticated`&&(fq=e,pr()),e}async function LGe(e){let t=e.email.trim();if(!t||!e.password)throw Error(`Enter your CMMD email and password.`);let n=hr(`/api/auth/cmmd-password/token`),r=await fetch(n,lr({body:JSON.stringify({email:t,password:e.password}),credentials:`include`,headers:{"content-type":`application/json`},method:`POST`}));if(!r.ok)throw new sq({message:await r.text()||`CMMD login failed (${r.status}).`,status:r.status});let i=await _q(r,n);if(i.authenticated===!0)return Oq(),{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 kq(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 RGe=`/.well-known/forge/environment`,Mq=Kt()(e=>({descriptor:null,setDescriptor:t=>e({descriptor:t}),reset:()=>e({descriptor:null})})),Nq=null;function zGe(e){let t=Pq();return t?qie(Io({id:t.environmentId,label:t.label,source:e.source,target:e.target}),t):null}async function BGe(){return Dq(async()=>{await mr();let e=fr()?.bearerToken,t=hr(RGe),n=e?await fetch(t,{headers:{Authorization:`Bearer ${e}`}}):await fetch(t);if(!n.ok)throw new sq({message:`Failed to load server environment descriptor (${n.status}).`,status:n.status});let r=await _q(n,t);return Fq(r),r})}function Pq(){return Mq.getState().descriptor}function VGe(){return Mq(HGe)}function HGe(e){return e.descriptor?.environmentId??null}function UGe(){return Mq(WGe)}function WGe(e){return e.descriptor}function GGe(){return Mq(KGe)}function KGe(e){return $ie(e.descriptor)}function qGe(){return Mq(JGe)}function JGe(e){return eae(e.descriptor)}function Fq(e){Mq.getState().setDescriptor(e)}function YGe(e,t){return t?.primaryMode!==`cloud`||e.environmentId===t.environmentId}function Iq(){let e=fr();return e?zGe({source:e.source,target:e.target}):null}function XGe(){return ZGe()}async function ZGe(){let e=await mr(),t=Pq();if(t&&YGe(t,e))return Promise.resolve(t);if(t&&Fq(null),Nq)return Nq;let n=BGe();return Nq=n,n.finally(()=>{Nq===n&&(Nq=null)})}function QGe(e,t){return e.reasoningEffortLevels.some(e=>e.value===t)}function Lq(e){return e.reasoningEffortLevels.find(e=>e.isDefault)?.value??null}function Rq(e,t){let n=Lq(e),r=typeof t==`string`?t.trim():null;return r&&!e.promptInjectedEffortLevels.includes(r)&&QGe(e,r)?r:n??void 0}function zq(e,t){return e.contextWindowOptions.some(e=>e.value===t)}function Bq(e){return e.contextWindowOptions.find(e=>e.isDefault)?.value??null}function $Ge(e,t){let n=Bq(e);return t&&zq(e,t)?t:n??void 0}function eKe(e,t){let n=Rq(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 tKe(e,t){let n=Rq(e,t?.effort),r=e.supportsThinkingToggle?t?.thinking:void 0,i=e.supportsFastMode?t?.fastMode:void 0,a=$Ge(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 Vq(e){return typeof e==`string`&&/\bultrathink\b/i.test(e)}function Hq(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 Uq(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=Hq(r,e),s=n.find(e=>e.slug===o);return s?s.slug:null}var nKe=[`codex`,`claudeAgent`];function Wq(e,t){return nKe.filter(e=>e!==t).some(t=>ene(t,e)!==void 0)}function rKe(e,t){let n=Hq(e,t);return!n||Wq(n,t)?Un[t]:n}function Gq(e,t){return rKe(t,e)}function iKe(e){return typeof e==`string`&&e.trim()||null}function aKe(e,t){let n=e.trim();return!n||t!==`ultrathink`||n.startsWith(`Ultrathink:`)?n:`Ultrathink:\n${n}`}function oKe(){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 Kq=typeof window<`u`?window.localStorage:oKe(),sKe=(e,t)=>kn(rn(e))(t),cKe=(e,t)=>Ate(rn(e))(t),qq=(e,t)=>{let n=Kq.getItem(e);return n?sKe(t,n):null},Jq=(e,t,n)=>{let r=cKe(n,t);Kq.setItem(e,r)},Yq=e=>{Kq.removeItem(e)},Xq=`forge:local_storage_change`;function lKe(e){typeof window>`u`||window.dispatchEvent(new CustomEvent(Xq,{detail:{key:e}}))}function uKe(e,t,n){let[r,i]=(0,F.useState)(()=>{try{return qq(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?Yq(e):Jq(e,i,n),queueMicrotask(()=>lKe(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=qq(e,n);i(r??t)}catch(e){console.error(`[LOCALSTORAGE] Error:`,e)}}},[e,t,n]),(0,F.useEffect)(()=>{let r=()=>{try{let r=qq(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(Xq,o),()=>{window.removeEventListener(`storage`,a),window.removeEventListener(Xq,o)}},[e,t,n]),[r,a]}var Zq=`full-access`,Qq=`default`,$q=`default`,dKe=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,fKe=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function eJ(e){return e.replace(/\r\n/g,`
1006
+ `).replace(/^\n+|\n+$/g,``)}function tJ(e){return eJ(e.text).length>0}function pKe(e){return!tJ(e)}function mKe(e){return e.filter(e=>tJ(e))}function hKe(e){let t=eJ(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 gKe(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function nJ(e){return`${e.terminalLabel} ${gKe(e)}`}function rJ(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function _Ke(e){return eJ(e.text).split(`
1007
+ `).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function vKe(e){let t=e.map(e=>hKe(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(`- ${nJ(r)}:`),n.push(..._Ke(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
1008
+ `)}function yKe(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+=rJ(e))}return r}function bKe(e,t){let n=yKe(e,t).trim(),r=vKe(t);return r.length===0?n:n.length>0?`${n}\n\n${r}`:r}function xKe(e){let t=dKe.exec(e);if(!t)return{promptText:e,contextCount:0,previewTitle:null,contexts:[]};let n=e.slice(0,t.index).replace(/\n+$/,``),r=wKe(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 yKe(e){let t=lKe.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 bKe(e){let t=yKe(e),n=vKe(t.promptText);return{visibleText:n.promptText,copyText:e,contextCount:n.contextCount,previewTitle:n.previewTitle,contexts:n.contexts,cmmdContext:t.cmmdContext}}function xKe(e){let t=[],n=null,r=()=>{n&&=(t.push({header:n.header,body:n.bodyLines.join(`
1010
+ `):null,contexts:r}}function SKe(e){let t=fKe.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 CKe(e){let t=SKe(e),n=xKe(t.promptText);return{visibleText:n.promptText,copyText:e,contextCount:n.contextCount,previewTitle:n.previewTitle,contexts:n.contexts,cmmdContext:t.cmmdContext}}function wKe(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 iJ(e){let t=0;for(let n of e)n===``&&(t+=1);return t}function aJ(e,t){let n=t-iJ(e);return n<=0?e:`${``.repeat(n)}${e}`}function SKe(e){return e===void 0||e===` `||e===`
1013
- `||e===` `||e===`\r`}function CKe(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${SKe(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:iJ(e.slice(0,n))}}function wKe(e){return e.replaceAll(``,``)}function TKe(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 oJ(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:oJ(()=>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},lJ=e=>Symbol.iterator in e,uJ=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},EKe=(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 DKe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:lJ(e)&&lJ(t)?uJ(e)&&uJ(t)?dJ(e,t):EKe(e,t):dJ({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function fJ(e){let t=F.useRef(void 0);return n=>{let r=e(n);return DKe(t.current,r)?t.current:t.current=r}}function pJ(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var OKe={enabled:!0,leading:!0,trailing:!0,wait:0},kKe=class{#e;constructor(e,t){this.fn=e,this.store=new wte(pJ()),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`}}),xte(`Throttler`,this)},this.#n=()=>!!Jt(this.options.enabled,this),this.#r=()=>Jt(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(pJ())},this.key=t.key,this.options={...OKe,...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 mJ(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function AKe(e){return e!=null&&typeof e.getItem==`function`&&typeof e.setItem==`function`&&typeof e.removeItem==`function`}function hJ(e){return AKe(e)?e:mJ()}var gJ=mJ();function _J(){return globalThis.localStorage||globalThis.window?.localStorage}var vJ={getItem:e=>{try{let t=_J()?.getItem(e);if(t!==void 0)return t}catch{}return gJ.getItem(e)},setItem:(e,t)=>{try{let n=_J();if(n){n.setItem(e,t);return}}catch{}gJ.setItem(e,t)},removeItem:e=>{try{let t=_J();if(t){t.removeItem(e);return}}catch{}gJ.removeItem(e)}};function yJ(e){let t=vJ.getItem(e);return typeof t==`string`?t:null}function bJ(e,t){vJ.setItem(e,t)}function jKe(e){vJ.removeItem(e)}function MKe(e,t=300){let n=hJ(e),r=new Yt((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()}}}function xJ(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 SJ={providers:{codex:!0,claude:!1,cmmd:!0},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function CJ(e){if(e==null)return SJ;let t=e.providers,n=e.allowedWallets;return{providers:{...SJ.providers,...t},allowedWallets:Array.isArray(n)&&n.length>0?n:SJ.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:SJ.updatedAt}}function NKe(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var PKe={"org-disabled":`Your organisation has not enabled this provider.`,"policy-unavailable":`Forge could not load your organisation’s provider policy, so this provider is unavailable right now. Try again shortly.`,"unknown-provider":`Coming soon.`};function FKe(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 wJ(e,t){let n=NKe(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=FKe(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:CJ(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function TJ(e,t){return wJ(e,t).offered}function IKe(e,t){return EJ(e,t).offered}function EJ(e,t){return t===null?{offered:!0}:wJ(e,t)}function DJ(e,t){return CJ(t).allowedWallets.includes(e)}function OJ(e){return DJ(`personal`,e)}function LKe(e){return e===`claudeAgent`||e===`codex`}function RKe(e,t){return e!==`claudeAgent`||OJ(t)||TJ(`claudeAgent`,t)}function zKe(e){return e.isDebugDisclosureEnabled||LKe(e.provider)&&OJ(e.policy)?!1:!TJ(e.provider===`apex`?`apex`:e.provider,e.policy)}var BKe=new Set([`pending`,`claimed`,`activating`]);function VKe(e){let t=e.current.runtimeId===e.runtimeId?e.current:{runtimeId:e.runtimeId,dataUpdatedAt:0,consecutiveUnavailableResponses:0};return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{runtimeId:e.runtimeId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0}}function HKe(e){return!e.claudeOffered||!e.claudeConnected?!1:e.deliveryStatus===null?e.consecutiveUnavailableResponses>0&&e.consecutiveUnavailableResponses<3:BKe.has(e.deliveryStatus)}function kJ(e){return e.credentialMode===`runtime`?e.provider&&xJ(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`}:UKe({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function UKe(e){return!e.provider||!xJ(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:TJ(e.providerKind,e.policy)?AJ({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function WKe(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:TJ(e.providerKind,e.access.policy)?AJ({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 AJ(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:GKe({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:DJ(`workspace`,e.policy),stage:e.stage})}function GKe(e){return KKe(e.workspaceWalletAllowed)?{eligible:!0}:qKe(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:JKe(e.providerKind,e.personalConnections)?YKe(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function KKe(e){return e&&!1}function qKe(e,t){return e===`codex`&&t?.codex===!0}function JKe(e,t){return t?.[e]===!0}function YKe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||XKe(e.claudeRuntimeReadiness)}function XKe(e){if(!ZKe(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function ZKe(e){return e?.connected===!0&&e.deliveryStatus===`applied`&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function jJ(e){return e.providers.filter(t=>kJ({provider:t,providerKind:t.provider,access:e.access,credentialMode:e.credentialMode}).eligible)}function QKe(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=DJ(`workspace`,e.policy);return t.cmmd?!0:DJ(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var $Ke={providers:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},MJ=[`cmmd`,`forge-provider-access`],eqe=2e3,tqe=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),nqe=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`],NJ=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`}};function rqe(e,t){return!(t instanceof NJ)&&e<3}function iqe(e,t=null){return[...MJ,e,t]}async function aqe(e){e.queryClient.setQueriesData({queryKey:MJ},t=>oqe(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:MJ,refetchType:`all`})}function oqe(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 PJ(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=aq(),r=Tqe(await n.getOrgProviderPolicy());DJ(`workspace`,r);let[i,a,o,s]=await Promise.all([lqe(()=>n.getProviderAccounts()),IJ({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),IJ({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),mqe({enabled:r.providers.claude,runtimeId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=sqe(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 sqe(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function cqe(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 lqe(e){try{return uqe(await e())}catch{return{accounts:[]}}}function uqe(e){if(!LJ(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(dqe)}}function dqe(e){return LJ(e)?fqe(e.provider)&&pqe(e.providerAccountId)&&FJ(e.accountEmail)&&(e.accountDisplayName===void 0||FJ(e.accountDisplayName))&&FJ(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function fqe(e){return e===`codex`||e===`claudeAgent`}function pqe(e){return typeof e==`string`&&e.trim().length>0}function FJ(e){return typeof e==`string`||e===null}async function mqe(e){if(!e.enabled||e.runtimeId===null)return null;try{return _qe(await e.load(e.runtimeId),e.runtimeId)}catch(e){if(e instanceof vr&&(e.kind===`auth`||e.kind===`permission`))throw new NJ(e.kind);return null}}async function IJ(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return Oqe(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function hqe(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function gqe(e){let t=(0,ul.c)(18),n=e.runtimeId??null,r;t[0]===n?r=t[1]:(r={runtimeId:n,dataUpdatedAt:0,consecutiveUnavailableResponses:0},t[0]=n,t[1]=r);let i=(0,F.useRef)(r),a;t[2]!==e.credentialMode||t[3]!==n?(a=iqe(e.credentialMode,n),t[2]=e.credentialMode,t[3]=n,t[4]=a):a=t[4];let o;t[5]===n?o=t[6]:(o=()=>PJ(`cmmd-cloud`,n),t[5]=n,t[6]=o);let s=e.enabled&&e.credentialMode===`cmmd-cloud`,c;t[7]===n?c=t[8]:(c=e=>{if(e.state.error instanceof NJ)return!1;let t=hqe(e.state.data);return i.current=VKe({current:i.current,runtimeId:n,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:n!==null&&t.readinessUnavailable}),n!==null&&HKe({claudeOffered:t.claudeOffered,claudeConnected:t.claudeConnected,deliveryStatus:t.deliveryStatus,consecutiveUnavailableResponses:i.current.consecutiveUnavailableResponses})?eqe:!1},t[7]=n,t[8]=c);let l;t[9]!==a||t[10]!==o||t[11]!==s||t[12]!==c?(l={queryKey:a,queryFn:o,enabled:s,retry:rqe,staleTime:3e4,refetchInterval:c},t[9]=a,t[10]=o,t[11]=s,t[12]=c,t[13]=l):l=t[13];let u=Ni(l);if(!e.enabled){let e;return t[14]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[14]=e):e=t[14],e}if(e.credentialMode===`runtime`){let e;return t[15]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[15]=e):e=t[15],e}if(u.isPending){let e;return t[16]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[16]=e):e=t[16],e}if(u.isError||!u.data){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[17]=e):e=t[17],e}return u.data}function _qe(e,t){if(!LJ(e)||!Cqe(e)||!vqe(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function vqe(e,t){if(e.deliveryReceipt===null)return e.deliveryStatus!==`applied`||e.nativeExecutable!==!0;if(!LJ(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=LJ(n.identity)?n.identity:null;return r!==null&&yqe(n,t)&&Sqe(r,e.generationId)}function yqe(e,t){return bqe(e,t)&&xqe(e)}function bqe(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 xqe(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function Sqe(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function Cqe(e){return typeof e.connected==`boolean`&&tqe.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&nqe.every(t=>wqe(e[t]))}function wqe(e){return e===null||typeof e==`string`}function Tqe(e){if(!LJ(e)||!LJ(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,allowedWallets:n,updatedAt:r}=e,i=Dqe(n,r);if(!Eqe(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 Eqe(e){return typeof e.codex==`boolean`&&typeof e.claude==`boolean`&&typeof e.cmmd==`boolean`}function Dqe(e,t){return Array.isArray(e)&&e.length>0&&e.every(kqe)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function Oqe(e,t){if(!LJ(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 kqe(e){return e===`personal`||e===`workspace`}function LJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Aqe(e){return e.status===`ready`?e.policy:$Ke}var jqe={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},RJ=[`codex`,`claudeAgent`,`apex`];function zJ(e){for(let t of RJ){let n=e.find(e=>e.provider===t);if(n&&VJ(n))return t}return e.find(VJ)?.provider??`codex`}function BJ(e,t){return e.find(e=>e.provider===t)?.models??[]}function VJ(e){return xJ(e)}function HJ(e,t){let n=t??zJ(e),r=e.find(e=>e.provider===n);if(r&&VJ(r)||n===`codex`)return n;for(let t of RJ){let n=e.find(e=>e.provider===t);if(n&&VJ(n))return t}return`codex`}function UJ(e,t,n,r){let i=jJ({providers:e,access:n,credentialMode:r});if(t&&i.some(e=>e.provider===t))return t;let a=zJ(i);return i.some(e=>e.provider===a)?a:null}function Mqe(e,t,n,r){return t==null?UJ(e,null,n,r):jJ({providers:e,access:n,credentialMode:r}).some(e=>e.provider===t)?t:null}function WJ(e,t,n){let r=Hq(t,n);return e.find(e=>e.slug===r)?.capabilities??jqe}function GJ(e,t){let n=BJ(e,t);return n.find(e=>!e.isCustom)?.slug??n[0]?.slug??Un[t]}function KJ(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=WJ(r,n,t),s=a?.[t],c=Rq(o,s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null)??null,l=t===`codex`?ZGe(o,s):QGe(o,s),u=o.promptInjectedEffortLevels.length>0&&Vq(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 qJ(e,t,n,r){return BJ(t,n).map(({slug:e,name:t,isCustom:n})=>({slug:e,name:t,isCustom:n}))}function JJ(e,t,n,r,i){let a=YJ(n,e,i),o=Uq(a,r,qJ(t,n,a,r))??GJ(n,a);return e&&Wq(o,e)?GJ(n,e):o}function YJ(e,t,n){return!t||!TJ(t,n)?HJ(e,`codex`):HJ(e,t)}function Nqe(e,t,n,r){return{codex:qJ(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:qJ(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:qJ(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:qJ(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:qJ(e,t,`apex`,n===`apex`?r:void 0),cursor:qJ(e,t,`cursor`,n===`cursor`?r:void 0),opencode:qJ(e,t,`opencode`,n===`opencode`?r:void 0)}}function Pqe(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:$n.codex},i=YJ(t,r.provider,n),a=JJ(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=KJ({provider:i,model:a,models:BJ(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function XJ(e){return e?.options?{[e.provider]:e.options}:null}function Fqe(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 Iqe(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 Lqe(e){let t=t=>t!==void 0&&Wq(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=Hq(n??r,e.selectedProvider)??GJ(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=Iqe({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?JJ(e.selectedProvider,e.settings,e.providers,s):i,l=Fqe(e.draft?.modelSelectionByProvider)??XJ(e.threadModelSelection)??XJ(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var ZJ=`forge:composer-drafts:v1`,QJ=5,Rqe=jn([`local`,`worktree`]),$J=Bte(wn),eY=MKe(typeof localStorage<`u`?localStorage:mJ(),300);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{eY.flush()});var tY=Vn({id:Gn,name:Gn,mimeType:Gn,sizeBytes:Mn,dataUrl:Gn}),nY=Vn({id:Gn,threadId:an,createdAt:Gn,terminalId:Gn,terminalLabel:Gn,lineStart:Mn,lineEnd:Mn}),zqe=Vn({prompt:Gn,attachments:Hn(tY),terminalContexts:Hn(nY),startedAt:Gn}),Bqe=Vn({prompt:Gn,lastGeneratedPullRequestPrompt:zn(Gn),attachments:Hn(tY),terminalContexts:zn(Hn(nY)),modelSelectionByProvider:zn(Pn(Tn,zn(Sn))),activeProvider:zn(tr(Tn)),runtimeMode:zn(wn),interactionMode:zn(dn),stagedSubmission:zn(zqe)});Vn({effort:zn(jn(Nn)),codexFastMode:zn(Jn),serviceTier:zn(Gn)}),Vn({provider:zn(Tn),model:zn(Gn),modelOptions:zn(tr(Xn))}),Vn({stickyProvider:zn(Tn),stickyModel:zn(Gn),stickyModelOptions:zn(tr(Xn))});var Vqe=Vn({threadId:an,environmentId:Gn,projectId:sn,logicalProjectKey:zn(Gn),createdAt:Gn,runtimeMode:wn,interactionMode:dn,branch:tr(Gn),worktreePath:tr(Gn),envMode:Rqe,promotedTo:zn(tr(Vn({environmentId:Gn,threadId:Gn}))),anchorKind:zn(Ite),anchorCmmdId:zn(tr(Gn)),linkedPullRequest:zn(tr(Dte))}),Hqe=Vn({draftsByThreadKey:Pn(Gn,Bqe),draftThreadsByThreadKey:Pn(Gn,Vqe),logicalProjectDraftThreadKeyByLogicalProjectKey:Pn(Gn,Gn),stickyModelSelectionByProvider:zn(Pn(Tn,zn(Sn))),stickyActiveProvider:zn(tr(Tn))}),Uqe=Vn({version:Mn,state:Hqe}),rY=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),iY=[],aY=[],oY=[],Wqe=[];Object.freeze(iY),Object.freeze(aY),Object.freeze(oY);var sY=Object.freeze({}),Gqe=Object.freeze({activeProvider:null,modelSelectionByProvider:sY}),Kqe=Object.freeze({prompt:``,images:iY,nonPersistedImageIds:aY,persistedAttachments:oY,terminalContexts:Wqe,modelSelectionByProvider:sY,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function cY(){return{prompt:``,images:[],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 uY(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function dY(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim();if(n.length===0||r.length===0)return null;let i=Math.max(1,Math.floor(t.lineStart)),a=Math.max(i,Math.floor(t.lineEnd));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:i,lineEnd:a,text:eJ(t.text)}}function fY(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=dY(e,a);if(!t)continue;let o=uY(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function pY(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===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 mY(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function hY(e){return Nn.some(t=>t===e)}function qqe(e){return Ute.some(t=>t===e)}function gY(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=hY(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&hY(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=qqe(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 _Y(e,t){let n=e&&typeof e==`object`?e:null,r=mY(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=Hq(i,r);if(!a)return null;let o=gY(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 vY(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 yY(e,t){return e?.options===void 0?gY(t):Jqe(gY(t),e.provider,e.options)}function Jqe(e,t,n){let{[t]:r,...i}=e??{},a=gY({[t]:n},t);return gY({...i,...a||{}})}function bY(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:Un[r],options:i})}return e&&(n[e.provider]=e),n}function xY(e){typeof URL>`u`||e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function SY(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.name,i=t.mimeType,a=t.sizeBytes,o=t.dataUrl;return typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`string`||n.length===0||o.length===0?null:{id:n,name:r,mimeType:i,sizeBytes:a,dataUrl:o}}function CY(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 Yqe(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function wY(e){return Ho(e)}function TY(e){return e.trim()}function EY(e){return typeof e==`string`?e.trim():Uo(e)}function DY(e,t){let n=Ko(e);return n?EY(n):t?.environmentId?EY(zo(t.environmentId,e)):e}function Xqe(e){return Ko(e)}function OY(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?Gt.make(e):null}return t}function kY(e,t){let n=OY(e,t);if(!n)return null;if(typeof n!=`string`){let t=EY(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=EY(n);return r.length>0?r:null}function AY(e,t){let n=OY(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??null:n.threadId:null}function jY(e,t){let n=kY(e,t);return n?e.draftsByThreadKey[n]??null:null}function Zqe(e,t){return Object.values(e).includes(t)}function MY(e,t){return{draftId:e,...t}}function Qqe(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 NY(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function PY(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function $qe(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)&&FY(e.linkedPullRequest,t.linkedPullRequest)&&NY(e.promotedTo,t.promotedTo)}function FY(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 IY(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 LY(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=Go(e);if(!t)continue;let i=Ko(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=Ko(t),o=DY(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?zo(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?wY(Ro(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:$J(e.runtimeMode)?e.runtimeMode:Zq,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:Qq,branch:typeof d==`string`?d:null,worktreePath:p,envMode:Yqe(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=Go(e),o=Ko(a),s=DY(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:Zq,interactionMode:Qq,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function RY(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=Xqe(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=SY(e);return t?[t]:[]}):[],l=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=CY(e);return t?[t]:[]}):[],u=$J(e.runtimeMode)?e.runtimeMode:null,d=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,f=eJe(e.stagedSubmission),p=aJ(o,l.length),m=a,h={},g=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)h=e.modelSelectionByProvider,g=mY(e.activeProvider);else{let e=gY(m.modelOptions,void 0,m)??null,t=_Y(m.modelSelection,{provider:m.provider,model:m.model,modelOptions:e??m.modelOptions,legacyCodex:m}),n=yY(t,e),r=vY(t,n);h=bY(r,n),g=r?.provider??null}let _=Object.keys(h).length>0||g!==null;if(o.length===0&&c.length===0&&l.length===0&&!_&&!u&&!d&&!f)continue;let v=Ko(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?DY(i,{environmentId:e}):i})():i:DY(i);r[v]={prompt:p,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{terminalContexts:l}:{},..._?{modelSelectionByProvider:h,activeProvider:g}:{},...u?{runtimeMode:u}:{},...d?{interactionMode:d}:{},...f?{stagedSubmission:f}:{}}}return r}function eJe(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.prompt!=`string`||typeof t.startedAt!=`string`)return null;let n=Array.isArray(t.attachments)?t.attachments.flatMap(e=>{let t=SY(e);return t?[t]:[]}):[],r=Array.isArray(t.terminalContexts)?t.terminalContexts.flatMap(e=>{let t=CY(e);return t?[t]:[]}):[];return{prompt:t.prompt,attachments:n,terminalContexts:r,startedAt:t.startedAt}}function tJe(e){if(!e||typeof e!=`object`)return rY;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=gY(t.stickyModelOptions)??{},o=_Y(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=yY(o,a),c=bY(vY(o,s),s),l=mY(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=LY(r,i);return{draftsByThreadKey:RY(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function nJe(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.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.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}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:{prompt:r.stagedSubmission.prompt,attachments:[...r.stagedSubmission.attachments],terminalContexts:r.stagedSubmission.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd})),startedAt:r.stagedSubmission.startedAt}}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function rJe(e){if(!e||typeof e!=`object`)return rY;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=LY(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=mY(t.stickyActiveProvider);else{let e=gY(t.stickyModelOptions)??{},n=_Y(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=yY(n,e);i=bY(vY(n,r),r),a=mY(t.stickyProvider)}return{draftsByThreadKey:RY(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function iJe(e){if(e.length===0)return[];try{let t=qq(ZJ,Uqe);return!t||t.version!==QJ?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function aJe(e,t,n){let r=new Set;try{eY.flush(),r=new Set(iJe(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 pY(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function oJe(e){let t=e.dataUrl.indexOf(`,`),n=t===-1?e.dataUrl:e.dataUrl.slice(0,t),r=t===-1?``:e.dataUrl.slice(t+1);if(r.length===0)return null;try{if(!n.includes(`;base64`)){let t=decodeURIComponent(r),i=n.startsWith(`data:`)&&n.includes(`;`)?n.slice(5,n.indexOf(`;`)):e.mimeType;return new File([t],e.name,{type:i||e.mimeType})}let t=atob(r),i=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return new File([i],e.name,{type:e.mimeType})}catch{return null}}function sJe(e){return e.flatMap(e=>{let t=oJe(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function cJe(e,t){return e.length>0?e:t?.prompt??``}function lJe(e,t){return e.length>0?e:t?.attachments??[]}function uJe(e,t){return e&&e.length>0?e:t?.terminalContexts??[]}function dJe(e){let t=e.stagedSubmission;return{prompt:cJe(e.prompt,t),attachments:lJe(e.attachments,t),terminalContexts:uJe(e.terminalContexts,t)}}function fJe(e){let t=e.modelSelectionByProvider??{},n=mY(e.activeProvider)??null,r=dJe(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:sJe(r.attachments),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],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,text:``})),modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:null}}function pJe(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??wY(Ro(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?zo(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var zY=Kt()(cJ((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>jY(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=TY(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||PY(i)?null:MY(Gt.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!PY(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return MY(Gt.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(Gt.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Uo(zo(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=TY(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=Qqe(t,i?.threadId??n?.threadId??an.make(r),a,n,i);if(o===r&&$qe(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&&!Zqe(c,o)&&!PY(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(wY(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=kY(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)&&FY(l.linkedPullRequest,t.linkedPullRequest)&&NY(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?IY(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=kY(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:IY(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=kY(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??zo(t.environmentId,t.threadId);return NY(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=kY(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!PY(t))return e;let n=EY(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return IY(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=kY(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)xY(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:IY(e,r)})},setStickyModelSelection:e=>{let t=_Y(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return Ye(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=kY(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]??cY(),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(Ye(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return pY(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={prompt:t.prompt,attachments:[...t.persistedAttachments],terminalContexts:[...t.terminalContexts],startedAt:r},a={...e.draftsByThreadKey};return a[i]={...t,stagedSubmission:n},{draftsByThreadKey:a}})},clearStagedComposerSubmission:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r)=>{let i=kY(t(),e),a=AY(t(),e);if(!i||!a)return;let o=fY(a,r);n(e=>{let t=e.draftsByThreadKey[i]??cY(),n={...t,prompt:aJ(t.prompt,o.length),terminalContexts:o},r={...e.draftsByThreadKey};return pY(n)?delete r[i]:r[i]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=_Y(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY(),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(Ye(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return pY(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=gY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY(),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??Un[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(Ye(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return pY(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=kY(t(),e)??``;if(o.length===0)return;let s=mY(r);if(s===null)return;let c=gY({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??cY(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??Un[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:Un[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(Ye(t.modelSelectionByProvider,n)&&Ye(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return pY(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=$J(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return pY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=kY(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??cY();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return pY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=kY(t(),e),i=AY(t(),e);!r||!i||t().addImages(typeof e==`string`?Gt.make(r):e,[n])},addImages:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY(),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)||xY(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]}}}})},removeImage:(e,r)=>{let i=kY(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&&xY(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 pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=kY(t(),e),s=AY(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??cY(),n=dY(s,i);if(!n)return e;let l=uY(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>uY(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=kY(t(),e),i=AY(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?Gt.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=kY(t(),e),a=AY(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??cY(),n=fY(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:aJ(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=kY(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 pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=kY(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 pY(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{aJe(i,r,n)})},clearComposerContent:e=>{let r=kY(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let{lastGeneratedPullRequestPrompt:n,...i}=t,a={...i,prompt:``,images:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[]},o={...e.draftsByThreadKey};return pY(a)?delete o[r]:o[r]=a,{draftsByThreadKey:o}})}}},{name:ZJ,version:QJ,storage:oJ(()=>eY),migrate:tJe,partialize:nJe,merge:(e,t)=>{let n=rJe(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,fJe(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,pJe(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function mJe(e){let t=(0,ul.c)(2),n;return t[0]===e?n=t[1]:(n=t=>jY(t,e)??Kqe,t[0]=e,t[1]=n),zY(n)}function hJe(e){let t=(0,ul.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=jY(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:Gqe},t[0]=e,t[1]=n),zY(fJ(n))}function gJe(e){let t=(0,ul.c)(10),n;t[0]!==e.draftId||t[1]!==e.threadRef?(n=e.threadRef??e.draftId??Gt.make(``),t[0]=e.draftId,t[1]=e.threadRef,t[2]=n):n=t[2];let r=hJe(n),i,a;return t[3]!==r||t[4]!==e.projectModelSelection||t[5]!==e.providers||t[6]!==e.selectedProvider||t[7]!==e.settings||t[8]!==e.threadModelSelection?(a=Lqe({draft:r,providers:e.providers,selectedProvider:e.selectedProvider,threadModelSelection:e.threadModelSelection,projectModelSelection:e.projectModelSelection,settings:e.settings}),t[3]=r,t[4]=e.projectModelSelection,t[5]=e.providers,t[6]=e.selectedProvider,t[7]=e.settings,t[8]=e.threadModelSelection,t[9]=a):a=t[9],i=a,i}function BY(e){let t=zY.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(Gt.make(n),e)}function _Je(e){for(let t of e)BY(t)}function vJe(e){let t=zY.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(Gt.make(n))}function yJe(e){return{environmentId:e.environmentId,threadId:e.threadId}}function bJe(e){return{draftId:e}}function xJe(e){return!e.environmentId||!e.threadId?null:zo(e.environmentId,e.threadId)}function SJe(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:zo(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}var CJe=F.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return bte(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function VY(e){let t=(0,ul.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=Qt(`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,Fr.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}var HY=`cmmd-runtime:`;function wJe(e){return`${HY}${e}`}function UY(e){return WY(e)!==null}function WY(e){let t=String(e);if(!t.startsWith(`cmmd-runtime:`))return null;let n=t.slice(13);return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(n)?n:null}var GY=`forge:client-settings:v1`,TJe=`forge:saved-environment-registry:v1`,EJe=Vn({environmentId:nn,label:Gn,httpBaseUrl:Gn,wsBaseUrl:Gn,createdAt:Gn,lastConnectedAt:tr(Gn),cmmdOrganizationId:zn(Gn),cmmdProjectId:zn(Gn),runtimeId:zn(Gn),runtimeTicketExpiresAt:zn(Gn),lastAuthenticatedPullRequestCapability:zn(Jn),bearerToken:zn(Gn)}),KY=Vn({version:zn(Mn),records:zn(Hn(EJe))});function qY(){return typeof window<`u`}var DJe={uiFontSize:14,codeFontSize:15},OJe=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function kJe(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function AJe(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(DJe).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 jJe(e){let t=OJe.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 JY(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[kJe,AJe,jJe]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function MJe(){if(!qY())return null;try{let e=window.localStorage.getItem(GY);return e?ir(In)(JY(JSON.parse(e))):null}catch{return null}}function NJe(e){qY()&&Jq(GY,e,In)}function YY(){if(!qY())return{};try{return qq(`forge:saved-environment-registry:v1`,KY)??{}}catch{return{}}}function XY(e){qY()&&Jq(TJe,e,KY)}function ZY(){return YY().records??[]}function PJe(e){XY({version:1,records:e})}function FJe(){return ZY().map(e=>Fn(e))}function IJe(e){let t=new Map(ZY().map(e=>[e.environmentId,e]));PJe(e.map(e=>{let n=UY(e.environmentId)?void 0:t.get(e.environmentId)?.bearerToken;return n?{...Fn(e),bearerToken:n}:Fn(e)}))}function LJe(e){return ZY().find(t=>t.environmentId===e)?.bearerToken??null}function RJe(e,t){let n=YY(),r=n.records??[],i=!1;return XY({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(Fn(n),{bearerToken:t})):n)}),i}function zJe(e){let t=YY();XY({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?Fn(t):t)})}var BJe=ir(In);function VJe(){return typeof window>`u`?void 0:window.desktopBridge}function QY(e){let t=VJe(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function $Y(){let e=QY(`getClientSettings`);if(e){let t=await e();return t?BJe(t):null}return MJe()}async function eX(e){let t=QY(`setClientSettings`);if(t)return t(e);NJe(e)}async function tX(){let e=QY(`getSavedEnvironmentRegistry`);return e?e():FJe()}async function nX(e){let t=QY(`setSavedEnvironmentRegistry`);if(t)return t(e);IJe(e)}async function rX(e){let t=QY(`getSavedEnvironmentSecret`);return t?t(e):LJe(e)}async function iX(e,t){let n=QY(`setSavedEnvironmentSecret`);return n?n(e,t):RJe(e,t)}async function aX(e){let t=QY(`removeSavedEnvironmentSecret`);if(t)return t(e);zJe(e)}var oX=!1,sX=null;function cX(e){return Object.values(e)}function lX(e){return e.map(e=>Fn(e))}function uX(e){try{nX(lX(cX(e))).catch(e=>{console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)})}catch(e){console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)}}function HJe(e){let t=dX.getState().byId,n=Object.fromEntries(e.map(e=>[e.environmentId,e]));dX.setState({byId:{...n,...t}})}async function UJe(){if(oX)return;if(sX)return sX;let e=(async()=>{try{HJe(await tX())}catch(e){console.error(`[SAVED_ENVIRONMENTS] hydrate failed`,e)}finally{oX=!0,dX.setState({hydrated:!0})}})().finally(()=>{sX===e&&(sX=null)});return sX=e,sX}var dX=Kt()(e=>({byId:{},hydrated:oX,upsert:t=>e(e=>{let n={...e.byId,[t.environmentId]:t};return uX(n),{byId:n}}),remove:t=>e(e=>{let{[t]:n,...r}=e.byId;return uX(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 uX(i),{byId:i}}),reset:()=>{uX({}),e({byId:{}})}}));function fX(){return oX}function pX(){return fX()?Promise.resolve():UJe()}function mX(){return Object.values(dX.getState().byId).toSorted((e,t)=>e.label.localeCompare(t.label))}function WJe(){return mX().filter(e=>e.lastAuthenticatedPullRequestCapability===!0)}function hX(e){return dX.getState().byId[e]??null}function GJe(e){let t=Iq();return t?.environmentId===e?Kie(t):hX(e)?.httpBaseUrl??null}function gX(e){let t=GJe(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()}async function _X(e){await nX(lX(cX({...dX.getState().byId,[e.environmentId]:e})))}async function vX(e){return rX(e)}async function KJe(e,t){return iX(e,t)}async function yX(e){await aX(e)}var qJe=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null});function bX(){return{...qJe}}var xX=Kt()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:bX()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??bX(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})})),JJe=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function SX(e){let t=e?.trim();return t&&t.length>0?t:null}function YJe(e){return SX(e)??`Project`}function XJe(e,t=`safe`){let n=SX(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function CX(e,t=`Something went wrong. Try again.`){let n=OK(e instanceof Error?e.message:typeof e==`string`?e:String(e),{fallback:t});return!n||JJe.some(e=>e.test(n))?t:n}function wX(e){return{...e,model:Gq(e.provider,e.model)}}function TX(e){return e.map(e=>({...e}))}function ZJe(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.defaultModelSelection===void 0?{}:{defaultModelSelection:t.defaultModelSelection?wX(t.defaultModelSelection):null},...t.scripts===void 0?{}:{scripts:TX(t.scripts)},updatedAt:t.updatedAt}}var QJe=[],$Je=[],eYe=[],tYe=[],nYe={},rYe={},iYe={},aYe={},oYe=[],EX=new WeakMap,DX=new WeakMap;function OX(e,t,n){if(!e||e.length===0||!t)return n;let r=EX.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||EX.set(e,o),a}function sYe(e,t){return OX(e.messageIdsByThreadId[t],e.messageByThreadId[t]??nYe,QJe)}function cYe(e,t){return OX(e.activityIdsByThreadId[t],e.activityByThreadId[t]??rYe,$Je)}function lYe(e,t){return OX(e.proposedPlanIdsByThreadId[t],e.proposedPlanByThreadId[t]??iYe,eYe)}function uYe(e,t){return OX(e.turnDiffIdsByThreadId[t],e.turnDiffSummaryByThreadId[t]??aYe,tYe)}function kX(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=sYe(e,t),s=cYe(e,t),c=lYe(e,t),l=uYe(e,t),u=DX.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 DX.set(n,{session:r,turnState:i,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l,thread:d}),d}function AX(e){return{settledAt:e.settledAt??null,settledOverride:e.settledOverride??null}}function jX(e,t,n,r){let i=sZ(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 dYe(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]}var MX={projectIds:[],projectById:{},threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:{},messageIdsByThreadId:{},messageByThreadId:{},activityIdsByThreadId:{},activityByThreadId:{},proposedPlanIdsByThreadId:{},proposedPlanByThreadId:{},turnDiffIdsByThreadId:{},turnDiffSummaryByThreadId:{},sidebarThreadSummaryById:{},threadSubscriptionErrorById:{},bootstrapComplete:!1},fYe={activeEnvironmentId:null,environmentStateById:{}},NX=[],PX=[];function FX(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function IX(e){let t=AK(e.lastError);return{provider:OYe(e.providerName),status:DYe(e.status),orchestrationStatus:e.status,activeTurnId:e.activeTurnId??void 0,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{lastError:t}:{}}}function LX(e,t){let n=t.attachments?.map(t=>({type:`image`,id:t.id,name:t.name,mimeType:t.mimeType,sizeBytes:t.sizeBytes,previewUrl:gX({environmentId:e,pathname:kYe(t.id)})}));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 RX(e){return{id:e.id,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId,createdAt:e.createdAt,updatedAt:e.updatedAt}}function zX(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 BX(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,defaultModelSelection:e.defaultModelSelection?wX(e.defaultModelSelection):null,createdAt:e.createdAt,updatedAt:e.updatedAt,scripts:TX(e.scripts)}}function VX(e,t){return{id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:wX(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,session:e.session?IX(e.session):null,messages:e.messages.map(e=>LX(t,e)),proposedPlans:e.proposedPlans.map(RX),error:AK(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...AX(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan,branch:e.branch,worktreePath:e.worktreePath,turnDiffSummaries:e.checkpoints.map(zX),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 HX(e,t){let n={id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:wX(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:AK(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...AX(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?IX(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,...AX(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 pYe(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 mYe(e){return{latestTurn:e.latestTurn,...e.pendingSourceProposedPlan?{pendingSourceProposedPlan:e.pendingSourceProposedPlan}:{}}}function UX(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.threadId===t.threadId&&e.planId===t.planId}function WX(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&&UX(e.sourceProposedPlan,t.sourceProposedPlan)}function GX(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 KX(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 qX(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.title===t.title&&JX(e.titleRegeneration,t.titleRegeneration)&&e.interactionMode===t.interactionMode&&GX(e.session,t.session)&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&WX(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&&KX(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status}function JX(e,t){return e===t?!0:e==null||t==null?!1:e.requestId===t.requestId&&e.startedAt===t.startedAt}function YX(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&&KX(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status&&e.goal===t.goal&&JX(e.titleRegeneration,t.titleRegeneration)}function XX(e,t){return e!==void 0&&WX(e.latestTurn,t.latestTurn)&&UX(e.pendingSourceProposedPlan,t.pendingSourceProposedPlan)}function hYe(e,t){return e.includes(t)?[...e]:[...e,t]}function ZX(e,t){return e.filter(e=>e!==t)}function gYe(e){return{ids:e.messages.map(e=>e.id),byId:Object.fromEntries(e.messages.map(e=>[e.id,e]))}}function _Ye(e){return{ids:e.activities.map(e=>e.id),byId:Object.fromEntries(e.activities.map(e=>[e.id,e]))}}function vYe(e){return{ids:e.proposedPlans.map(e=>e.id),byId:Object.fromEntries(e.proposedPlans.map(e=>[e.id,e]))}}function yYe(e){return{ids:e.turnDiffSummaries.map(e=>e.turnId),byId:Object.fromEntries(e.turnDiffSummaries.map(e=>[e.turnId,e]))}}function bYe(e){return e.projectIds.flatMap(t=>{let n=e.projectById[t];return n?[n]:[]})}function QX(e){return e.threadIds.flatMap(t=>{let n=kX(e,t);return n?[n]:[]})}function $X(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]??NX,i=ZX(n,t);if(i.length===0){let{[r]:t,...n}=e;e=n}else FX(n,i)||(e={...e,[r]:i})}let a=e[n]??NX,o=hYe(a,t);FX(a,o)||(e={...e,[n]:o}),e!==i.threadIdsByProjectId&&(i={...i,threadIdsByProjectId:e})}return i}function eZ(e,t,n){let r=pYe(t),i=mYe(t),a=e.threadShellById[t.id],o=e.threadTurnStateById[t.id],s=$X(e,t.id,t.projectId,n?.projectId);YX(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};qX(c,e)||(s={...s,sidebarThreadSummaryById:{...s.sidebarThreadSummaryById,[t.id]:e}})}if(GX(n?.session??null,t.session)||(s={...s,threadSessionById:{...s.threadSessionById,[t.id]:t.session}}),(n?.rateLimitStatus??PX)!==(t.rateLimitStatus??PX)&&(s={...s,threadRateLimitStatusById:{...s.threadRateLimitStatusById,[t.id]:t.rateLimitStatus??PX}}),XX(o,i)||(s={...s,threadTurnStateById:{...s.threadTurnStateById,[t.id]:i}}),n?.messages!==t.messages){let e=gYe(t);s={...s,messageIdsByThreadId:{...s.messageIdsByThreadId,[t.id]:e.ids},messageByThreadId:{...s.messageByThreadId,[t.id]:e.byId}}}if(n?.activities!==t.activities){let e=_Ye(t);s={...s,activityIdsByThreadId:{...s.activityIdsByThreadId,[t.id]:e.ids},activityByThreadId:{...s.activityByThreadId,[t.id]:e.byId}}}if(n?.proposedPlans!==t.proposedPlans){let e=vYe(t);s={...s,proposedPlanIdsByThreadId:{...s.proposedPlanIdsByThreadId,[t.id]:e.ids},proposedPlanByThreadId:{...s.proposedPlanByThreadId,[t.id]:e.byId}}}if(n?.turnDiffSummaries!==t.turnDiffSummaries){let e=yYe(t);s={...s,turnDiffIdsByThreadId:{...s.turnDiffIdsByThreadId,[t.id]:e.ids},turnDiffSummaryByThreadId:{...s.turnDiffSummaryByThreadId,[t.id]:e.byId}}}return s}function tZ(e,t){let n=e.threadShellById[t.shell.id],r=$X(e,t.shell.id,t.shell.projectId,n?.projectId);return YX(n,t.shell)||(r={...r,threadShellById:{...r.threadShellById,[t.shell.id]:t.shell}}),GX(e.threadSessionById[t.shell.id]??null,t.session)||(r={...r,threadSessionById:{...r.threadSessionById,[t.shell.id]:t.session}}),XX(e.threadTurnStateById[t.shell.id],t.turnState)||(r={...r,threadTurnStateById:{...r.threadTurnStateById,[t.shell.id]:t.turnState}}),qX(e.sidebarThreadSummaryById[t.shell.id],t.summary)||(r={...r,sidebarThreadSummaryById:{...r.sidebarThreadSummaryById,[t.shell.id]:t.summary}}),r}function nZ(e,t){return Object.fromEntries(Object.entries(e).flatMap(([e,n])=>t.has(e)?[[e,n]]:[]))}function rZ(e,t){let n=e.threadShellById[t],r=e.sidebarThreadSummaryById[t],i=n?.projectId??r?.projectId;if(!i)return e;let a=ZX(e.threadIds,t),o=ZX(e.threadIdsByProjectId[i]??NX,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]:O,...ee}=e.turnDiffSummaryByThreadId,{[t]:te,...k}=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:ee,sidebarThreadSummaryById:k}}function xYe(e,t){let n=new Set(e.threadIdsByProjectId[t]??NX);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 iZ(e,t){let n=xYe(e,t);if(!e.projectById[t]&&n.length===0&&!e.projectIds.includes(t))return e;let r=e;for(let e of n)r=rZ(r,e);let{[t]:i,...a}=r.projectById;return{...r,projectById:a,projectIds:ZX(r.projectIds,t)}}function aZ(e){return e===`error`?`error`:e===`missing`?`interrupted`:`completed`}function SYe(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 oZ(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 CYe(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 wYe(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 TYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function EYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function DYe(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 OYe(e){return e===`codex`||e===`claudeAgent`||e===`ollama`||e===`cmmd`||e===`apex`?e:`codex`}function kYe(e){return`/attachments/${encodeURIComponent(e)}`}function sZ(e,t,n){let r=kX(e,t);if(!r)return e;let i=n(r);return i===r?e:eZ(e,i,r)}function AYe(e){return{projectIds:e.map(e=>e.id),projectById:Object.fromEntries(e.map(e=>[e.id,e]))}}function cZ(e,t){return e.environmentStateById[t]??MX}function lZ(e,t,n){let r=e.environmentStateById[t]===n?e.environmentStateById:{...e.environmentStateById,[t]:n};return r===e.environmentStateById?e:{...e,environmentStateById:r}}function jYe(e,t,n){let r=t.projects.map(e=>BX(e,n)),i=new Set(t.threads.map(e=>e.id)),a={...e,...AYe(r),threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:nZ(e.threadRateLimitStatusById,i),sidebarThreadSummaryById:{},messageIdsByThreadId:nZ(e.messageIdsByThreadId,i),messageByThreadId:nZ(e.messageByThreadId,i),activityIdsByThreadId:nZ(e.activityIdsByThreadId,i),activityByThreadId:nZ(e.activityByThreadId,i),proposedPlanIdsByThreadId:nZ(e.proposedPlanIdsByThreadId,i),proposedPlanByThreadId:nZ(e.proposedPlanByThreadId,i),turnDiffIdsByThreadId:nZ(e.turnDiffIdsByThreadId,i),turnDiffSummaryByThreadId:nZ(e.turnDiffSummaryByThreadId,i),bootstrapComplete:!0};for(let e of t.threads)a=tZ(a,HX(e,n));return a}function MYe(e,t,n){return lZ(e,n,jYe(cZ(e,n),t,n))}function NYe(e,t,n){let r=cZ(e,n),i=kX(r,t.id);return lZ(e,n,eZ(r,VX(t,n),i))}function PYe(e,t,n,r){let i=cZ(e,t);return lZ(e,t,{...i,threadSubscriptionErrorById:{...i.threadSubscriptionErrorById,[n]:r}})}function FYe(e,t,n){let r=cZ(e,t);if(!(n in r.threadSubscriptionErrorById))return e;let{[n]:i,...a}=r.threadSubscriptionErrorById;return lZ(e,t,{...r,threadSubscriptionErrorById:a})}function uZ(e,t,n){switch(t.type){case`project.created`:{let r=BX({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,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=ZJe(n,t.payload);return{...e,projectById:{...e.projectById,[t.payload.projectId]:r}}}case`project.deleted`:return iZ(e,t.payload.projectId);case`thread.created`:{let r=kX(e,t.payload.threadId);return eZ(e,VX({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 rZ(e,t.payload.threadId);case`thread.archived`:return jX(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:t.payload.archivedAt});case`thread.unarchived`:return jX(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:null});case`thread.settled`:return jX(e,t.payload.threadId,t.payload.updatedAt,{settledAt:t.payload.settledAt,settledOverride:t.payload.settledOverride});case`thread.unsettled`:return jX(e,t.payload.threadId,t.payload.updatedAt,{settledAt:null,settledOverride:`active`});case`thread.meta-updated`:return sZ(e,t.payload.threadId,e=>({...e,...t.payload.title===void 0?{}:{title:t.payload.title},...t.payload.modelSelection===void 0?{}:{modelSelection:wX(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 sZ(e,t.payload.threadId,e=>({...e,runtimeMode:t.payload.runtimeMode,updatedAt:t.payload.updatedAt}));case`thread.interaction-mode-set`:return sZ(e,t.payload.threadId,e=>({...e,interactionMode:t.payload.interactionMode,updatedAt:t.payload.updatedAt}));case`thread.turn-start-requested`:return sZ(e,t.payload.threadId,e=>({...e,...t.payload.modelSelection===void 0?{}:{modelSelection:wX(t.payload.modelSelection)},runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,pendingSourceProposedPlan:t.payload.sourceProposedPlan,latestTurn:oZ({previous:e.latestTurn,turnId:_n.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:sZ(e,t.payload.threadId,e=>{let n=e.latestTurn;return n===null||n.turnId!==t.payload.turnId?e:{...e,latestTurn:oZ({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 sZ(e,t.payload.threadId,e=>{let n=LX(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?CYe(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)?oZ({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 sZ(e,t.payload.threadId,e=>({...e,session:IX(t.payload.session),error:AK(t.payload.session.lastError),latestTurn:t.payload.session.status===`running`&&t.payload.session.activeTurnId!==null?oZ({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 sZ(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 sZ(e,t.payload.threadId,e=>{let n=RX(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 sZ(e,t.payload.threadId,e=>{let n=zX({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?oZ({previous:e.latestTurn,turnId:t.payload.turnId,state:aZ(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 sZ(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=wYe(e.messages,r,t.payload.turnCount).slice(-2e3),a=EYe(e.proposedPlans,r).slice(-200),o=TYe(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:aZ(s.status??`ready`),requestedAt:s.completedAt,startedAt:s.completedAt,completedAt:s.completedAt,assistantMessageId:s.assistantMessageId??null},updatedAt:t.occurredAt}});case`thread.activity-appended`:return sZ(e,t.payload.threadId,e=>{let n=[...e.activities.filter(e=>e.id!==t.payload.activity.id),{...t.payload.activity}].toSorted(SYe).slice(-500);return{...e,activities:n,updatedAt:t.occurredAt}});case`thread.rate-limit-set`:return sZ(e,t.payload.threadId,e=>({...e,rateLimitStatus:dYe(e.rateLimitStatus??[],t.payload),updatedAt:t.occurredAt}));case`thread.worker-spawned`:return sZ(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 IYe(e,t,n){switch(t.kind){case`project-upserted`:{let r=BX(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 iZ(e,t.projectId);case`thread-upserted`:return tZ(e,HX(t.thread,n));case`thread-removed`:return rZ(e,t.threadId)}}function LYe(e,t,n){if(t.length===0)return e;let r=cZ(e,n);return lZ(e,n,t.reduce((e,t)=>uZ(e,t,n),r))}function dZ(e){return Object.entries(e.environmentStateById)}function fZ(e,t){return t?cZ(e,t):MX}function RYe(e,t){return QX(fZ(e,t))}function pZ(e){return dZ(e).flatMap(([,e])=>bYe(e))}function mZ(e){return dZ(e).flatMap(([,e])=>QX(e))}function zYe(e){return dZ(e).flatMap(([,e])=>hZ(e).flatMap(t=>{let n=e.threadShellById[t];return n?[n]:[]}))}function hZ(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 gZ(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 BYe(e){return dZ(e).flatMap(([e,t])=>hZ(t).flatMap(n=>{let r=gZ(e,t,n);return r?[r]:[]}))}function _Z(e,t){if(!t)return[];let n=fZ(e,t.environmentId),r=n.threadIdsByProjectId[t.projectId]??NX;return(r.length>0?r:hZ(n)).flatMap(e=>{let r=gZ(t.environmentId,n,e);return!r||r.projectId!==t.projectId?[]:[r]})}function VYe(e,t){return t.length===0?[]:t.length===1?_Z(e,t[0]):t.flatMap(t=>_Z(e,t))}function HYe(e){return e.activeEnvironmentId===null?Object.values(e.environmentStateById).some(e=>e.bootstrapComplete):fZ(e,e.activeEnvironmentId).bootstrapComplete}function UYe(e,t){return t?fZ(e,t.environmentId).projectById[t.projectId]:void 0}function vZ(e,t){return t?kX(fZ(e,t.environmentId),t.threadId):void 0}function WYe(e,t){return t?fZ(e,t.environmentId).threadShellById[t.threadId]!==void 0:!1}function yZ(e,t){return t?gZ(t.environmentId,fZ(e,t.environmentId),t.threadId)??void 0:void 0}function GYe(e,t,n){if(e.activeEnvironmentId===null)return e;let r=sZ(cZ(e,e.activeEnvironmentId),t,e=>e.error===n?e:{...e,error:n});return lZ(e,e.activeEnvironmentId,r)}function KYe(e,t,n){return lZ(e,n,uZ(cZ(e,n),t,n))}function qYe(e,t,n){return lZ(e,n,IYe(cZ(e,n),t,n))}function JYe(e,t){return e.activeEnvironmentId===t?e:{...e,activeEnvironmentId:t}}function YYe(e,t,n,r){let i=sZ(cZ(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 lZ(e,t.environmentId,i)}var bZ=Kt(e=>({...fYe,setActiveEnvironmentId:t=>e(e=>JYe(e,t)),syncServerShellSnapshot:(t,n)=>e(e=>MYe(e,t,n)),syncServerThreadDetail:(t,n)=>e(e=>NYe(e,t,n)),setThreadSubscriptionError:(t,n,r)=>e(e=>PYe(e,t,n,r)),clearThreadSubscriptionError:(t,n)=>e(e=>FYe(e,t,n)),applyOrchestrationEvent:(t,n)=>e(e=>KYe(e,t,n)),applyOrchestrationEvents:(t,n)=>e(e=>LYe(e,t,n)),applyShellEvent:(t,n)=>e(e=>qYe(e,t,n)),setError:(t,n)=>e(e=>GYe(e,t,n)),setThreadBranch:(t,n,r)=>e(e=>YYe(e,t,n,r))})),xZ=`Thread not found or you no longer have access.`;function XYe(e){if(e==null)return xZ;let t=CX(ite(e)?Fe(e):e,xZ);return/\bnot found\b/i.test(t)?xZ:t}function ZYe(e,t,n){bZ.getState().setThreadSubscriptionError(e,t,XYe(n))}function QYe(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 $Ye(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 SZ={all:[`projects`],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},CZ={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function eXe(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function tXe(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:eXe(e.cursors)}}}var wZ={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,tXe(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]},nXe=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function rXe(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 iXe(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 TZ(e){let t=rXe(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 nXe(await iXe(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function EZ(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function aXe(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function oXe(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function DZ(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 oXe({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}function sXe(e,t){if(t){Nne(t,e);return}Pne(e)}function cXe(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(`
1014
- `)}}function lXe(e,t){let n=cXe(e);if(n.eventName!==`phase`||!n.data)return!1;try{let e=JSON.parse(n.data);return sXe(e,t),e.phase===`app-ready`||e.phase===`error`}catch{return!1}}async function uXe(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 iJ(e){let t=0;for(let n of e)n===``&&(t+=1);return t}function aJ(e,t){let n=t-iJ(e);return n<=0?e:`${``.repeat(n)}${e}`}function TKe(e){return e===void 0||e===` `||e===`
1013
+ `||e===` `||e===`\r`}function EKe(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${TKe(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:iJ(e.slice(0,n))}}function DKe(e){return e.replaceAll(``,``)}function OKe(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 oJ(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:oJ(()=>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},lJ=e=>Symbol.iterator in e,uJ=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},kKe=(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 AKe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:lJ(e)&&lJ(t)?uJ(e)&&uJ(t)?dJ(e,t):kKe(e,t):dJ({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function fJ(e){let t=F.useRef(void 0);return n=>{let r=e(n);return AKe(t.current,r)?t.current:t.current=r}}function pJ(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var jKe={enabled:!0,leading:!0,trailing:!0,wait:0},MKe=class{#e;constructor(e,t){this.fn=e,this.store=new wte(pJ()),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`}}),xte(`Throttler`,this)},this.#n=()=>!!Jt(this.options.enabled,this),this.#r=()=>Jt(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(pJ())},this.key=t.key,this.options={...jKe,...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 mJ(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function NKe(e){return e!=null&&typeof e.getItem==`function`&&typeof e.setItem==`function`&&typeof e.removeItem==`function`}function hJ(e){return NKe(e)?e:mJ()}var gJ=mJ();function _J(){return globalThis.localStorage||globalThis.window?.localStorage}var vJ={getItem:e=>{try{let t=_J()?.getItem(e);if(t!==void 0)return t}catch{}return gJ.getItem(e)},setItem:(e,t)=>{try{let n=_J();if(n){n.setItem(e,t);return}}catch{}gJ.setItem(e,t)},removeItem:e=>{try{let t=_J();if(t){t.removeItem(e);return}}catch{}gJ.removeItem(e)}};function yJ(e){let t=vJ.getItem(e);return typeof t==`string`?t:null}function bJ(e,t){vJ.setItem(e,t)}function PKe(e){vJ.removeItem(e)}function FKe(e,t=300){let n=hJ(e),r=new Yt((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()}}}function xJ(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 SJ={providers:{codex:!0,claude:!1,cmmd:!0},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function CJ(e){if(e==null)return SJ;let t=e.providers,n=e.allowedWallets;return{providers:{...SJ.providers,...t},allowedWallets:Array.isArray(n)&&n.length>0?n:SJ.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:SJ.updatedAt}}function IKe(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var LKe={"org-disabled":`Your organisation has not enabled this provider.`,"policy-unavailable":`Forge could not load your organisation’s provider policy, so this provider is unavailable right now. Try again shortly.`,"unknown-provider":`Coming soon.`};function RKe(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 wJ(e,t){let n=IKe(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=RKe(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:CJ(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function TJ(e,t){return wJ(e,t).offered}function zKe(e,t){return EJ(e,t).offered}function EJ(e,t){return t===null?{offered:!0}:wJ(e,t)}function DJ(e,t){return CJ(t).allowedWallets.includes(e)}function OJ(e){return DJ(`personal`,e)}function BKe(e){return e===`claudeAgent`||e===`codex`}function VKe(e,t){return e!==`claudeAgent`||OJ(t)||TJ(`claudeAgent`,t)}function HKe(e){return e.isDebugDisclosureEnabled||BKe(e.provider)&&OJ(e.policy)?!1:!TJ(e.provider===`apex`?`apex`:e.provider,e.policy)}var UKe=new Set([`pending`,`claimed`,`activating`]);function WKe(e){let t=e.current.runtimeId===e.runtimeId?e.current:{runtimeId:e.runtimeId,dataUpdatedAt:0,consecutiveUnavailableResponses:0};return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{runtimeId:e.runtimeId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0}}function GKe(e){return!e.claudeOffered||!e.claudeConnected?!1:e.deliveryStatus===null?e.consecutiveUnavailableResponses>0&&e.consecutiveUnavailableResponses<3:UKe.has(e.deliveryStatus)}function kJ(e){return e.credentialMode===`runtime`?e.provider&&xJ(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`}:KKe({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function KKe(e){return!e.provider||!xJ(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:TJ(e.providerKind,e.policy)?AJ({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function qKe(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:TJ(e.providerKind,e.access.policy)?AJ({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 AJ(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:JKe({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:DJ(`workspace`,e.policy),stage:e.stage})}function JKe(e){return YKe(e.workspaceWalletAllowed)?{eligible:!0}:XKe(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:ZKe(e.providerKind,e.personalConnections)?QKe(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function YKe(e){return e&&!1}function XKe(e,t){return e===`codex`&&t?.codex===!0}function ZKe(e,t){return t?.[e]===!0}function QKe(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||$Ke(e.claudeRuntimeReadiness)}function $Ke(e){if(!eqe(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function eqe(e){return e?.connected===!0&&e.deliveryStatus===`applied`&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function jJ(e){return e.providers.filter(t=>kJ({provider:t,providerKind:t.provider,access:e.access,credentialMode:e.credentialMode}).eligible)}function tqe(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=DJ(`workspace`,e.policy);return t.cmmd?!0:DJ(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var nqe={providers:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},MJ=[`cmmd`,`forge-provider-access`],rqe=2e3,iqe=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),aqe=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`],NJ=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`}};function oqe(e,t){return!(t instanceof NJ)&&e<3}function sqe(e,t=null){return[...MJ,e,t]}async function cqe(e){e.queryClient.setQueriesData({queryKey:MJ},t=>lqe(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:MJ,refetchType:`all`})}function lqe(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 PJ(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=aq(),r=Oqe(await n.getOrgProviderPolicy());DJ(`workspace`,r);let[i,a,o,s]=await Promise.all([fqe(()=>n.getProviderAccounts()),IJ({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),IJ({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),_qe({enabled:r.providers.claude,runtimeId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=uqe(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 uqe(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function dqe(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 fqe(e){try{return pqe(await e())}catch{return{accounts:[]}}}function pqe(e){if(!LJ(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(mqe)}}function mqe(e){return LJ(e)?hqe(e.provider)&&gqe(e.providerAccountId)&&FJ(e.accountEmail)&&(e.accountDisplayName===void 0||FJ(e.accountDisplayName))&&FJ(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function hqe(e){return e===`codex`||e===`claudeAgent`}function gqe(e){return typeof e==`string`&&e.trim().length>0}function FJ(e){return typeof e==`string`||e===null}async function _qe(e){if(!e.enabled||e.runtimeId===null)return null;try{return bqe(await e.load(e.runtimeId),e.runtimeId)}catch(e){if(e instanceof vr&&(e.kind===`auth`||e.kind===`permission`))throw new NJ(e.kind);return null}}async function IJ(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return jqe(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function vqe(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function yqe(e){let t=(0,ul.c)(18),n=e.runtimeId??null,r;t[0]===n?r=t[1]:(r={runtimeId:n,dataUpdatedAt:0,consecutiveUnavailableResponses:0},t[0]=n,t[1]=r);let i=(0,F.useRef)(r),a;t[2]!==e.credentialMode||t[3]!==n?(a=sqe(e.credentialMode,n),t[2]=e.credentialMode,t[3]=n,t[4]=a):a=t[4];let o;t[5]===n?o=t[6]:(o=()=>PJ(`cmmd-cloud`,n),t[5]=n,t[6]=o);let s=e.enabled&&e.credentialMode===`cmmd-cloud`,c;t[7]===n?c=t[8]:(c=e=>{if(e.state.error instanceof NJ)return!1;let t=vqe(e.state.data);return i.current=WKe({current:i.current,runtimeId:n,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:n!==null&&t.readinessUnavailable}),n!==null&&GKe({claudeOffered:t.claudeOffered,claudeConnected:t.claudeConnected,deliveryStatus:t.deliveryStatus,consecutiveUnavailableResponses:i.current.consecutiveUnavailableResponses})?rqe:!1},t[7]=n,t[8]=c);let l;t[9]!==a||t[10]!==o||t[11]!==s||t[12]!==c?(l={queryKey:a,queryFn:o,enabled:s,retry:oqe,staleTime:3e4,refetchInterval:c},t[9]=a,t[10]=o,t[11]=s,t[12]=c,t[13]=l):l=t[13];let u=Ni(l);if(!e.enabled){let e;return t[14]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[14]=e):e=t[14],e}if(e.credentialMode===`runtime`){let e;return t[15]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[15]=e):e=t[15],e}if(u.isPending){let e;return t[16]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[16]=e):e=t[16],e}if(u.isError||!u.data){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[17]=e):e=t[17],e}return u.data}function bqe(e,t){if(!LJ(e)||!Eqe(e)||!xqe(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function xqe(e,t){if(e.deliveryReceipt===null)return e.deliveryStatus!==`applied`||e.nativeExecutable!==!0;if(!LJ(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=LJ(n.identity)?n.identity:null;return r!==null&&Sqe(n,t)&&Tqe(r,e.generationId)}function Sqe(e,t){return Cqe(e,t)&&wqe(e)}function Cqe(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 wqe(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function Tqe(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function Eqe(e){return typeof e.connected==`boolean`&&iqe.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&aqe.every(t=>Dqe(e[t]))}function Dqe(e){return e===null||typeof e==`string`}function Oqe(e){if(!LJ(e)||!LJ(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,allowedWallets:n,updatedAt:r}=e,i=Aqe(n,r);if(!kqe(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 kqe(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(Mqe)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function jqe(e,t){if(!LJ(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 Mqe(e){return e===`personal`||e===`workspace`}function LJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nqe(e){return e.status===`ready`?e.policy:nqe}var Pqe={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},RJ=[`codex`,`claudeAgent`,`apex`];function zJ(e){for(let t of RJ){let n=e.find(e=>e.provider===t);if(n&&VJ(n))return t}return e.find(VJ)?.provider??`codex`}function BJ(e,t){return e.find(e=>e.provider===t)?.models??[]}function VJ(e){return xJ(e)}function HJ(e,t){let n=t??zJ(e),r=e.find(e=>e.provider===n);if(r&&VJ(r)||n===`codex`)return n;for(let t of RJ){let n=e.find(e=>e.provider===t);if(n&&VJ(n))return t}return`codex`}function UJ(e,t,n,r){let i=jJ({providers:e,access:n,credentialMode:r});if(t&&i.some(e=>e.provider===t))return t;let a=zJ(i);return i.some(e=>e.provider===a)?a:null}function Fqe(e,t,n,r){return t==null?UJ(e,null,n,r):jJ({providers:e,access:n,credentialMode:r}).some(e=>e.provider===t)?t:null}function WJ(e,t,n){let r=Hq(t,n);return e.find(e=>e.slug===r)?.capabilities??Pqe}function GJ(e,t){let n=BJ(e,t);return n.find(e=>!e.isCustom)?.slug??n[0]?.slug??Un[t]}function KJ(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=WJ(r,n,t),s=a?.[t],c=Rq(o,s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null)??null,l=t===`codex`?eKe(o,s):tKe(o,s),u=o.promptInjectedEffortLevels.length>0&&Vq(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 qJ(e,t,n,r){return BJ(t,n).map(({slug:e,name:t,isCustom:n})=>({slug:e,name:t,isCustom:n}))}function JJ(e,t,n,r,i){let a=YJ(n,e,i),o=Uq(a,r,qJ(t,n,a,r))??GJ(n,a);return e&&Wq(o,e)?GJ(n,e):o}function YJ(e,t,n){return!t||!TJ(t,n)?HJ(e,`codex`):HJ(e,t)}function Iqe(e,t,n,r){return{codex:qJ(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:qJ(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:qJ(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:qJ(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:qJ(e,t,`apex`,n===`apex`?r:void 0),cursor:qJ(e,t,`cursor`,n===`cursor`?r:void 0),opencode:qJ(e,t,`opencode`,n===`opencode`?r:void 0)}}function Lqe(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:$n.codex},i=YJ(t,r.provider,n),a=JJ(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=KJ({provider:i,model:a,models:BJ(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function XJ(e){return e?.options?{[e.provider]:e.options}:null}function Rqe(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 zqe(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&&Wq(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=Hq(n??r,e.selectedProvider)??GJ(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=zqe({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?JJ(e.selectedProvider,e.settings,e.providers,s):i,l=Rqe(e.draft?.modelSelectionByProvider)??XJ(e.threadModelSelection)??XJ(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var ZJ=`forge:composer-drafts:v1`,QJ=5,Vqe=jn([`local`,`worktree`]),$J=Bte(wn),eY=FKe(typeof localStorage<`u`?localStorage:mJ(),300);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{eY.flush()});var tY=Vn({id:Gn,name:Gn,mimeType:Gn,sizeBytes:Mn,dataUrl:Gn}),nY=Vn({id:Gn,threadId:an,createdAt:Gn,terminalId:Gn,terminalLabel:Gn,lineStart:Mn,lineEnd:Mn}),Hqe=Vn({prompt:Gn,attachments:Hn(tY),terminalContexts:Hn(nY),startedAt:Gn}),Uqe=Vn({prompt:Gn,lastGeneratedPullRequestPrompt:zn(Gn),attachments:Hn(tY),terminalContexts:zn(Hn(nY)),modelSelectionByProvider:zn(Pn(Tn,zn(Sn))),activeProvider:zn(tr(Tn)),runtimeMode:zn(wn),interactionMode:zn(dn),stagedSubmission:zn(Hqe)});Vn({effort:zn(jn(Nn)),codexFastMode:zn(Jn),serviceTier:zn(Gn)}),Vn({provider:zn(Tn),model:zn(Gn),modelOptions:zn(tr(Xn))}),Vn({stickyProvider:zn(Tn),stickyModel:zn(Gn),stickyModelOptions:zn(tr(Xn))});var Wqe=Vn({threadId:an,environmentId:Gn,projectId:sn,logicalProjectKey:zn(Gn),createdAt:Gn,runtimeMode:wn,interactionMode:dn,branch:tr(Gn),worktreePath:tr(Gn),envMode:Vqe,promotedTo:zn(tr(Vn({environmentId:Gn,threadId:Gn}))),anchorKind:zn(Ite),anchorCmmdId:zn(tr(Gn)),linkedPullRequest:zn(tr(Dte))}),Gqe=Vn({draftsByThreadKey:Pn(Gn,Uqe),draftThreadsByThreadKey:Pn(Gn,Wqe),logicalProjectDraftThreadKeyByLogicalProjectKey:Pn(Gn,Gn),stickyModelSelectionByProvider:zn(Pn(Tn,zn(Sn))),stickyActiveProvider:zn(tr(Tn))}),Kqe=Vn({version:Mn,state:Gqe}),rY=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),iY=[],aY=[],oY=[],qqe=[];Object.freeze(iY),Object.freeze(aY),Object.freeze(oY);var sY=Object.freeze({}),Jqe=Object.freeze({activeProvider:null,modelSelectionByProvider:sY}),Yqe=Object.freeze({prompt:``,images:iY,nonPersistedImageIds:aY,persistedAttachments:oY,terminalContexts:qqe,modelSelectionByProvider:sY,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function cY(){return{prompt:``,images:[],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 uY(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function dY(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim();if(n.length===0||r.length===0)return null;let i=Math.max(1,Math.floor(t.lineStart)),a=Math.max(i,Math.floor(t.lineEnd));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:i,lineEnd:a,text:eJ(t.text)}}function fY(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=dY(e,a);if(!t)continue;let o=uY(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function pY(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===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 mY(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function hY(e){return Nn.some(t=>t===e)}function Xqe(e){return Ute.some(t=>t===e)}function gY(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=hY(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&hY(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=Xqe(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 _Y(e,t){let n=e&&typeof e==`object`?e:null,r=mY(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=Hq(i,r);if(!a)return null;let o=gY(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 vY(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 yY(e,t){return e?.options===void 0?gY(t):Zqe(gY(t),e.provider,e.options)}function Zqe(e,t,n){let{[t]:r,...i}=e??{},a=gY({[t]:n},t);return gY({...i,...a||{}})}function bY(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:Un[r],options:i})}return e&&(n[e.provider]=e),n}function xY(e){typeof URL>`u`||e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function SY(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.name,i=t.mimeType,a=t.sizeBytes,o=t.dataUrl;return typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`string`||n.length===0||o.length===0?null:{id:n,name:r,mimeType:i,sizeBytes:a,dataUrl:o}}function CY(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 Qqe(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function wY(e){return Ho(e)}function TY(e){return e.trim()}function EY(e){return typeof e==`string`?e.trim():Uo(e)}function DY(e,t){let n=Ko(e);return n?EY(n):t?.environmentId?EY(zo(t.environmentId,e)):e}function $qe(e){return Ko(e)}function OY(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?Gt.make(e):null}return t}function kY(e,t){let n=OY(e,t);if(!n)return null;if(typeof n!=`string`){let t=EY(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=EY(n);return r.length>0?r:null}function AY(e,t){let n=OY(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??null:n.threadId:null}function jY(e,t){let n=kY(e,t);return n?e.draftsByThreadKey[n]??null:null}function eJe(e,t){return Object.values(e).includes(t)}function MY(e,t){return{draftId:e,...t}}function tJe(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 NY(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function PY(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function nJe(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)&&FY(e.linkedPullRequest,t.linkedPullRequest)&&NY(e.promotedTo,t.promotedTo)}function FY(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 IY(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 LY(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=Go(e);if(!t)continue;let i=Ko(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=Ko(t),o=DY(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?zo(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?wY(Ro(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:$J(e.runtimeMode)?e.runtimeMode:Zq,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:Qq,branch:typeof d==`string`?d:null,worktreePath:p,envMode:Qqe(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=Go(e),o=Ko(a),s=DY(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:Zq,interactionMode:Qq,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function RY(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=$qe(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=SY(e);return t?[t]:[]}):[],l=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=CY(e);return t?[t]:[]}):[],u=$J(e.runtimeMode)?e.runtimeMode:null,d=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,f=rJe(e.stagedSubmission),p=aJ(o,l.length),m=a,h={},g=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)h=e.modelSelectionByProvider,g=mY(e.activeProvider);else{let e=gY(m.modelOptions,void 0,m)??null,t=_Y(m.modelSelection,{provider:m.provider,model:m.model,modelOptions:e??m.modelOptions,legacyCodex:m}),n=yY(t,e),r=vY(t,n);h=bY(r,n),g=r?.provider??null}let _=Object.keys(h).length>0||g!==null;if(o.length===0&&c.length===0&&l.length===0&&!_&&!u&&!d&&!f)continue;let v=Ko(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?DY(i,{environmentId:e}):i})():i:DY(i);r[v]={prompt:p,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{terminalContexts:l}:{},..._?{modelSelectionByProvider:h,activeProvider:g}:{},...u?{runtimeMode:u}:{},...d?{interactionMode:d}:{},...f?{stagedSubmission:f}:{}}}return r}function rJe(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.prompt!=`string`||typeof t.startedAt!=`string`)return null;let n=Array.isArray(t.attachments)?t.attachments.flatMap(e=>{let t=SY(e);return t?[t]:[]}):[],r=Array.isArray(t.terminalContexts)?t.terminalContexts.flatMap(e=>{let t=CY(e);return t?[t]:[]}):[];return{prompt:t.prompt,attachments:n,terminalContexts:r,startedAt:t.startedAt}}function iJe(e){if(!e||typeof e!=`object`)return rY;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=gY(t.stickyModelOptions)??{},o=_Y(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=yY(o,a),c=bY(vY(o,s),s),l=mY(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=LY(r,i);return{draftsByThreadKey:RY(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function aJe(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.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.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}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:{prompt:r.stagedSubmission.prompt,attachments:[...r.stagedSubmission.attachments],terminalContexts:r.stagedSubmission.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd})),startedAt:r.stagedSubmission.startedAt}}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function oJe(e){if(!e||typeof e!=`object`)return rY;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=LY(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=mY(t.stickyActiveProvider);else{let e=gY(t.stickyModelOptions)??{},n=_Y(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=yY(n,e);i=bY(vY(n,r),r),a=mY(t.stickyProvider)}return{draftsByThreadKey:RY(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function sJe(e){if(e.length===0)return[];try{let t=qq(ZJ,Kqe);return!t||t.version!==QJ?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function cJe(e,t,n){let r=new Set;try{eY.flush(),r=new Set(sJe(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 pY(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function lJe(e){let t=e.dataUrl.indexOf(`,`),n=t===-1?e.dataUrl:e.dataUrl.slice(0,t),r=t===-1?``:e.dataUrl.slice(t+1);if(r.length===0)return null;try{if(!n.includes(`;base64`)){let t=decodeURIComponent(r),i=n.startsWith(`data:`)&&n.includes(`;`)?n.slice(5,n.indexOf(`;`)):e.mimeType;return new File([t],e.name,{type:i||e.mimeType})}let t=atob(r),i=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return new File([i],e.name,{type:e.mimeType})}catch{return null}}function uJe(e){return e.flatMap(e=>{let t=lJe(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function dJe(e,t){return e.length>0?e:t?.prompt??``}function fJe(e,t){return e.length>0?e:t?.attachments??[]}function pJe(e,t){return e&&e.length>0?e:t?.terminalContexts??[]}function mJe(e){let t=e.stagedSubmission;return{prompt:dJe(e.prompt,t),attachments:fJe(e.attachments,t),terminalContexts:pJe(e.terminalContexts,t)}}function hJe(e){let t=e.modelSelectionByProvider??{},n=mY(e.activeProvider)??null,r=mJe(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:uJe(r.attachments),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],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,text:``})),modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:null}}function gJe(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??wY(Ro(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?zo(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var zY=Kt()(cJ((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>jY(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=TY(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||PY(i)?null:MY(Gt.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!PY(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return MY(Gt.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(Gt.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Uo(zo(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=TY(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=tJe(t,i?.threadId??n?.threadId??an.make(r),a,n,i);if(o===r&&nJe(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&&!eJe(c,o)&&!PY(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(wY(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=kY(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)&&FY(l.linkedPullRequest,t.linkedPullRequest)&&NY(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?IY(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=kY(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:IY(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=kY(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??zo(t.environmentId,t.threadId);return NY(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=kY(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!PY(t))return e;let n=EY(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return IY(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=kY(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)xY(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:IY(e,r)})},setStickyModelSelection:e=>{let t=_Y(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return Ye(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=kY(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]??cY(),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(Ye(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return pY(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={prompt:t.prompt,attachments:[...t.persistedAttachments],terminalContexts:[...t.terminalContexts],startedAt:r},a={...e.draftsByThreadKey};return a[i]={...t,stagedSubmission:n},{draftsByThreadKey:a}})},clearStagedComposerSubmission:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r)=>{let i=kY(t(),e),a=AY(t(),e);if(!i||!a)return;let o=fY(a,r);n(e=>{let t=e.draftsByThreadKey[i]??cY(),n={...t,prompt:aJ(t.prompt,o.length),terminalContexts:o},r={...e.draftsByThreadKey};return pY(n)?delete r[i]:r[i]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=_Y(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY(),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(Ye(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return pY(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=gY(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY(),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??Un[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(Ye(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return pY(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=kY(t(),e)??``;if(o.length===0)return;let s=mY(r);if(s===null)return;let c=gY({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??cY(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??Un[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:Un[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(Ye(t.modelSelectionByProvider,n)&&Ye(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return pY(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=kY(t(),e)??``;if(i.length===0)return;let a=$J(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??cY();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return pY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=kY(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??cY();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return pY(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=kY(t(),e),i=AY(t(),e);!r||!i||t().addImages(typeof e==`string`?Gt.make(r):e,[n])},addImages:(e,r)=>{let i=kY(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??cY(),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)||xY(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]}}}})},removeImage:(e,r)=>{let i=kY(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&&xY(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 pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=kY(t(),e),s=AY(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??cY(),n=dY(s,i);if(!n)return e;let l=uY(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>uY(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=kY(t(),e),i=AY(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?Gt.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=kY(t(),e),a=AY(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??cY(),n=fY(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:aJ(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=kY(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 pY(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=kY(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 pY(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=kY(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 pY(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{cJe(i,r,n)})},clearComposerContent:e=>{let r=kY(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let{lastGeneratedPullRequestPrompt:n,...i}=t,a={...i,prompt:``,images:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[]},o={...e.draftsByThreadKey};return pY(a)?delete o[r]:o[r]=a,{draftsByThreadKey:o}})}}},{name:ZJ,version:QJ,storage:oJ(()=>eY),migrate:iJe,partialize:aJe,merge:(e,t)=>{let n=oJe(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,hJe(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,gJe(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function _Je(e){let t=(0,ul.c)(2),n;return t[0]===e?n=t[1]:(n=t=>jY(t,e)??Yqe,t[0]=e,t[1]=n),zY(n)}function vJe(e){let t=(0,ul.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=jY(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:Jqe},t[0]=e,t[1]=n),zY(fJ(n))}function yJe(e){let t=(0,ul.c)(10),n;t[0]!==e.draftId||t[1]!==e.threadRef?(n=e.threadRef??e.draftId??Gt.make(``),t[0]=e.draftId,t[1]=e.threadRef,t[2]=n):n=t[2];let r=vJe(n),i,a;return t[3]!==r||t[4]!==e.projectModelSelection||t[5]!==e.providers||t[6]!==e.selectedProvider||t[7]!==e.settings||t[8]!==e.threadModelSelection?(a=Bqe({draft:r,providers:e.providers,selectedProvider:e.selectedProvider,threadModelSelection:e.threadModelSelection,projectModelSelection:e.projectModelSelection,settings:e.settings}),t[3]=r,t[4]=e.projectModelSelection,t[5]=e.providers,t[6]=e.selectedProvider,t[7]=e.settings,t[8]=e.threadModelSelection,t[9]=a):a=t[9],i=a,i}function BY(e){let t=zY.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(Gt.make(n),e)}function bJe(e){for(let t of e)BY(t)}function xJe(e){let t=zY.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(Gt.make(n))}function SJe(e){return{environmentId:e.environmentId,threadId:e.threadId}}function CJe(e){return{draftId:e}}function wJe(e){return!e.environmentId||!e.threadId?null:zo(e.environmentId,e.threadId)}function TJe(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:zo(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}var EJe=F.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return bte(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function VY(e){let t=(0,ul.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=Qt(`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,Fr.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}var HY=`cmmd-runtime:`;function DJe(e){return`${HY}${e}`}function UY(e){return WY(e)!==null}function WY(e){let t=String(e);if(!t.startsWith(`cmmd-runtime:`))return null;let n=t.slice(13);return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(n)?n:null}var GY=`forge:client-settings:v1`,OJe=`forge:saved-environment-registry:v1`,kJe=Vn({environmentId:nn,label:Gn,httpBaseUrl:Gn,wsBaseUrl:Gn,createdAt:Gn,lastConnectedAt:tr(Gn),cmmdOrganizationId:zn(Gn),cmmdProjectId:zn(Gn),runtimeId:zn(Gn),runtimeTicketExpiresAt:zn(Gn),lastAuthenticatedPullRequestCapability:zn(Jn),bearerToken:zn(Gn)}),KY=Vn({version:zn(Mn),records:zn(Hn(kJe))});function qY(){return typeof window<`u`}var AJe={uiFontSize:14,codeFontSize:15},jJe=[[`uiFontSize`,11,20],[`codeFontSize`,11,20]];function MJe(e){return e.defaultThreadRuntime===`desktop-cloud-bridge`?{...e,defaultThreadRuntime:`cloud`}:null}function NJe(e){if(typeof e.fontDefaultsVersion==`number`)return null;let t=Object.entries(AJe).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 PJe(e){let t=jJe.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 JY(e){if(!e||typeof e!=`object`)return e;let t=e,n=!1;for(let e of[MJe,NJe,PJe]){let r=e(t);r!==null&&(t=r,n=!0)}return n?t:e}function FJe(){if(!qY())return null;try{let e=window.localStorage.getItem(GY);return e?ir(In)(JY(JSON.parse(e))):null}catch{return null}}function IJe(e){qY()&&Jq(GY,e,In)}function YY(){if(!qY())return{};try{return qq(`forge:saved-environment-registry:v1`,KY)??{}}catch{return{}}}function XY(e){qY()&&Jq(OJe,e,KY)}function ZY(){return YY().records??[]}function LJe(e){XY({version:1,records:e})}function RJe(){return ZY().map(e=>Fn(e))}function zJe(e){let t=new Map(ZY().map(e=>[e.environmentId,e]));LJe(e.map(e=>{let n=UY(e.environmentId)?void 0:t.get(e.environmentId)?.bearerToken;return n?{...Fn(e),bearerToken:n}:Fn(e)}))}function BJe(e){return ZY().find(t=>t.environmentId===e)?.bearerToken??null}function VJe(e,t){let n=YY(),r=n.records??[],i=!1;return XY({version:n.version??1,records:r.map(n=>n.environmentId===e?(i=!0,Object.assign(Fn(n),{bearerToken:t})):n)}),i}function HJe(e){let t=YY();XY({version:t.version??1,records:(t.records??[]).map(t=>t.environmentId===e?Fn(t):t)})}var UJe=ir(In);function WJe(){return typeof window>`u`?void 0:window.desktopBridge}function QY(e){let t=WJe(),n=t?.[e];return typeof n==`function`?n.bind(t):null}async function $Y(){let e=QY(`getClientSettings`);if(e){let t=await e();return t?UJe(t):null}return FJe()}async function eX(e){let t=QY(`setClientSettings`);if(t)return t(e);IJe(e)}async function tX(){let e=QY(`getSavedEnvironmentRegistry`);return e?e():RJe()}async function nX(e){let t=QY(`setSavedEnvironmentRegistry`);if(t)return t(e);zJe(e)}async function rX(e){let t=QY(`getSavedEnvironmentSecret`);return t?t(e):BJe(e)}async function iX(e,t){let n=QY(`setSavedEnvironmentSecret`);return n?n(e,t):VJe(e,t)}async function aX(e){let t=QY(`removeSavedEnvironmentSecret`);if(t)return t(e);HJe(e)}var oX=!1,sX=null;function cX(e){return Object.values(e)}function lX(e){return e.map(e=>Fn(e))}function uX(e){try{nX(lX(cX(e))).catch(e=>{console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)})}catch(e){console.error(`[SAVED_ENVIRONMENTS] persist failed`,e)}}function GJe(e){let t=dX.getState().byId,n=Object.fromEntries(e.map(e=>[e.environmentId,e]));dX.setState({byId:{...n,...t}})}async function KJe(){if(oX)return;if(sX)return sX;let e=(async()=>{try{GJe(await tX())}catch(e){console.error(`[SAVED_ENVIRONMENTS] hydrate failed`,e)}finally{oX=!0,dX.setState({hydrated:!0})}})().finally(()=>{sX===e&&(sX=null)});return sX=e,sX}var dX=Kt()(e=>({byId:{},hydrated:oX,upsert:t=>e(e=>{let n={...e.byId,[t.environmentId]:t};return uX(n),{byId:n}}),remove:t=>e(e=>{let{[t]:n,...r}=e.byId;return uX(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 uX(i),{byId:i}}),reset:()=>{uX({}),e({byId:{}})}}));function fX(){return oX}function pX(){return fX()?Promise.resolve():KJe()}function mX(){return Object.values(dX.getState().byId).toSorted((e,t)=>e.label.localeCompare(t.label))}function qJe(){return mX().filter(e=>e.lastAuthenticatedPullRequestCapability===!0)}function hX(e){return dX.getState().byId[e]??null}function JJe(e){let t=Iq();return t?.environmentId===e?Kie(t):hX(e)?.httpBaseUrl??null}function gX(e){let t=JJe(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()}async function _X(e){await nX(lX(cX({...dX.getState().byId,[e.environmentId]:e})))}async function vX(e){return rX(e)}async function YJe(e,t){return iX(e,t)}async function yX(e){await aX(e)}var XJe=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null});function bX(){return{...XJe}}var xX=Kt()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:bX()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??bX(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})})),ZJe=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function SX(e){let t=e?.trim();return t&&t.length>0?t:null}function QJe(e){return SX(e)??`Project`}function $Je(e,t=`safe`){let n=SX(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function CX(e,t=`Something went wrong. Try again.`){let n=OK(e instanceof Error?e.message:typeof e==`string`?e:String(e),{fallback:t});return!n||ZJe.some(e=>e.test(n))?t:n}function wX(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?TX(e.defaultModelSelection):null,createdAt:e.createdAt,updatedAt:e.updatedAt,scripts:EX(e.scripts)}}function TX(e){return{...e,model:Gq(e.provider,e.model)}}function EX(e){return e.map(e=>({...e}))}function eYe(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?TX(t.defaultModelSelection):null},...t.scripts===void 0?{}:{scripts:EX(t.scripts)},updatedAt:t.updatedAt}}var tYe=[],nYe=[],rYe=[],iYe=[],aYe={},oYe={},sYe={},cYe={},lYe=[],DX=new WeakMap,OX=new WeakMap;function kX(e,t,n){if(!e||e.length===0||!t)return n;let r=DX.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||DX.set(e,o),a}function uYe(e,t){return kX(e.messageIdsByThreadId[t],e.messageByThreadId[t]??aYe,tYe)}function dYe(e,t){return kX(e.activityIdsByThreadId[t],e.activityByThreadId[t]??oYe,nYe)}function fYe(e,t){return kX(e.proposedPlanIdsByThreadId[t],e.proposedPlanByThreadId[t]??sYe,rYe)}function pYe(e,t){return kX(e.turnDiffIdsByThreadId[t],e.turnDiffSummaryByThreadId[t]??cYe,iYe)}function AX(e,t){let n=e.threadShellById[t];if(!n)return;let r=e.threadSessionById[t]??null,i=e.threadTurnStateById[t],a=e.threadRateLimitStatusById[t]??lYe,o=uYe(e,t),s=dYe(e,t),c=fYe(e,t),l=pYe(e,t),u=OX.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 OX.set(n,{session:r,turnState:i,rateLimitStatus:a,messages:o,activities:s,proposedPlans:c,turnDiffSummaries:l,thread:d}),d}function jX(e){return{settledAt:e.settledAt??null,settledOverride:e.settledOverride??null}}function MX(e,t,n,r){let i=sZ(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 mYe(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]}var NX={projectIds:[],projectById:{},threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:{},messageIdsByThreadId:{},messageByThreadId:{},activityIdsByThreadId:{},activityByThreadId:{},proposedPlanIdsByThreadId:{},proposedPlanByThreadId:{},turnDiffIdsByThreadId:{},turnDiffSummaryByThreadId:{},sidebarThreadSummaryById:{},threadSubscriptionErrorById:{},bootstrapComplete:!1},hYe={activeEnvironmentId:null,environmentStateById:{}},PX=[],FX=[];function IX(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function LX(e){let t=AK(e.lastError);return{provider:jYe(e.providerName),status:AYe(e.status),orchestrationStatus:e.status,activeTurnId:e.activeTurnId??void 0,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{lastError:t}:{}}}function RX(e,t){let n=t.attachments?.map(t=>({type:`image`,id:t.id,name:t.name,mimeType:t.mimeType,sizeBytes:t.sizeBytes,previewUrl:gX({environmentId:e,pathname:MYe(t.id)})}));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 zX(e){return{id:e.id,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId,createdAt:e.createdAt,updatedAt:e.updatedAt}}function BX(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 VX(e,t){return{id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:TX(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,session:e.session?LX(e.session):null,messages:e.messages.map(e=>RX(t,e)),proposedPlans:e.proposedPlans.map(zX),error:AK(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...jX(e),updatedAt:e.updatedAt,latestTurn:e.latestTurn,pendingSourceProposedPlan:e.latestTurn?.sourceProposedPlan,branch:e.branch,worktreePath:e.worktreePath,turnDiffSummaries:e.checkpoints.map(BX),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 HX(e,t){let n={id:e.id,environmentId:t,codexThreadId:null,projectId:e.projectId,title:e.title,modelSelection:TX(e.modelSelection),runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,error:AK(e.session?.lastError),createdAt:e.createdAt,archivedAt:e.archivedAt,...jX(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?LX(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,...jX(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 gYe(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 _Ye(e){return{latestTurn:e.latestTurn,...e.pendingSourceProposedPlan?{pendingSourceProposedPlan:e.pendingSourceProposedPlan}:{}}}function UX(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.threadId===t.threadId&&e.planId===t.planId}function WX(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&&UX(e.sourceProposedPlan,t.sourceProposedPlan)}function GX(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 KX(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 qX(e,t){return e!==void 0&&e.id===t.id&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.title===t.title&&JX(e.titleRegeneration,t.titleRegeneration)&&e.interactionMode===t.interactionMode&&GX(e.session,t.session)&&e.createdAt===t.createdAt&&e.archivedAt===t.archivedAt&&e.settledAt===t.settledAt&&e.settledOverride===t.settledOverride&&e.updatedAt===t.updatedAt&&WX(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&&KX(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status}function JX(e,t){return e===t?!0:e==null||t==null?!1:e.requestId===t.requestId&&e.startedAt===t.startedAt}function YX(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&&KX(e.linkedPullRequest,t.linkedPullRequest)&&e.kind===t.kind&&e.parentThreadId===t.parentThreadId&&e.status===t.status&&e.goal===t.goal&&JX(e.titleRegeneration,t.titleRegeneration)}function XX(e,t){return e!==void 0&&WX(e.latestTurn,t.latestTurn)&&UX(e.pendingSourceProposedPlan,t.pendingSourceProposedPlan)}function vYe(e,t){return e.includes(t)?[...e]:[...e,t]}function ZX(e,t){return e.filter(e=>e!==t)}function yYe(e){return{ids:e.messages.map(e=>e.id),byId:Object.fromEntries(e.messages.map(e=>[e.id,e]))}}function bYe(e){return{ids:e.activities.map(e=>e.id),byId:Object.fromEntries(e.activities.map(e=>[e.id,e]))}}function xYe(e){return{ids:e.proposedPlans.map(e=>e.id),byId:Object.fromEntries(e.proposedPlans.map(e=>[e.id,e]))}}function SYe(e){return{ids:e.turnDiffSummaries.map(e=>e.turnId),byId:Object.fromEntries(e.turnDiffSummaries.map(e=>[e.turnId,e]))}}function CYe(e){return e.projectIds.flatMap(t=>{let n=e.projectById[t];return n?[n]:[]})}function QX(e){return e.threadIds.flatMap(t=>{let n=AX(e,t);return n?[n]:[]})}function $X(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]??PX,i=ZX(n,t);if(i.length===0){let{[r]:t,...n}=e;e=n}else IX(n,i)||(e={...e,[r]:i})}let a=e[n]??PX,o=vYe(a,t);IX(a,o)||(e={...e,[n]:o}),e!==i.threadIdsByProjectId&&(i={...i,threadIdsByProjectId:e})}return i}function eZ(e,t,n){let r=gYe(t),i=_Ye(t),a=e.threadShellById[t.id],o=e.threadTurnStateById[t.id],s=$X(e,t.id,t.projectId,n?.projectId);YX(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};qX(c,e)||(s={...s,sidebarThreadSummaryById:{...s.sidebarThreadSummaryById,[t.id]:e}})}if(GX(n?.session??null,t.session)||(s={...s,threadSessionById:{...s.threadSessionById,[t.id]:t.session}}),(n?.rateLimitStatus??FX)!==(t.rateLimitStatus??FX)&&(s={...s,threadRateLimitStatusById:{...s.threadRateLimitStatusById,[t.id]:t.rateLimitStatus??FX}}),XX(o,i)||(s={...s,threadTurnStateById:{...s.threadTurnStateById,[t.id]:i}}),n?.messages!==t.messages){let e=yYe(t);s={...s,messageIdsByThreadId:{...s.messageIdsByThreadId,[t.id]:e.ids},messageByThreadId:{...s.messageByThreadId,[t.id]:e.byId}}}if(n?.activities!==t.activities){let e=bYe(t);s={...s,activityIdsByThreadId:{...s.activityIdsByThreadId,[t.id]:e.ids},activityByThreadId:{...s.activityByThreadId,[t.id]:e.byId}}}if(n?.proposedPlans!==t.proposedPlans){let e=xYe(t);s={...s,proposedPlanIdsByThreadId:{...s.proposedPlanIdsByThreadId,[t.id]:e.ids},proposedPlanByThreadId:{...s.proposedPlanByThreadId,[t.id]:e.byId}}}if(n?.turnDiffSummaries!==t.turnDiffSummaries){let e=SYe(t);s={...s,turnDiffIdsByThreadId:{...s.turnDiffIdsByThreadId,[t.id]:e.ids},turnDiffSummaryByThreadId:{...s.turnDiffSummaryByThreadId,[t.id]:e.byId}}}return s}function tZ(e,t){let n=e.threadShellById[t.shell.id],r=$X(e,t.shell.id,t.shell.projectId,n?.projectId);return YX(n,t.shell)||(r={...r,threadShellById:{...r.threadShellById,[t.shell.id]:t.shell}}),GX(e.threadSessionById[t.shell.id]??null,t.session)||(r={...r,threadSessionById:{...r.threadSessionById,[t.shell.id]:t.session}}),XX(e.threadTurnStateById[t.shell.id],t.turnState)||(r={...r,threadTurnStateById:{...r.threadTurnStateById,[t.shell.id]:t.turnState}}),qX(e.sidebarThreadSummaryById[t.shell.id],t.summary)||(r={...r,sidebarThreadSummaryById:{...r.sidebarThreadSummaryById,[t.shell.id]:t.summary}}),r}function nZ(e,t){return Object.fromEntries(Object.entries(e).flatMap(([e,n])=>t.has(e)?[[e,n]]:[]))}function rZ(e,t){let n=e.threadShellById[t],r=e.sidebarThreadSummaryById[t],i=n?.projectId??r?.projectId;if(!i)return e;let a=ZX(e.threadIds,t),o=ZX(e.threadIdsByProjectId[i]??PX,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]:O,...ee}=e.turnDiffSummaryByThreadId,{[t]:te,...k}=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:ee,sidebarThreadSummaryById:k}}function wYe(e,t){let n=new Set(e.threadIdsByProjectId[t]??PX);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 iZ(e,t){let n=wYe(e,t);if(!e.projectById[t]&&n.length===0&&!e.projectIds.includes(t))return e;let r=e;for(let e of n)r=rZ(r,e);let{[t]:i,...a}=r.projectById;return{...r,projectById:a,projectIds:ZX(r.projectIds,t)}}function aZ(e){return e===`error`?`error`:e===`missing`?`interrupted`:`completed`}function TYe(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 oZ(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 EYe(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 DYe(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 OYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function kYe(e,t){return e.filter(e=>e.turnId===null||t.has(e.turnId))}function AYe(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 jYe(e){return e===`codex`||e===`claudeAgent`||e===`ollama`||e===`cmmd`||e===`apex`?e:`codex`}function MYe(e){return`/attachments/${encodeURIComponent(e)}`}function sZ(e,t,n){let r=AX(e,t);if(!r)return e;let i=n(r);return i===r?e:eZ(e,i,r)}function NYe(e){return{projectIds:e.map(e=>e.id),projectById:Object.fromEntries(e.map(e=>[e.id,e]))}}function cZ(e,t){return e.environmentStateById[t]??NX}function lZ(e,t,n){let r=e.environmentStateById[t]===n?e.environmentStateById:{...e.environmentStateById,[t]:n};return r===e.environmentStateById?e:{...e,environmentStateById:r}}function PYe(e,t,n){let r=t.projects.map(e=>wX(e,n)),i=new Set(t.threads.map(e=>e.id)),a={...e,...NYe(r),threadIds:[],threadIdsByProjectId:{},threadShellById:{},threadSessionById:{},threadTurnStateById:{},threadRateLimitStatusById:nZ(e.threadRateLimitStatusById,i),sidebarThreadSummaryById:{},messageIdsByThreadId:nZ(e.messageIdsByThreadId,i),messageByThreadId:nZ(e.messageByThreadId,i),activityIdsByThreadId:nZ(e.activityIdsByThreadId,i),activityByThreadId:nZ(e.activityByThreadId,i),proposedPlanIdsByThreadId:nZ(e.proposedPlanIdsByThreadId,i),proposedPlanByThreadId:nZ(e.proposedPlanByThreadId,i),turnDiffIdsByThreadId:nZ(e.turnDiffIdsByThreadId,i),turnDiffSummaryByThreadId:nZ(e.turnDiffSummaryByThreadId,i),bootstrapComplete:!0};for(let e of t.threads)a=tZ(a,HX(e,n));return a}function FYe(e,t,n){return lZ(e,n,PYe(cZ(e,n),t,n))}function IYe(e,t,n){let r=cZ(e,n),i=AX(r,t.id);return lZ(e,n,eZ(r,VX(t,n),i))}function LYe(e,t,n,r){let i=cZ(e,t);return lZ(e,t,{...i,threadSubscriptionErrorById:{...i.threadSubscriptionErrorById,[n]:r}})}function RYe(e,t,n){let r=cZ(e,t);if(!(n in r.threadSubscriptionErrorById))return e;let{[n]:i,...a}=r.threadSubscriptionErrorById;return lZ(e,t,{...r,threadSubscriptionErrorById:a})}function uZ(e,t,n){switch(t.type){case`project.created`:{let r=wX({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=eYe(n,t.payload);return{...e,projectById:{...e.projectById,[t.payload.projectId]:r}}}case`project.deleted`:return iZ(e,t.payload.projectId);case`thread.created`:{let r=AX(e,t.payload.threadId);return eZ(e,VX({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 rZ(e,t.payload.threadId);case`thread.archived`:return MX(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:t.payload.archivedAt});case`thread.unarchived`:return MX(e,t.payload.threadId,t.payload.updatedAt,{archivedAt:null});case`thread.settled`:return MX(e,t.payload.threadId,t.payload.updatedAt,{settledAt:t.payload.settledAt,settledOverride:t.payload.settledOverride});case`thread.unsettled`:return MX(e,t.payload.threadId,t.payload.updatedAt,{settledAt:null,settledOverride:`active`});case`thread.meta-updated`:return sZ(e,t.payload.threadId,e=>({...e,...t.payload.title===void 0?{}:{title:t.payload.title},...t.payload.modelSelection===void 0?{}:{modelSelection:TX(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 sZ(e,t.payload.threadId,e=>({...e,runtimeMode:t.payload.runtimeMode,updatedAt:t.payload.updatedAt}));case`thread.interaction-mode-set`:return sZ(e,t.payload.threadId,e=>({...e,interactionMode:t.payload.interactionMode,updatedAt:t.payload.updatedAt}));case`thread.turn-start-requested`:return sZ(e,t.payload.threadId,e=>({...e,...t.payload.modelSelection===void 0?{}:{modelSelection:TX(t.payload.modelSelection)},runtimeMode:t.payload.runtimeMode,interactionMode:t.payload.interactionMode,pendingSourceProposedPlan:t.payload.sourceProposedPlan,latestTurn:oZ({previous:e.latestTurn,turnId:_n.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:sZ(e,t.payload.threadId,e=>{let n=e.latestTurn;return n===null||n.turnId!==t.payload.turnId?e:{...e,latestTurn:oZ({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 sZ(e,t.payload.threadId,e=>{let n=RX(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?EYe(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)?oZ({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 sZ(e,t.payload.threadId,e=>({...e,session:LX(t.payload.session),error:AK(t.payload.session.lastError),latestTurn:t.payload.session.status===`running`&&t.payload.session.activeTurnId!==null?oZ({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 sZ(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 sZ(e,t.payload.threadId,e=>{let n=zX(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 sZ(e,t.payload.threadId,e=>{let n=BX({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?oZ({previous:e.latestTurn,turnId:t.payload.turnId,state:aZ(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 sZ(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=DYe(e.messages,r,t.payload.turnCount).slice(-2e3),a=kYe(e.proposedPlans,r).slice(-200),o=OYe(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:aZ(s.status??`ready`),requestedAt:s.completedAt,startedAt:s.completedAt,completedAt:s.completedAt,assistantMessageId:s.assistantMessageId??null},updatedAt:t.occurredAt}});case`thread.activity-appended`:return sZ(e,t.payload.threadId,e=>{let n=[...e.activities.filter(e=>e.id!==t.payload.activity.id),{...t.payload.activity}].toSorted(TYe).slice(-500);return{...e,activities:n,updatedAt:t.occurredAt}});case`thread.rate-limit-set`:return sZ(e,t.payload.threadId,e=>({...e,rateLimitStatus:mYe(e.rateLimitStatus??[],t.payload),updatedAt:t.occurredAt}));case`thread.worker-spawned`:return sZ(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 zYe(e,t,n){switch(t.kind){case`project-upserted`:{let r=wX(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 iZ(e,t.projectId);case`thread-upserted`:return tZ(e,HX(t.thread,n));case`thread-removed`:return rZ(e,t.threadId)}}function BYe(e,t,n){if(t.length===0)return e;let r=cZ(e,n);return lZ(e,n,t.reduce((e,t)=>uZ(e,t,n),r))}function dZ(e){return Object.entries(e.environmentStateById)}function fZ(e,t){return t?cZ(e,t):NX}function VYe(e,t){return QX(fZ(e,t))}function pZ(e){return dZ(e).flatMap(([,e])=>CYe(e))}function mZ(e){return dZ(e).flatMap(([,e])=>QX(e))}function HYe(e){return dZ(e).flatMap(([,e])=>hZ(e).flatMap(t=>{let n=e.threadShellById[t];return n?[n]:[]}))}function hZ(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 gZ(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 UYe(e){return dZ(e).flatMap(([e,t])=>hZ(t).flatMap(n=>{let r=gZ(e,t,n);return r?[r]:[]}))}function _Z(e,t){if(!t)return[];let n=fZ(e,t.environmentId),r=n.threadIdsByProjectId[t.projectId]??PX;return(r.length>0?r:hZ(n)).flatMap(e=>{let r=gZ(t.environmentId,n,e);return!r||r.projectId!==t.projectId?[]:[r]})}function WYe(e,t){return t.length===0?[]:t.length===1?_Z(e,t[0]):t.flatMap(t=>_Z(e,t))}function GYe(e){return e.activeEnvironmentId===null?Object.values(e.environmentStateById).some(e=>e.bootstrapComplete):fZ(e,e.activeEnvironmentId).bootstrapComplete}function KYe(e,t){return t?fZ(e,t.environmentId).projectById[t.projectId]:void 0}function vZ(e,t){return t?AX(fZ(e,t.environmentId),t.threadId):void 0}function qYe(e,t){return t?fZ(e,t.environmentId).threadShellById[t.threadId]!==void 0:!1}function yZ(e,t){return t?gZ(t.environmentId,fZ(e,t.environmentId),t.threadId)??void 0:void 0}function JYe(e,t,n){if(e.activeEnvironmentId===null)return e;let r=sZ(cZ(e,e.activeEnvironmentId),t,e=>e.error===n?e:{...e,error:n});return lZ(e,e.activeEnvironmentId,r)}function YYe(e,t,n){return lZ(e,n,uZ(cZ(e,n),t,n))}function XYe(e,t,n){return lZ(e,n,zYe(cZ(e,n),t,n))}function ZYe(e,t){return e.activeEnvironmentId===t?e:{...e,activeEnvironmentId:t}}function QYe(e,t,n,r){let i=sZ(cZ(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 lZ(e,t.environmentId,i)}var bZ=Kt(e=>({...hYe,setActiveEnvironmentId:t=>e(e=>ZYe(e,t)),syncServerShellSnapshot:(t,n)=>e(e=>FYe(e,t,n)),syncServerThreadDetail:(t,n)=>e(e=>IYe(e,t,n)),setThreadSubscriptionError:(t,n,r)=>e(e=>LYe(e,t,n,r)),clearThreadSubscriptionError:(t,n)=>e(e=>RYe(e,t,n)),applyOrchestrationEvent:(t,n)=>e(e=>YYe(e,t,n)),applyOrchestrationEvents:(t,n)=>e(e=>BYe(e,t,n)),applyShellEvent:(t,n)=>e(e=>XYe(e,t,n)),setError:(t,n)=>e(e=>JYe(e,t,n)),setThreadBranch:(t,n,r)=>e(e=>QYe(e,t,n,r))})),xZ=`Thread not found or you no longer have access.`;function $Ye(e){if(e==null)return xZ;let t=CX(ite(e)?Fe(e):e,xZ);return/\bnot found\b/i.test(t)?xZ:t}function eXe(e,t,n){bZ.getState().setThreadSubscriptionError(e,t,$Ye(n))}function tXe(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 nXe(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 SZ={all:[`projects`],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},CZ={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function rXe(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function iXe(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:rXe(e.cursors)}}}var wZ={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,iXe(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]},aXe=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function oXe(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 sXe(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 TZ(e){let t=oXe(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 aXe(await sXe(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function EZ(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function cXe(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function lXe(e){return TZ({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function DZ(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 lXe({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}function uXe(e,t){if(t){Nne(t,e);return}Pne(e)}function dXe(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(`
1014
+ `)}}function fXe(e,t){let n=dXe(e);if(n.eventName!==`phase`||!n.data)return!1;try{let e=JSON.parse(n.data);return uXe(e,t),e.phase===`app-ready`||e.phase===`error`}catch{return!1}}async function pXe(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(`
1015
1015
 
1016
- `);for(;o!==-1;){let e=a.slice(0,o);if(a=a.slice(o+2),lXe(e,t))return;o=a.indexOf(`
1016
+ `);for(;o!==-1;){let e=a.slice(0,o);if(a=a.slice(o+2),fXe(e,t))return;o=a.indexOf(`
1017
1017
 
1018
- `)}}}var dXe=(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 uXe(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},fXe=6e4;function pXe(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 mXe(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 OZ(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=mXe({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??fXe}),s=e.readiness?(e.readiness.openStream??dXe)({url:pXe(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-DsJoTBtH.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([2,1,3,4])).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 hXe(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var gXe=3e4,_Xe=1e4,vXe=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,kZ=/https?:\/\/[^\s"'`<>]+/gu,yXe=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),bXe=/(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 AZ(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=vXe.test(t)||MZ(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 xXe(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function jZ(e){try{let t=new URL(e);return xne(t.hostname)}catch{return!1}}function MZ(e){return Sne(e)}function NZ(e){try{let t=new URL(e);if(t.protocol!==`http:`||!jZ(t.toString())&&!MZ(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 SXe(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 CXe(e){return e.replace(yXe,``).replaceAll(/./gsu,e=>wXe(e)?``:e).replace(bXe,`$1$2`)}function wXe(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function PZ(e){let t=null,n=null,r=CXe(e);kZ.lastIndex=0;for(let e of r.matchAll(kZ)){let r=AZ(SXe(e[0]));!r||!NZ(r)||(t=r,jZ(r)&&(n=r))}return n??t}function TXe(e){let t=null;for(let n of e){let e=n.event,r=PZ(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function EXe(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var DXe=`forge:terminal-state:v1`,FZ=[],OXe=200,IZ=8;function kXe(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:KZ(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!Ko(e)&&typeof t?.url==`string`&&!!NZ(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function AXe(){return hJ(typeof window<`u`?window.localStorage:void 0)}function jXe(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[$q]}function MXe(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 LZ(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 zZ(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function NXe(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function PXe(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=NXe(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():LZ(e[0]??`default`);i.push({id:RZ(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:RZ(LZ(e),a),terminalIds:[e]});return i.length===0?[{id:LZ($q),terminalIds:[$q]}]:i}function BZ(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 FXe(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||!BZ(r.terminalIds,i.terminalIds))return!1}return!0}function VZ(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&BZ(e.terminalIds,t.terminalIds)&&BZ(e.runningTerminalIds,t.runningTerminalIds)&&FXe(e.terminalGroups,t.terminalGroups)}var HZ=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[$q],runningTerminalIds:[],activeTerminalId:$q,terminalGroups:[{id:LZ($q),terminalIds:[$q]}],activeTerminalGroupId:LZ($q)});function UZ(){return{...HZ,terminalIds:[...HZ.terminalIds],runningTerminalIds:[...HZ.runningTerminalIds],terminalGroups:eQ(HZ.terminalGroups)}}function WZ(){return HZ}function GZ(e){let t=jXe(e.terminalIds),n=t.length>0?t:[$q],r=MXe(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=PXe(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??LZ(`default`)};return VZ(e,c)?e:c}function IXe(e){let t=GZ(e);if(t.terminalIds.length<=IZ)return t;let n=new Set,r=e=>{!e||n.size>=IZ||t.terminalIds.includes(e)&&n.add(e)};r($q),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 GZ({...t,terminalIds:i.length>0?i:[$q],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 KZ(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>Ko(e)?[[e,IXe(t)]]:[]))}function LXe(e){return VZ(GZ(e),HZ)}function RXe(e){return e.trim().length>0}function qZ(e){return Uo(e)}function JZ(e,t){return`${qZ(e)}\u0000${t}`}function YZ(e,t){return JZ(e,t)}function XZ(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function ZZ(e,t){let n=PZ(e);return n?{url:n,observedAt:t}:null}function zXe(e){return ZZ(e.history,e.updatedAt)}function QZ(e){return e.type===`output`?ZZ(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?ZZ(e.snapshot.history,e.snapshot.updatedAt):null}function $Z(e,t,n){if(!n)return e;let r=qZ(t),i=e[r];return i&&XZ(i.observedAt)>XZ(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function eQ(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function tQ(e,t,n,r){let i=JZ(n,r.terminalId),a=e[i]??FZ,o={id:t,event:r},s=a.length>=OXe?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function nQ(e,t,n,r){let i=JZ(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function rQ(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function iQ(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function aQ(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 BXe(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function VXe(e,t){let n=BXe(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 oQ(e,t,n){let r=GZ(e);if(!RXe(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=eQ(r.terminalGroups),s=zZ(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(LZ(t),e);return o.push({id:n,terminalIds:[t]}),GZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=zZ(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=RZ(LZ(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 GZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function sQ(e,t){let n=GZ(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function HXe(e,t){let n=GZ(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function UXe(e,t){return oQ(e,t,`split`)}function cQ(e,t,n){let r=oQ(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function lQ(e,t){let n=GZ(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 WXe(e,t){let n=GZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return UZ();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??LZ(a);return GZ({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function uQ(e,t,n){let r=GZ(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 dQ(e,t){return!t||t.threadId.length===0?WZ():e[qZ(t)]??WZ()}function fQ(e,t,n){if(t.threadId.length===0)return e;let r=qZ(t),i=dQ(e,t),a=n(i);if(a===i)return e;if(LXe(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function GXe(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?FZ:e[JZ(t,n)]??FZ}function KXe(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[YZ(t,n)]??null}function qXe(e,t){if(!t||t.threadId.length===0)return[];let n=`${qZ(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function JXe(e,t){return!t||t.threadId.length===0?null:e[qZ(t)]??null}var pQ=Kt()(cJ(e=>{let t=(t,n)=>{e(e=>{let r=fQ(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=>sQ(e,n)),setTerminalHeight:(e,n)=>t(e,e=>HXe(e,n)),splitTerminal:(e,n)=>t(e,e=>UXe(e,n)),newTerminal:(e,n,r)=>t(e,e=>cQ(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=cQ(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=lQ(t,n)),r?.open&&(t=sQ(t,!0)),GZ(t)}),setActiveTerminal:(e,n)=>t(e,e=>lQ(e,n)),closeTerminal:(e,n)=>t(e,e=>WXe(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[qZ(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=qZ(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>uQ(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=YZ(t,n.terminalId),i=rQ(n),a=n.type===`started`||n.type===`restarted`;if(iQ(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?nQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):tQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=$Z(e.terminalPreviewUrlByThreadKey,t,QZ(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[YZ(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=qZ(t),i=YZ(t,n.terminalId),a=rQ(n),o=n.type===`started`||n.type===`restarted`;if(iQ(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=$Z(e.terminalPreviewUrlByThreadKey,t,QZ(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[YZ(t,n.terminalId)]:n.snapshot},s=fQ(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=cQ(r,n.terminalId)),t?(r=lQ(r,n.terminalId),r=sQ(r,!0)):(r=lQ(r,e.activeTerminalId),r=sQ(r,e.terminalOpen)),GZ(r)}),c={...c,[r]:VXe(c[r],n)});let d=EXe(n);d!==null&&(s=fQ(s,t,e=>uQ(e,n.terminalId,d)));let f=o&&a?nQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):tQ(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,[YZ(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:$Z(e.terminalPreviewUrlByThreadKey,t,zXe(n))})),clearTerminalState:t=>e(e=>{let n=qZ(t),r=fQ(e.terminalStateByThreadKey,t,()=>UZ()),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=aQ(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=qZ(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=aQ(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:DXe,version:4,storage:oJ(AXe),migrate:kXe,partialize:e=>({terminalStateByThreadKey:KZ(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function YXe(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 XXe(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 mQ(e){let t=YXe(e).trim()||`Unknown browser error.`,n=XXe(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 ZXe(e){let t=mQ(e);return`${t.cause} ${t.nextAction}`}function QXe(e){let t=mQ(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var hQ={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function gQ(e){return Uo(e)}function $Xe(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 eZe(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function _Q(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!$Xe(t.display)||!eZe(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 tZe(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 vQ(e,t,n){return e[t]===n?e:{...e,[t]:n}}function nZe(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 rZe(e,t){let n=nZe(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 iZe(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 yQ(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function aZe(e,t){let n=yQ(t);return e.some(e=>yQ(e)===n)?e:[...e,t]}function oZe(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 sZe(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 cZe(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 lZe(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 uZe(e,t){let n=t.payload.tabId,r=jce(lZe(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 dZe(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function fZe(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 pZe(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!cZe(t,n))return i;let o=uZe(t,n);if(!o.decision.observe)return i;let s=dZe(t,n,o),c=o.decision.accept?fZe(s,n):s;return{browserStateByThreadKey:vQ(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var bQ=Kt(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=gQ(t),i=e.browserStateByThreadKey[r]??hQ,a=n?_Q({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:vQ(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=gQ(t),i=e.browserStateByThreadKey[r]??hQ,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=gQ(t),i=iZe(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=rZe(e.browserStateByThreadKey[r]??hQ,n);switch(n.type){case`session.started`:{if(tZe({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=_Q({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:vQ(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=_Q({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:vQ(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:vQ(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:oZe(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:sZe({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:vQ(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:vQ(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:vQ(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:vQ(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:vQ(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 pZe({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:vQ(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:vQ(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:aZe(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...a,lastError:QXe(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=gQ(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 mZe(e,t){return t?e[gQ(t)]??null:null}var hZe={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function gZe(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 _Ze(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function vZe(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}var xQ=`forge:ui-state:v1`,SQ=[`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`],CQ=`months`,yZe=new Set([`weeks`,`months`,`quarters`]);function bZe(e){return typeof e==`string`&&yZe.has(e)?e:CQ}function wQ(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var TQ={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:CQ,projectLeadCompanion:hZe},EQ=new Set,DQ=[],OQ=new Map,kQ=!1;function xZe(){if(typeof window>`u`)return TQ;try{let e=window.localStorage.getItem(xQ);if(!e){for(let e of SQ){let t=window.localStorage.getItem(e);if(t)return AQ(JSON.parse(t)),TQ}return TQ}let t=JSON.parse(e);return AQ(t),{...TQ,projectGroupOrder:SZe(t.projectGroupOrderKeys),threadChangedFilesExpandedById:TZe(t.threadChangedFilesExpandedById),pinnedThreadById:CZe(t.pinnedThreadKeys),threadLinkedPrById:wZe(t.threadLinkedPrById),timelineWorkColumnWidth:wQ(t.timelineWorkColumnWidth??360),timelineScale:bZe(t.timelineScale)}}catch{return TQ}}function SZe(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function CZe(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 wZe(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 TZe(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 AQ(e){EQ.clear(),DQ.length=0;for(let t of e.expandedProjectCwds??[])typeof t==`string`&&t.length>0&&EQ.add(t);for(let t of e.projectOrderCwds??[])typeof t==`string`&&t.length>0&&!DQ.includes(t)&&DQ.push(t)}function EZe(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=OQ.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=OQ.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(xQ,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})),!kQ){kQ=!0;for(let e of SQ)window.localStorage.removeItem(e)}}catch{}}var jQ=new Yt(EZe,{wait:500});function MQ(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 NQ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function DZe(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)||!MQ(r,t[e]))return!1;return!0}function OZe(e,t){let n=new Map(OQ),r=new Map([...n.entries()].map(([e,t])=>[t,e]));OQ.clear();for(let e of t)OQ.set(e.key,e.cwd);let i=n.size!==OQ.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(DQ.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)??(EQ.size>0?EQ.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)??DQ.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 MQ(e.projectExpandedById,a)&&NQ(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function kZe(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 MQ(e.threadLastVisitedAtById,r)&&DZe(e.threadChangedFilesExpandedById,i)&&MQ(e.pinnedThreadById,a)&&MQ(e.threadLinkedPrById,o)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o}}function AZe(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 jZe(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 MZe(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 PQ(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 NZe(e,t){return PQ(e,t,e.pinnedThreadById[t]!==!0)}function PZe(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function FZe(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function IZe(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}function LZe(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function RZe(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function zZe(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function BZe(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function VZe(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 HZe(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 NQ(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function UZe(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 FQ=Kt(e=>({...xZe(),syncProjects:t=>e(e=>OZe(e,t)),syncProjectGroups:t=>e(e=>HZe(e,t)),syncThreads:t=>e(e=>kZe(e,t)),markThreadVisited:(t,n)=>e(e=>AZe(e,t,n)),markThreadUnread:(t,n)=>e(e=>jZe(e,t,n)),clearThreadUi:t=>e(e=>MZe(e,t)),setThreadPinned:(t,n)=>e(e=>PQ(e,t,n)),toggleThreadPinned:t=>e(e=>NZe(e,t)),setThreadLinkedPr:(t,n)=>e(e=>PZe(e,t,n)),clearThreadLinkedPr:t=>e(e=>FZe(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>IZe(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>RZe(e,t,n)),toggleProject:t=>e(e=>zZe(e,t)),setProjectExpanded:(t,n)=>e(e=>BZe(e,t,n)),reorderProjects:(t,n)=>e(e=>VZe(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>UZe(e,t,n)),setLastActiveProject:t=>e(e=>LZe(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:wQ(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:_Ze(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 WZe(e){FQ.getState().openProjectLeadCompanion(e)}FQ.subscribe(e=>jQ.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{jQ.flush()});var GZe=xt(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),KZe=class extends Ot()(`effect/http/FetchHttpClient/RequestInit`){},qZe=Kre(et(Ure((e,t,n,r)=>{let i=r.getRef(GZe),a=r.context.mapUnsafe.get(KZe.key)??{},o=a.headers?en(vn(a.headers),e.headers):e.headers,s=r=>Ze(Pee({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new En({reason:new nne({request:e,cause:t})})}),t=>Hte(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 bt(dte(e.body.stream),s)}return s(void 0)}))),JZe=ste.pipe(S,It(e=>{if(Qn(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=Oee(e.reason.response.headers[`retry-after`]).pipe(See(Ore),ute(()=>5));return et(A(t))}return et(A(1))})),YZe=Xe(function*(e){let t=yield*Tt(),n=At(t,Dre),r=At(t,je),i=He(t),o=p(Me(e.exportInterval),mee),s,c=Vre(At(t,Hi)).pipe(Ui(De(Ki,!1)),Wre({schedule:JZe,times:3})),l=sr({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(l=en(vn(e.headers),l));let d=Mre(e.url,{headers:l}),f=[],m=Dt(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return rt;s!==void 0&&(s=void 0);let t=f;if(e.maxBatchSize!==`disabled`){if(f.length===0)return rt;f=[]}return c.execute(Bi(d,e.body(t))).pipe(dee,kee(!1))}).pipe(Ue(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,f=[],Tee(`Disabling exporter for 60 seconds`,e)):rt),u({package:`@effect/opentelemetry`,module:e.label}));return yield*zt(r,m.pipe(wt,st,Kee(e.shutdownTimeout))),yield*a(o).pipe(Rt(m),Qe,Mt(r)),{push(t){s===void 0&&(f.push(t),e.maxBatchSize!==`disabled`&&f.length>=e.maxBatchSize&&fe(i(m),r))}}}),XZe=e=>{let t=e.attributes?IQ(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}},ZZe=Xe(function*(e){let t={...yield*Ml(Ln(Nl(Gn,Gn)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*Ml(Gn,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*Ml(Ln(Gn),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],XZe({serviceName:n,serviceVersion:r,attributes:t})},l),QZe=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},IQ=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:LQ(r)});return t},LQ=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(LQ)}};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:i(e)}}},RQ=class extends Ot()(`effect/observability/OtlpSerialization`){},$Ze=pe(RQ,{traces:e=>fn(e),metrics:e=>fn(e),logs:e=>fn(e)}),eQe=Xe(function*(e){let t=yield*ZZe(e.resource),n=yield*RQ,r={name:QZe(t)},i=yield*YZe({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??A(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??A(3)});function a(e){e.sampled&&i.push(rQe(e))}return ye({span(e){return nQe({...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})}),tQe={_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)}},nQe=e=>{let t=Object.assign(Object.create(tQe),e);return t.traceId=x(t.parent)?t.parent.value.traceId:zQ(32),t.spanId=zQ(16),t.events=[],t},zQ=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},rQe=e=>{let t=e.status,n=IQ(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?IQ(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=aQe;else if(ot(t.exit.cause))i={code:BQ.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=cte(t.exit.cause);if(i={code:BQ.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:o(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:iQe[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:IQ(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},BQ={Unset:0,Ok:1,Error:2},iQe={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},aQe={code:BQ.Ok},oQe=1e4,sQe={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":Ir?`electron`:`browser`,"service.version":ml}},cQe=Ee(qZe,$Ze,pe(Gi,()=>!0)),VQ=null,HQ=null,UQ=null,WQ=null,GQ=0,KQ=Promise.resolve(),lQe=pe(Vee,ye({span(e){return VQ?.span(e)??new c(e)}}));function uQe(e={}){return e.exportIntervalMs===void 0&&WQ!==null||(KQ=KQ.finally(()=>dQe(e))),KQ}async function dQe(e){let t=hr(`/api/observability/v1/traces`),n=fr()?.bearerToken,r=Math.max(10,e.exportIntervalMs??oQe),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(WQ===i&&VQ!==null)return;WQ=i;let a=++GQ,o=HQ,s=UQ;VQ=null,HQ=null,UQ=null,await qQ(o,s);let c=al(cQe),l=c.runSync(Re());try{let e=await c.runPromise(ee(l)(eQe({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:sQe})));if(a!==GQ){await qQ(c,l);return}VQ=e,HQ=c,UQ=l}catch(e){await qQ(c,l),a===GQ&&console.warn(`Failed to configure client tracing exporter`,{error:fQe(e),otlpTracesUrl:t})}}async function qQ(e,t){e!==null&&t!==null&&await e.runPromise(Be(t,St)).catch(()=>void 0).finally(()=>{e.dispose()})}function fQe(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var JQ=15e3,YQ=new Map,XQ=Wt([]).pipe(Ut,Vt(`slow-rpc-ack-requests`));function ZQ(e){Ht.set(XQ,[...e])}function QQ(){return Ht.get(XQ)}var $Q=`global`;function pQe(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)}function mQe(e,t,n=$Q){if(!pQe(t))return;n$(e,n),vQe();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:JQ},a=t$(n,e),o=setTimeout(()=>{YQ.delete(a),_Qe(i)},JQ);YQ.set(a,{request:i,timeoutId:o})}function hQe(e,t=$Q){n$(e,t);let n=QQ();n.some(n=>n.clientId===t&&n.requestId===e)&&ZQ(n.filter(n=>n.clientId!==t||n.requestId!==e))}function e$(e){for(let[t,n]of YQ)n.request.clientId===e&&(clearTimeout(n.timeoutId),YQ.delete(t));ZQ(QQ().filter(t=>t.clientId!==e))}function gQe(){for(let e of YQ.values())clearTimeout(e.timeoutId);YQ.clear(),ZQ([])}function t$(e,t){return`${e}:${t}`}function n$(e,t){let n=t$(t,e),r=YQ.get(n);r&&(clearTimeout(r.timeoutId),YQ.delete(n))}function _Qe(e){let t=[...QQ(),e];if(t.length<=256){ZQ(t);return}ZQ(t.slice(-256))}function vQe(){for(;YQ.size>=256;){let e=YQ.keys().next().value;if(e===void 0)return;let t=YQ.get(e);if(!t)return;n$(t.request.requestId,t.request.clientId)}}function yQe(){return dr(XQ)}var bQe=jo(Wn),r$=1;function xQe(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function i$(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 SQe(){return{onAttempt:Ane,onOpen:jne,onError:e=>{Tne(e)},onClose:e=>{Mne(e)},trackGlobalConnection:!0}}function CQe(e){let t=SQe(),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 wQe(e,t){let n=r$;r$+=1;let r=CQe(t),i=typeof e==`function`?ft(()=>e()).pipe(Ze(e=>i$(e)),nte(e=>ct(()=>{r.onError(xQe(e))})),l):i$(e),a=pe(ca,(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=la(i).pipe(E(a)),s=It(y(10),e=>et(Ve(wne(e)??0)));return dt(Po,Ze(Fo({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`?hQe(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&e$(i),r(e))).pipe(Ke(ct(()=>{e$(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&mQe(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(E(Ee(o,Ao)))}var TQe=Ve(250),a$=()=>void 0,o$=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=ze(Me(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},EQe=new Set([`OrchestrationGetSnapshotError`]);function DQe(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&EQe.has(t)}function OQe(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?kQe(e):String(e)}function kQe(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 AQe=4e3,jQe=1e4,MQe=500,s$=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??AQe,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??jQe,sessionCloseGraceMs:r?.sessionCloseGraceMs??MQe},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=Dt(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(jt({duration:o,orElse:()=>r(new o$(o))}));return await n.runtime.runPromise(s)}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:a$},i=ze(Me(n?.retryDelay??TQe));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=a$}catch(e){if(r.cancelCurrentStream=a$,!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=OQe(e);return kK(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await NQe(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){DQe(e)||BK(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=>{BK(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(Be(e.clientScope,St)),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:wQe(this.url,this.lifecycleHandlers),makeClient:bQe},t=al(Ee(e.layer,lQe)),n=t.runSync(Re());return{runtime:t,clientScope:n,clientPromise:t.runPromise(ee(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(ft(()=>e.clientPromise).pipe(bt(e=>qee(t(e),e=>ct(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if($ee(e)){a();return}o(Fe(e.cause))}}),completed:s}}};function NQe(e){return new Promise(t=>{setTimeout(t,e)})}var c$=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,PQe=/^[A-Za-z0-9_-]+$/;function FQe(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+=c$[o>>>18&63],t+=c$[o>>>12&63],n+1<e.byteLength&&(t+=c$[o>>>6&63]),n+2<e.byteLength&&(t+=c$[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function IQe(e){if(e.length===0||!PQe.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=c$.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 l$(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 LQe(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 ${pne}.`);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:FQe(a),sha256:await l$(a)})}return{totalBytes:e.byteLength,sha256:await l$(e),chunks:i}}async function RQe(e){let t=IQe(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 l$(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function zQe(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 RQe(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 l$(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var u$=`forge`,BQe=RegExp(`^${u$}\\/[0-9a-f]{8}$`);function VQe(){return`${u$}/${de(vte).replace(/-/g,``).slice(0,8).toLowerCase()}`}function HQe(e){return BQe.test(e.trim().toLowerCase())}function UQe(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 WQe(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 GQe(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 d$(e){return`https://${e}`}function KQe(e){return e===`github.com`||e.includes(`github`)}function qQe(e){return e===`gitlab.com`||e.includes(`gitlab`)}function JQe(e){return e===`bitbucket.org`}function YQe(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function XQe(e){let t=GQe(e);if(!t)return null;let n=UQe(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?KQe(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:d$(t)}:qQe(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:d$(t)}:JQe(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:d$(t)}:YQe(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:d$(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:d$(t)}:null}var ZQe={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function f$(e,t){return{...e,...t??ZQe}}function QQe(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function $Qe(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 e$e(e,t){switch(t._tag){case`snapshot`:return f$(t.local,t.remote);case`localUpdated`:return f$(t.local,e?QQe(e):null);case`remoteUpdated`:return f$(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:$Qe(e),t.remote)}}var t$e=262144,n$e=250;function r$e(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function i$e(e){return new Promise(t=>setTimeout(t,e))}function a$e(e){let t=Tce({controllerId:crypto.randomUUID(),maxPendingWriteBytes:t$e}),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(!kK(r$e(e)))throw e;await i$e(n$e)}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()}}}var o$e=2e4,s$e=12e4,c$e=3e5;function l$e(e){return e instanceof o$||kK(e instanceof Error?e.message:String(e))}async function u$e(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?c$e:o$e,r=()=>e.request(e=>e[ln.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!l$e(t))throw t;return await e.reconnect(),await r()}}function p$(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function m$(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>d$e(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 zQe({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function d$e(e,t,n){if(e.protocolError===null){if(t.kind===`started`){f$e(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`){p$e(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function f$e(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 p$e(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 m$e(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${ane}-byte write limit.`);let i=await LQe(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{p$(n?.signal);let r=await h$e(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await g$e(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await _$e(e,a),t}}function h$e(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 g$e(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;p$(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[M.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}p$(i?.signal),await e.request(e=>e[M.workspaceCommitWriteFile]({transferId:t}))}}async function _$e(e,t){await e.request(e=>e[M.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}function h$(e){let t=a$e(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{Cne(),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))},projects:{searchEntries:t=>e.request(e=>e[M.projectsSearchEntries](t)),readFile:(t,n)=>m$(e,e=>e[M.workspaceReadFile](t),n),writeFile:(t,n)=>m$e(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[M.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[M.projectCheckoutDeletionExecute](t))},codeGraph:{summary:t=>e.request(e=>e[M.codeGraphSummary](t)),neighborhood:t=>e.request(e=>e[M.codeGraphNeighborhood](t)),search:t=>e.request(e=>e[M.codeGraphSearch](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=e$e(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:s$e})},orchestration:{dispatchCommand:t=>u$e(e,t),getTurnDiff:(t,n)=>m$(e,e=>e[ln.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>m$(e,e=>e[ln.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[ln.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[ln.subscribeThread](t),n,r)}}}var v$e=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function g$(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!v$e.has(t)?null:t}function _$(e,t){return e===401||e===403||g$(t)!==null}function y$e(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return _$(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}function b$e(e){return new Promise(t=>globalThis.setTimeout(t,e))}function v$(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function y$(e){if(e?.aborted)throw v$()}function x$e(e,t){return t?t.aborted?Promise.reject(v$()):new Promise((n,r)=>{let i=()=>r(v$());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function S$e(e,t){return t?t.aborted?Promise.reject(v$()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(v$())};t.addEventListener(`abort`,a,{once:!0})}):b$e(e)}var b$=`forge.deviceRegistry.deviceKey`,x$=`forge.deviceRegistry.runtimeId`;function C$e(e){let t=w$(b$,e.desktopIdentity?.deviceKey,`device`),n=w$(x$,e.desktopIdentity?.runtimeId,`runtime`),r=C$(e.desktopIdentity?.hostKey),i=D$e(),a=e.desktopAvailable?`desktop`:O$e(),o=e.desktopAvailable?E$e(e.desktopIdentity)??k$e(i):A$e(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 S$(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return C$e({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function C$(e){let t=e?.trim()??``;return t.length>0?t:null}function w$(e,t,n){let r=C$(t);return r?(bJ(e,r),r):T$e(e,n)}function w$e(){return yJ(x$)}function T$(){return yJ(b$)}function T$e(e,t){let n=yJ(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return bJ(e,r),r}function E$e(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function D$e(){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 O$e(){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 k$e(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function A$e(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var E$=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function D$(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new E$(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new E$(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function j$e(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 M$e(e){if(!e.deviceKey)throw new E$(`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 E$(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new E$(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function N$e(e,t){let n=async()=>M$e(await j$e(t));return{acquireRoute:async()=>{let r=await n(),i=await Sce();try{return wce({route:await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Yn],protocolMinVersion:4,protocolMaxVersion:4,...Cce(i)}),runtimeId:e,endpoint:i})}catch(e){if(e instanceof rl)throw new E$(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return D$(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 D$(e)}}}}var O$=`forge.relayControlJournal.v1`;function k$(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var P$e={read:()=>k$().getItem(O$),write:e=>k$().setItem(O$,e)},A$=null,j$=Kt()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function F$e(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));j$.getState().replace(Object.fromEntries([...t].map(t=>[t,Ise(e.records,t)])))})}function M$(){return A$===null&&(A$=Vc({storage:P$e}),F$e(A$)),A$}function I$e(){let e=(0,ul.c)(1),t=j$(R$e),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,F.useEffect)(L$e,n),t}function L$e(){M$()}function R$e(e){return e.byRuntimeId}function z$e(e){let t=M$();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 B$e=6e4;function V$e(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 H$e(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 U$e(e){let t=await fetch(hr(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),lr({method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})})),n=await t.json().catch(()=>null);if(!t.ok){let e=_$(t.status,n)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${t.status}).`;throw Object.assign(Error(V$e(n,e)),{status:t.status,...g$(n)?{code:g$(n)}:{}})}return H$e(n)}function W$e(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+B$e}function F$(e){let t=e.requestDescriptor??U$e,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=()=>i||(i=t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId}}).then(async t=>(await e.validateDescriptor?.(t),await e.persistDescriptor?.(t),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>e?.forceRefresh||a||W$e(r,n())?o():Promise.resolve(r),invalidate:()=>{a=!0}}}var G$e=12e4,K$e=3e4,I$=3e4;function L$(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 q$e(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function J$e(e){let t=e.now??Date.now,n=e.renewalSkewMs??G$e,r=!1,i=null,a=null,o=L$(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=L$(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()+I$;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},I$),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=L$(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=q$e(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()+K$e?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}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=hX(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||Y$(t,e.record):t!==null&&Y$(t,e.registryExpectation.record)}var Y$e=9e5,Z$=32,Q$=()=>void 0;function $$(e,t){return Uo(zo(e,t))}function e1(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function X$e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=yZ(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=vZ(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&&!X$e(e)}function n1(e){if(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Q$)return!0;let t=M1(e.environmentId);return t?(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{if(e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`snapshot`){bZ.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),bZ.getState().clearThreadSubscriptionError(e.environmentId,e.threadId);return}b1e(t.event,e.environmentId)},{onError:t=>ZYe(e.environmentId,e.threadId,t)}),!0):!1}function r1(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=j1(()=>{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$,n1e(),!0):!1}var a1=null;function Z$e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=yZ(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=vZ(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function Q$e(e){e.unsubscribe!==Q$&&(e.unsubscribe(),e.unsubscribe=Q$),n1(e)||r1(e)}function $$e(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`){Q$e(e);return}M1(e.environmentId)?.reconnect().catch(t=>{BK(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 e1e(){let e=Date.now();for(let t of W$.values()){let n=hXe({isWorking:Z$e(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:gXe,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&$$e(t,n,e-t.lastEventAt)}}function t1e(){a1===null&&(a1=setInterval(e1e,_Xe))}function n1e(){W$.size>0||a1!==null&&(clearInterval(a1),a1=null)}function r1e(e){for(let[t,n]of W$)n.environmentId===e&&i1(t)}function i1e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=vZ(n,t);if(!r)return null;let i=yZ(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 a1e(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=i1e(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function o1e(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 s1e(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)))},Y$e))}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)&&s1e(e)}function c1e(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 l1e(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),t1e(),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 u1e(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],d1e=9e4;function f1e(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function p1e(e){if(y$e(e))return!1;let t=f1e(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 m1e(e){return f1[e]??f1[f1.length-1]}function h1e(){return d1e}function g1e(e,t){if(!UY(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}. The VM may still be starting.`))},h1e())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function p1(e){xX.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function m1(e){let t=u1();xX.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),dX.getState().markConnected(e,t)}function h1(e,t){xX.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function g1(e,t){xX.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:u1(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:u1()}:{}})}function _1(e,t){xX.getState().patch(e,{connectionState:`error`,...u1e(t)})}function _1e(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=pZ(bZ.getState());FQ.getState().syncProjects(e.map(e=>({key:Ho(Ro(e.environmentId,e.id)),cwd:e.cwd})))}function y1(){let e=mZ(bZ.getState());FQ.getState().syncThreads(e.map(e=>({key:Uo(zo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),_Je(e.map(e=>zo(e.environmentId,e.id)))}function v1e(){v1(),y1();let e=QYe({snapshotThreads:mZ(bZ.getState()).map(e=>({key:Uo(zo(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:zY.getState().listDraftThreadKeys()});pQ.getState().removeOrphanedTerminalStates(e)}function b1(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function y1e(e,t){if(e.length===0)return;let n=$Ye(e),r=_1e(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()),bZ.getState().applyOrchestrationEvents(r,t),i){let e=pZ(bZ.getState());FQ.getState().syncProjects(e.map(e=>({key:Ho(Ro(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=mZ(bZ.getState());FQ.getState().syncThreads(e.map(e=>({key:Uo(zo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=zY.getState();for(let e of n.promoteDraftThreadIds)BY(zo(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(zo(t,e)),FQ.getState().clearThreadUi(Uo(zo(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=zo(t,e);pQ.getState().removeTerminalState(n),bQ.getState().clearBrowserState(n)}c1(t)}function b1e(e,t){y1e([e],t)}function x1e(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?zo(t,n):null,i=r?vZ(bZ.getState(),r):void 0;switch(bZ.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:v1();return;case`thread-upserted`:y1(),!i&&r&&BY(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(pQ.getState().removeTerminalState(r),bQ.getState().clearBrowserState(r)),c1e(t,e.thread.id),o1();return;case`thread-removed`:r&&(i1(Uo(r)),zY.getState().clearDraftThread(r),FQ.getState().clearThreadUi(Uo(r)),pQ.getState().removeTerminalState(r),bQ.getState().clearBrowserState(r)),y1();return}}function S1e(e,t){return e.invalidateQueries({queryKey:wZ.all(t)})}function x1(e){return{onWelcome:(t,n)=>{e?.(t),G$&&S1e(G$.queryClient,n)},applyShellEvent:x1e,syncShellSnapshot:(e,t)=>{let n=a1e(e,t);bZ.getState().syncServerShellSnapshot(n,t),o1e(t,n.threads.map(e=>e.id)),c1(t),v1e()},applyTerminalEvent:(e,t)=>{let n=zo(t,an.make(e.threadId)),r=vZ(bZ.getState(),n),i=zY.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&pQ.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=zo(t,an.make(e.threadId)),r=vZ(bZ.getState(),n),i=zY.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&bQ.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{_1(t,e)}}}function S1(){if(typeof window>`u`)return;let e=cr();if(e?.primaryMode===`cloud`&&e.bearerToken)return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function C1e(){if(typeof window>`u`)return;let e=cr(),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 w1e(e){let t=Gie(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return h$(new s$(async()=>{await mr().catch(()=>null);let e=S1();if(e)try{return await DZ({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})}catch(e){throw lq(e)&&_r(`ws-token`),e}return SGe(t)}))}function T1e(e){return h$(new s$(()=>DZ({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken}),{trackGlobalConnection:!1,onAttempt:()=>{p1(e.environmentId)},onOpen:()=>{m1(e.environmentId)},onError:t=>{xX.getState().patch(e.environmentId,{connectionState:`error`,lastError:t,lastErrorAt:u1()})},onClose:t=>{g1(e.environmentId,t.reason)}}))}function C1(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`)}function E1e(e){let t=e.runtimeId?.trim();if(t)return t;let n=WY(e.environmentId);if(!n)throw Error(`Saved Cloud environment ${e.environmentId} is missing its runtime id.`);return n}function D1e(e,t,n){let r=e;return F$({runtimeId:E1e(e),...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...t===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:t,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await EZ({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(n&&!n())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...I1(r),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:Kn(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:u1()};await _X(t),await yX(t.environmentId),dX.getState().upsert(t),r=t}})}function O1e(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 k1e(e,t,n){return n()&&xX.getState().ensure(e.environmentId),h$(new s$(async()=>{let n=await t.acquire(),r=t=>DZ({wsBaseUrl:t.wsBaseUrl,httpBaseUrl:t.httpBaseUrl,bearerToken:t.bearerToken,...UY(e.environmentId)?{runtimeTicket:t.bearerToken}:{}});try{return await r(n)}catch(n){if(!UY(e.environmentId)||!lq(n))throw n;return r(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&p1(e.environmentId)},onOpen:()=>{n()&&m1(e.environmentId)},onError:r=>{UY(e.environmentId)&&C1(r)&&t.invalidate?.(),n()&&xX.getState().patch(e.environmentId,{connectionState:`error`,lastError:r,lastErrorAt:u1()})},onClose:r=>{UY(e.environmentId)&&(r.code===1008||C1(r.reason))&&t.invalidate?.(),n()&&g1(e.environmentId,r.reason)}}))}async function w1(e,t,n,r,i,a,o){let s=await t.acquire(),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),EZ({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);if(!r())return!1;xX.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=hX(e.environmentId);return r()&&l.authenticated&&u&&dX.getState().upsert({...u,lastAuthenticatedPullRequestCapability:c.environment.capabilities?.pullRequests===!0}),!0}function T1(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 E1(e){let t=R$.get(e);return t?(R$.delete(e),r1e(e),l1(),await t.dispose(),!0):!1}function D1(){let e=Iq();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 T1(OZ({kind:`primary`,knownEnvironment:e,client:w1e(e),resolveEnvironmentId:()=>Iq()?.environmentId??e.environmentId,...r?{readiness:n?{bearerToken:n.bearerToken}:{}}:{},...x1()}))}async function A1e(e,t,n){let r=R$.get(e.environmentId);if(r)return r;let i=UY(e.environmentId),a=()=>X$({record:e,generation:t,registryExpectation:n?.registryExpectation??{kind:`existing-record`,record:e}}),o=i?n?.bearerToken:n?.bearerToken??await vX(e.environmentId);if(!i&&!o)throw a()&&xX.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 s=i?D1e(e,o??void 0,a):O1e({record:e,bearerToken:o}),c=await s.acquire();if(!a())throw Error(`Saved environment changed while its connection was being acquired.`);let l=n?.client??k1e(e,s,a),u=Io({id:e.environmentId,label:e.label,source:`manual`,target:{httpBaseUrl:c.httpBaseUrl,wsBaseUrl:c.wsBaseUrl}}),d=i&&c.expiresAt?J$e({initialDescriptor:{httpBaseUrl:c.httpBaseUrl,wsBaseUrl:c.wsBaseUrl,bearerToken:c.bearerToken,expiresAt:c.expiresAt},renew:async()=>{let e=await s.acquire({forceRefresh:!0});return{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken,expiresAt:e.expiresAt??null}},onState:t=>{a()&&xX.getState().patch(e.environmentId,{providerAuthority:t})}}):null,f=OZ({kind:`saved`,knownEnvironment:{...u,environmentId:e.environmentId},client:l,readiness:{bearerToken:c.bearerToken},tolerateReportedEnvironmentIdentity:i,refreshMetadata:async()=>{await w1(e,s,l,a)},...d?{ensureProviderAuthority:d.ensureLive,onDispose:d.dispose}:{},onConfigSnapshot:t=>{a()&&xX.getState().patch(e.environmentId,{descriptor:t.environment,serverConfig:t})},...x1(t=>{a()&&xX.getState().patch(e.environmentId,{descriptor:t.environment})})});try{if(!await g1e(e.environmentId,w1(e,s,l,a,n?.role??null,n?.serverConfig??null,n?.signal))||!a())throw Error(`Saved environment changed while its connection was being acquired.`);return T1(f)}catch(t){throw a()&&_1(e.environmentId,t),await f.dispose().catch(()=>void 0),t}}async function O1(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=A1e(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 k1(e){await nX(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 P1(e)}))}function A1(){G$?.stop(),G$=null}function j1(e){return U$.add(e),()=>{U$.delete(e)}}function M1(e){return R$.get(e)??null}function j1e(e){let t=M1(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function N1(){return D1()}async function M1e(){let e=C1e();if(!e)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let t=await aXe({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return R$.get(t.environmentId)||T1(OZ({kind:`desktop-local`,knownEnvironment:{...Io({id:t.environmentId,label:e.label,source:`desktop-managed`,target:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}),environmentId:t.environmentId,label:t.label},client:T1e({environmentId:t.environmentId,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken}),...x1()}))}async function N1e(e){let t=nn.make(e.runtimeId),n=R$.get(t);if(n)return n;p1(t);let r=M$(),i=N$e(e.runtimeId,{apiClient:oq,getStoredDeviceKey:T$,buildDeviceRegistration:S$,controlSessionId:r.controlSessionId}),a=await i.acquireRoute(),o=a,s=xce({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=h$(new s$(a.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:s,makeClient:bce(Yn)})),l=OZ({kind:`saved`,knownEnvironment:{...Io({id:t,label:e.label,source:`manual`,target:{httpBaseUrl:fr()?.target.httpBaseUrl??a.relayWebSocketUrl,wsBaseUrl:a.relayWebSocketUrl}}),environmentId:t},client:c,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>{h1(t,e)},...x1(e=>{xX.getState().patch(t,{descriptor:e.environment})})});try{let[,e]=await Promise.all([l.ensureBootstrapped(),c.server.getConfig()]);return h1(t,e),m1(t),T1(l)}catch(e){throw _1(t,e),await l.dispose().catch(()=>void 0),e}}function P1e(e){let t=nn.make(e.runtimeId),n=R$.get(t);if(n)return Promise.resolve(n);let r=z$.get(t);if(r)return r;let i=N1e(e).finally(()=>{z$.delete(t)});return z$.set(t,i),i}async function P1(e){R$.get(e)?.kind===`saved`&&(xX.getState().clear(e),await E1(e).catch(()=>!1))}function F1(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 F1e(e){let t=e.environmentId;B$.set(t,(B$.get(t)??0)+1);try{return M1(t)||await L1(e),!0}catch{return F1([t]),!1}}async function I1e(){await pX();let e=(await Promise.all(WJe().map(async e=>await F1e(e)?e.environmentId:null))).flatMap(e=>e===null?[]:[e]),t=!1;return()=>{t||(t=!0,F1(e))}}async function L1e(e){J$(e),dX.getState().remove(e),await yX(e),await P1(e)}function I1(e){let t=hX(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=xX.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}async function R1e(e){let t=nn.make(e.environment.environmentId),n=hX(t),{kind:r,cmmdOrganizationId:i,cmmdProjectId:a,runtimeId:o,runtimeTicketExpiresAt:s}=e.environment,c={environmentId:t,label:e.environment.label,wsBaseUrl:Kn(e.environment.wsBaseUrl),httpBaseUrl:e.environment.httpBaseUrl,createdAt:n?.createdAt??u1(),lastConnectedAt:u1(),...r===void 0?{}:{kind:r},...i===void 0?{}:{cmmdOrganizationId:i},...a===void 0?{}:{cmmdProjectId:a},...o===void 0?{}:{runtimeId:o},...s===void 0?{}:{runtimeTicketExpiresAt:s}};y$(e.signal);let l=mX(),u=n?await vX(c.environmentId):null;J$(c.environmentId),await E1(c.environmentId).catch(()=>!1),await L1(c,{bearerToken:e.bearerToken,registryExpectation:n?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}});let d=!1;try{return y$(e.signal),await _X(c),d=!0,y$(e.signal),await yX(c.environmentId),y$(e.signal),dX.getState().upsert(I1(c)),c}catch(t){throw await E1(c.environmentId).catch(()=>!1),u&&await KJe(c.environmentId,u),d&&await nX(l),y$(e.signal),t}}async function L1(e,t){if(!UY(e.environmentId))return O1(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){y$(t?.signal);try{let n=await O1(e,t);return await x$e(n.ensureBootstrapped(),t?.signal),n}catch(a){if(i=a,!r())throw a;if(await E1(e.environmentId).catch(()=>!1),y$(t?.signal),n>=7||!p1e(a))throw r()&&_1(e.environmentId,a),a;let o=m1e(n);t?.onBootstrapRetry?.({attempt:n+2,maxAttempts:d1,retryDelayMs:o,error:a}),r()&&xX.getState().patch(e.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await S$e(o,t?.signal)}}let a=i instanceof Error?i:Error(String(i));throw r()&&_1(e.environmentId,a),a}async function z1e(e){await R$.get(e)?.ensureBootstrapped()}async function B1e(e){let t=R$.get(e);if(!UY(e)){await t?.ensureProviderAuthority?.();return}if(!t?.ensureProviderAuthority)throw Error(`Cloud runtime provider authority is not available.`);await t.ensureProviderAuthority()}function V1e(e){if(G$?.queryClient===e)return G$.refCount+=1,()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&A1())};A1(),K$=!1;let t=new kKe(()=>{K$&&(K$=!1,e.invalidateQueries({queryKey:CZ.all}),e.invalidateQueries({queryKey:SZ.all}))},{wait:100,leading:!1,trailing:!0});D1(),mr().catch(()=>void 0);let n=dX.subscribe(()=>{fX()&&k1(mX())});return pX().then(()=>k1(mX())).catch(()=>void 0),G$={queryClient:e,queryInvalidationThrottler:t,refCount:1,stop:()=>{n(),t.cancel()}},()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&A1())}}function R1(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var z1=Object.freeze({data:null,error:null,cause:null,isPending:!1}),B1=Object.freeze({...z1,isPending:!0}),H1e=Wt(z1).pipe(Ut,Vt(`git-status:null`)),V1=()=>void 0,H1=new Map,U1e=new Set,U1=new Map,W1=new Map,W1e=1e3,G1=hte(e=>(U1e.add(e),Wt(B1).pipe(Ut,Vt(`git-status:${e}`))));function K1(e){return e.environmentId===null||R1(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function q1(e){if(e.environmentId===null)return null;let t=M1(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function J1(e){let t=K1(e);return t===null?z1:Ht.get(G1(t))}function G1e(e,t){let n=K1(e);if(n===null)return V1;let r=H1.get(n);return r?(r.refCount+=1,()=>Y1(n)):(H1.set(n,{refCount:1,unsubscribe:J1e(n,e,t)}),()=>Y1(n))}function K1e(e,t){let n=K1(e),r=R1(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??q1(e)?.client;if(!i)return Promise.resolve(J1(e).data);let a=U1.get(n);if(a)return a;let o=W1.get(n)??0;if(Date.now()-o<W1e)return Promise.resolve(J1(e).data);W1.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{U1.delete(n)});return U1.set(n,s),s}function q1e(e){let t=(0,ul.c)(4),n=K1(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>G1e({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=dr(n===null?H1e:G1(n));return n===null?z1:a}function Y1(e){let t=H1.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),H1.delete(e)))}function J1e(e,t,n){let r=R1(t.cwd);if(r===null)return V1;let i=null,a=V1,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:q1(t);if(!o){i!==null&&(a(),a=V1,i=null),X1(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=Y1e(e,r,o.client))},s=n?V1:j1(o);return o(),()=>{s(),a()}}function Y1e(e,t,n){return X1(e),n.onStatus({cwd:t},t=>{Ht.set(G1(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{X1(e)}})}function X1(e){let t=G1(e),n=Ht.get(t),r=n.data===null?B1:{...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 Z1(e,t){return Wt(t).pipe(Ut,Vt(e))}function Q1(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var X1e=[],Z1e=[],Q1e=[],$1e=e=>e?.availableEditors??X1e,e0e=e=>e?.keybindings??Z1e,t0e=e=>e?.keybindingsConfigPath??null,n0e=e=>e?.observability??null,r0e=e=>e?.providers??Q1e,i0e=e=>e?.settings??vne,$1=Z1(`server-welcome`,null),e0=Z1(`server-config`,null),t0=Z1(`server-config-updated`,null),a0e=Z1(`server-providers-updated`,null);function n0(){return Ht.get(e0)}function o0e(){return Ht.get(t0)}function r0(e){s0(e),c0({providers:e.providers}),l0(Q1(e),`snapshot`)}function s0e(e){switch(e.type){case`snapshot`:r0(e.config);return;case`keybindingsUpdated`:{let t=n0();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};s0(n),l0(Q1(n),e.type);return}case`providerStatuses`:i0(e.payload);return;case`settingsUpdated`:a0(e.payload.settings);return;case`environmentUpdated`:o0(e.payload.environment);return}}function i0(e){let t=n0();if(c0(e),!t)return;let n={...t,providers:e.providers};s0(n),l0(Q1(n),`providerStatuses`)}function a0(e){let t=n0();if(!t)return;let n={...t,settings:e};s0(n),l0(Q1(n),`settingsUpdated`)}function o0(e){let t=n0();if(Pq()?.environmentId===e.environmentId&&Fq(e),!t)return;let n={...t,environment:e};s0(n),l0(Q1(n),`environmentUpdated`)}function c0e(e){Ht.set($1,e)}function l0e(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&c0e(e.payload)}),e.subscribeConfig(e=>{s0e(e)})];return n0()===null&&e.getConfig().then(e=>{t||n0()!==null||r0(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var u0e=1;function s0(e){Ht.set(e0,e)}function c0(e){Ht.set(a0e,e)}function l0(e,t){Ht.set(t0,{id:u0e++,payload:e,source:t})}function u0(e,t){let n=(0,F.useRef)(t);n.current=t;let r=(0,F.useCallback)(e=>{e!==null&&n.current(e)},[]);bne(e,r,{immediate:!0})}function d0e(){return dr(e0)}function d0(){return dr(e0,i0e)}function f0e(){return dr(e0,r0e)}function p0e(){return dr(e0,e0e)}function m0e(){return dr(e0,$1e)}function h0e(){return dr(e0,t0e)}function g0e(){return dr(e0,n0e)}function _0e(e){u0($1,e)}function v0e(e){u0(t0,e)}function y0e(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 b0e(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 x0e(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 S0e(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 y0e(e)){if(n){i.appendChild(b0e(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=x0e({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 f0;function C0e(){return p0(N1().client)}function p0(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 o0(n.environment),n}}}function w0e(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 T0e(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):S0e(e,t)},persistence:{getClientSettings:$Y,setClientSettings:eX,getSavedEnvironmentRegistry:tX,setSavedEnvironmentRegistry:nX,getSavedEnvironmentSecret:rX,setSavedEnvironmentSecret:iX,removeSavedEnvironmentSecret:aX},server:p0(e)}}function m0(){if(typeof window>`u`)return;if(f0)return f0;let e=T0e(N1().client);return window.nativeApi?(f0=w0e(e,window.nativeApi),f0):(f0=e,f0)}function E0e(){let e=m0();if(!e)throw Error(`Local API not found`);return e}function h0(e,t){if(!Ne(e)||!Ne(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]=Ne(t)&&Ne(r)?h0(t,r):r}return n}var g0=`[CLIENT_SETTINGS]`,_0=new Set,v0=rr,y0=!1,b0=null;function D0e(){for(let e of _0)e()}function x0(){return v0}function S0(e){v0=e,D0e()}function O0e(e){return _0.add(e),k0e(),()=>{_0.delete(e)}}async function k0e(){if(y0)return;if(b0)return b0;let e=(async()=>{try{let e=await $Y();e&&S0(e)}catch(e){console.error(`${g0} hydrate failed`,e)}finally{y0=!0}})().finally(()=>{b0===e&&(b0=null)});return b0=e,b0}function A0e(e){S0(e),eX(e).catch(e=>{console.error(`${g0} persist failed`,e)})}var j0e=new Set(yne(Kte.fields));function M0e(e){let t={},n={};for(let[r,i]of Object.entries(e))j0e.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function C0(e){let t=d0(),n=(0,F.useSyncExternalStore)(O0e,x0,()=>rr),r=(0,F.useMemo)(()=>({...t,...n}),[n,t]);return(0,F.useMemo)(()=>e?e(r):r,[r,e])}function w0(){let e=(0,ul.c)(2),t=N0e,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(_ne)},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 N0e(e){let{serverPatch:t,clientPatch:n}=M0e(e);if(Object.keys(t).length>0){let e=n0();e&&a0(h0(e.settings,t)),N1().client.server.updateSettings(t)}Object.keys(n).length>0&&A0e({...x0(),...n})}function P0e(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var T0=new Map;function E0(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=T0.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,P0e(e,t));return T0.set(n,i),i}function F0e(e,t){return E0(t,!0).format(new Date(e))}function I0e(e,t){return E0(t,!1).format(new Date(e))}function D0(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 L0e(e){let t=D0(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}var R0e=[{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 z0e(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 B0e(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:z0e(r-n)}function O0(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function V0e(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?O0(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function k0(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 A0(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 H0e(e){let t=new Map,n=[...e].toSorted(J0);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?or.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?k0(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&&A0(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function U0e(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 W0e(e){let t=new Map,n=[...e].toSorted(J0);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?or.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=U0e(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&&A0(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function G0e(e,t){if(!t)return null;let n=[...e].toSorted(J0),r=null;for(let e of n){let t=M0(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 K0e(e,t){let n=[...e].toSorted(J0),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&&J0(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 j0(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 z0(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?z0(n):null}function q0e(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 z0(n)}}return j0(t,e.latestTurn?.turnId??null)}function J0e(e){return e!==null&&e.implementedAt===null}function Y0e(e,t){let n=X0e();return a2e([...e].toSorted(J0).filter(e=>!t||e.turnId===t||Z0e(e)).filter(e=>e.kind!==`tool.started`).filter(e=>e.kind!==`task.started`).filter(e=>e.kind!==`context-window.updated`).filter(e=>e.summary!==`Checkpoint captured`).filter(e=>n||e.kind!==`runtime.warning`).filter(e=>!Q0e(e)).map($0e)).map(({activityKind:e,collapseKey:t,...n})=>n)}function X0e(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function Z0e(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function Q0e(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 $0e(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=b2e(t),r=E2e(t),i=x2e(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=w2e(t),d=T2e(t);if(!s&&t&&typeof t.detail==`string`&&t.detail.length>0){let e=G0(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=e2e(t);if(f)l.githubConfirmation=f,l.tone=`approval`,l.label=`GitHub action needs approval`,l.toolTitle=P0(f.operation),l.detail=F0(f);else{let e=M0(t);e&&(l.githubActionRequired=e,l.tone=`approval`,l.label=I0(e.action),l.toolTitle=`GitHub setup required`,l.detail=R0(e))}let p=l2e(l);return p&&(l.collapseKey=p),l}function e2e(e){for(let t of N0(e)){if(t.userActionRequired!==`confirm_github_tool`)continue;let e=B0(t.confirmation),n=B0(e?.request),r=V0(e?.confirmationId),i=V0(e?.toolName),a=V0(e?.operation);if(!(!r||!i||!a||!n))return{confirmationId:r,toolName:i,operation:a,request:n}}return null}function M0(e){let t=N0(e)[0];if(!t)return null;let n=V0(t.userActionRequired);return!n||n===`confirm_github_tool`?null:{action:n,toolName:V0(t.toolName),message:V0(t.error)??V0(t.message)}}function N0(e){if(!e)return[];let t=[],n=new Set,r=(e,i)=>{if(i>8||e==null)return;if(typeof e==`string`){let n=V0(e);if(!n)return;let r=t2e(n);r&&V0(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(V0(a.userActionRequired)){t.push(a);return}for(let e of Object.values(a))r(e,i+1)};return r(e,0),t}function t2e(e){try{return B0(JSON.parse(e))}catch{return null}}function P0(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 F0(e){return[V0(e.request.repoFullName)??(V0(e.request.owner)&&V0(e.request.name)?`${V0(e.request.owner)}/${V0(e.request.name)}`:null),V0(e.request.cwd),V0(e.request.branch),V0(e.request.title)].filter(Boolean).join(` - `)}function I0(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 L0(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 R0(e){return e.action===`connect_cmmd`?L0(e.action):e.message??L0(e.action)}function n2e(e,t){return e.action===t.action&&e.toolName===t.toolName&&e.message===t.message}function r2e(e){switch(e){case`connect_cmmd`:return`Reconnect Forge`;case`connect_github`:return`Connect GitHub`;default:return`Open Git settings`}}function i2e(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(`
1019
- `)}function a2e(e){let t=[];for(let n of e){let e=t.at(-1);if(e&&o2e(e,n)){t[t.length-1]=s2e(e,n);continue}t.push(n)}return t}function o2e(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 s2e(e,t){let n=c2e(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 c2e(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function l2e(e){if(e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`)return;let t=u2e(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 u2e(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}function z0(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function B0(e){return e&&typeof e==`object`?e:null}function V0(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function H0(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 d2e(e){let t=H0(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function f2e(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 p2e=[{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 m2e(e){return p2e.find(t=>t.executables.includes(e))}function h2e(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=H0(r);return i.length>0?i:null}function g2e(e){let t=f2e(e);if(!t||t.rest.length===0)return e;let n=d2e(t.executable);if(!n)return e;let r=m2e(n);return r?h2e(t.rest,r.wrapperFlagPattern)??e:e}function _2e(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function U0(e){let t=V0(e);if(t)return t;if(!Array.isArray(e))return null;let n=e.map(e=>V0(e)).filter(e=>e!==null);return n.length===0?null:n.map(e=>_2e(e)).join(` `)}function v2e(e){let t=U0(e);return t?g2e(t):null}function y2e(e,t){let n=U0(e);return!n||t===null||n===t?null:n}function b2e(e){let t=B0(e?.data),n=B0(t?.item),r=B0(n?.result),i=B0(n?.input),a=V0(e?.itemType),o=V0(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?G0(o).output:null];for(let e of s){let t=v2e(e);if(t)return{command:t,rawCommand:y2e(e,t)}}return{command:null,rawCommand:null}}function x2e(e){return S2e(e)??V0(e?.title)}function S2e(e){if(!e)return null;let t=B0(e.data),n=B0(t?.item),r=B0(n?.input)??B0(t?.input),i=V0(e.title),a=V0(e.itemType),o=V0(n?.name)??V0(n?.toolName)??V0(t?.name)??V0(e.toolName)??i,s=V0(e.detail),c=[o,i,a,s].filter(Boolean).join(` `).toLowerCase();if(!c.includes(`browser`)&&!c.includes(`forge-browser`))return null;switch(C2e(o,r,s)){case`open-session`:return`Opened browser session`;case`name-session`:return`Named browser session`;case`new-tab`:return W0(r)??`Opened browser tab`;case`navigate`:return W0(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 C2e(e,t,n){let r=[V0(t?.type)??V0(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 W0(e){let t=V0(e?.url)??V0(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 G0(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 w2e(e){if(typeof e?.itemType==`string`&&jte(e.itemType))return e.itemType}function T2e(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:k0(e?.requestType)??void 0}function K0(e,t,n){let r=V0(n);!r||t.has(r)||(t.add(r),e.push(r))}function q0(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(q0(i,t,n,r+1),t.length>=12)return;return}let i=B0(e);if(i){K0(t,n,i.path),K0(t,n,i.filePath),K0(t,n,i.relativePath),K0(t,n,i.filename),K0(t,n,i.newPath),K0(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(q0(i[e],t,n,r+1),t.length>=12))return}}function E2e(e){let t=[],n=new Set;return q0(B0(e?.data),t,n,0),t}function J0(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=Y0(e.kind)-Y0(t.kind);return r===0?e.id.localeCompare(t.id):r}function Y0(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 D2e(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}function O2e(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=k2e(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:F0(t),tone:`approval`,toolTitle:P0(t.operation),githubConfirmation:t}}]:[]});return[...r,...i,...a,...o].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function k2e(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=N2e(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=A2e(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 A2e(e,t,n){if(!j2e(e))return null;let r=M2e(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?V0(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function j2e(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 M2e(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 N2e(e,t){return t.exec(e)?.[1]??null}function P2e(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 F2e(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 I2e(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function L2e(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}function X0(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}:{},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:{searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},codeGraph:{summary:e.codeGraph.summary,neighborhood:e.codeGraph.neighborhood,search:e.codeGraph.search},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 Z0(e){if(typeof window>`u`||!e)return;let t=M1(e);return t?X0(t.client):void 0}function R2e(e){let t=(0,ul.c)(4),n;t[0]===e?n=t[1]:(n=()=>M1(e),t[0]=e,t[1]=n);let r=(0,F.useSyncExternalStore)(j1,n,z2e),i,a;return t[2]===r?a=t[3]:(a=r?X0(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function z2e(){return null}function B2e(e){let t=Z0(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}function V2e(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=Zt(i),[,o]=F.useState(!1),s=qt(U2e).current,c=qt(H2e).current,l=F.useRef(0),u=F.useRef(!0),d=F.useRef([]),f=F.useRef(null),p=Zt(()=>{u.current||(u.current=!0,o(e=>!e))}),m=Zt((e,t)=>{c.set(e,t),p()}),h=Zt(e=>{c.delete(e),p()}),g=Zt(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(!K2e(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&Q0(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=G2e(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=Zt(()=>{let[e,t]=W2e(c),n=g(e);_(t),d.current=e,u.current=!1,s.forEach(e=>e(n)),a(n)});Xt(()=>(u.current||g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),Xt(()=>{u.current&&v()}),Xt(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=Zt(e=>(s.add(e),()=>{s.delete(e)})),b=F.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,Fr.jsx)(Ste.Provider,{value:b,children:t})}function H2e(){return new Map}function U2e(){return new Set}function W2e(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)=>Q0(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 G2e(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function K2e(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 Q0(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var $0=[`preview`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`graph`,`pull-request`],e2={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function t2(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function q2e(e,t,n){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n}}function n2(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 r2(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var J2e=`workspace:pull-requests`;function i2(e){return typeof e==`object`&&!!e}function Y2e(e){return typeof e==`string`&&$0.includes(e)}function a2(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function X2e(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function Z2e(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:a2(e.revealLine),revealRequestId:X2e(e.revealRequestId)}}function Q2e(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 $2e(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?_n.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var e4e=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function o2(e){return typeof e==`string`&&e.length>0}function s2(e){return e===null||typeof e==`string`}function t4e(e){return e===void 0||s2(e)}function n4e(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=a2(e.number),c=e.title;return![o2(t)&&e4e.has(t),o2(n),s2(r),o2(i),o2(a),o2(o),s!==null,t4e(c)].every(Boolean)||!o2(t)||!o2(n)?null:n2({provider:t,environmentId:nn.make(n),repositoryLinkId:r,projectId:sn.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function r4e(e){if(!i2(e)||!Y2e(e.kind))return null;let t=e.kind;return t===`file`?Z2e(e):t===`preview`?Q2e(e):t===`diff`?$2e(e):t===`pull-request`?n4e(e):{id:t,kind:t}}function i4e(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=r4e(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function a4e(e){if(!i2(e))return null;let t=i4e(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 o4e(e){if(!i2(e)||!i2(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===J2e)continue;let e=a4e(r);e&&(t[n]=e)}return{byThreadKey:t}}var s4e=`forge:right-panel-state`,c4e=3,l4e=e=>e===`workspace:pull-requests`;function u4e(e){return`draft:${e}`}function d4e(e){return e.startsWith(`draft:`)}function f4e(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var c2=(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}),l2=(e,t,n)=>{let r=e[t]??e2,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}},p4e=Kt()(cJ(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,e.surfaces.find(e=>e.kind===n)??r2(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return c2({...e,surfaces:t},t2(n))})})),revealBrowser:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,e.surfaces.find(e=>e.kind===`preview`)??t2(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:l2(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)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>{let t=`file:${n}`,i=e.surfaces.find(e=>e.id===t&&e.kind===`file`),a=q2e(n,f4e(r),(i?.revealRequestId??0)+1);return{...e,isOpen:!0,activeSurfaceId:a.id,surfaces:i?e.surfaces.map(e=>e.id===a.id?a:e):[...e.surfaces,a]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,n2(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:l2(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:l2(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:l2(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:l2(e.byThreadKey,t,()=>e2)})),show:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:l2(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:s4e,version:c4e,storage:oJ(()=>vJ),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!d4e(e)&&!l4e(e)))}),migrate:e=>o4e(e)}));function m4e(e){return t=>e?fZ(t,e.environmentId).projectById[e.projectId]:void 0}function u2(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=fZ(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=kX(o,a.threadId),r)}}function h4e(e){return u2(()=>e)}function g4e(e){return t=>{if(e)return fZ(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function _4e(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=fZ(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 v4e(e){return u2(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 d2=`forge:last-editor`;function f2(e){let t=new Set(e),n=qq(d2,Bn);if(n&&t.has(n))return n;let r=zte.find(e=>t.has(e.id))?.id??null;return r&&Jq(d2,r,Bn),r??null}async function y4e(e,t){let{availableEditors:n}=await e.server.getConfig(),r=f2(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}var b4e=/https?:\/\/[^\s"'`<>]+/g,x4e=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,S4e=/[.,;!?]+$/;function C4e(e){let t=e.replace(S4e,``);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 w4e(e,t){return e.start<t.end&&t.start<e.end}function p2(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=C4e(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=>w4e(s,e))||i.push(s)}return i}function m2(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function T4e(e){return e.startsWith(`/`)||m2(e)}function h2(e){return m2(e)||/[A-Za-z]:\\/.test(e)}function g2(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function E4e(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 _2(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 D4e(e){let t=p2(e,`url`,b4e,[]),n=p2(e,`path`,x4e,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function O4e(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 v2(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 k4e(e,t){return{start:v2(e.segments,t.start),end:v2(e.segments,t.end-1)}}function A4e(e,t){return e.start.y<=t&&t<=e.end.y}function j4e(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:yte(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function M4e(e,t){let{path:n,line:r,column:i}=_2(e),a=n;if(n.startsWith(`~/`)){let e=E4e(t);if(e){let t=h2(e)?`\\`:`/`;a=g2(e,n.slice(2),t)}}else T4e(n)||(a=g2(t,n,h2(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var y2=`diffs-container`,N4e=(()=>{try{return!1}catch{return!1}})(),P4e=/(?=^From [a-f0-9]+ .+$)/m,F4e=/(?=^diff --git)/gm,I4e=/(?<=\n)/,L4e=/^(---|\+\+\+)\s+([^\t\r\n]+)/,R4e=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,z4e=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,B4e=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,b2=`header-prefix`,x2=`header-filename-suffix`,S2=`header-metadata`,C2=`header-custom`,w2={dark:`pierre-dark`,light:`pierre-light`},V4e=`data-theme-css`,H4e=`data-unsafe-css`,U4e=`data-diffs-scrollbar-measure`,W4e=`data-diffs-code-view-header`,G4e=`data-diffs-code-view-footer`,T2=`--diffs-scrollbar-gutter-measured`,K4e=1e5,E2={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},q4e={...E2,hunkLineCount:1},J4e={paddingTop:8,paddingBottom:8,gap:8},Y4e={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},X4e=Object.freeze({fromStart:0,fromEnd:0}),Z4e={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},Q4e={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},D2=new Set,O2=null;function k2(e){D2.add(e),O2??=requestAnimationFrame(j2)}function A2(e){D2.delete(e)&&D2.size===0&&O2!=null&&(cancelAnimationFrame(O2),O2=null)}function j2(e){let t=new Set(D2);D2.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}O2=D2.size>0?requestAnimationFrame(j2):null}function M2(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 N2(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function $4e(e,t){let n=e?.theme??w2,r=t?.theme??w2,i=P2(e),a=P2(t);return N2(n,r)&&M2(e,t,[`theme`,`parseDiffOptions`])&&M2(i,a)}function P2(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function F2(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function e3e({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 I2(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function L2(e,t){return e-(t===0?0:1)}function R2(e,t){return L2(e,t)+t}var z2=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}},t3e=new class extends z2{};function n3e(e,t,n){return t3e.diff(e,t,n)}function B2(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 V2(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 H2(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 U2(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 W2(e,t){return H2(e,t,``)}function G2(e,t){return U2(e,t,``)}function K2(e,t){return t.slice(0,r3e(e,t))}function r3e(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 q2(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 J2(e,t){if(t)return X2(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Y2(e,t){if(t)return X2(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function X2(e,t){if(!t)return[Y2(e),J2(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=q2(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var Z2=`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}`,i3e=RegExp(`[${Z2}]+|\\s+|[^${Z2}]`,`ug`);new class extends z2{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=q2(e,r)}else n=e.match(i3e)||[];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)&&Q2(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&Q2(n,i,r,null,t.intlSegmenter),e}};function Q2(e,t,n,r,i){if(t&&n){let[a,o]=X2(t.value,i),[s,c]=X2(n.value,i);if(e){let r=B2(a,s);e.value=U2(e.value,s,r),t.value=W2(t.value,r),n.value=W2(n.value,r)}if(r){let e=V2(o,c);r.value=H2(r.value,c,e),t.value=G2(t.value,e),n.value=G2(n.value,e)}}else if(n){if(e){let e=Y2(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Y2(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Y2(r.value,i),[a,o]=X2(t.value,i),s=B2(n,a);t.value=W2(t.value,s);let c=V2(W2(n,s),o);t.value=G2(t.value,c),r.value=H2(r.value,n,c),e.value=U2(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Y2(r.value,i),n=K2(J2(t.value,i),e);t.value=G2(t.value,n)}else if(e){let n=K2(J2(e.value,i),Y2(t.value,i));t.value=W2(t.value,n)}}var a3e=new class extends z2{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Z2}]+|[^\\S\\n\\r]+|[^${Z2}]`,`ug`);return e.match(t)||[]}};function o3e(e,t,n){return a3e.diff(e,t,n)}var s3e=new class extends z2{constructor(){super(...arguments),this.tokenize=e4}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
1018
+ `)}}}var mXe=(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 pXe(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},hXe=6e4;function gXe(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 _Xe(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 OZ(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=_Xe({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??hXe}),s=e.readiness?(e.readiness.openStream??mXe)({url:gXe(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-DsJoTBtH.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([2,1,3,4])).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 vXe(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var yXe=3e4,bXe=1e4,xXe=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,kZ=/https?:\/\/[^\s"'`<>]+/gu,SXe=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),CXe=/(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 AZ(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=xXe.test(t)||MZ(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 wXe(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function jZ(e){try{let t=new URL(e);return xne(t.hostname)}catch{return!1}}function MZ(e){return Sne(e)}function NZ(e){try{let t=new URL(e);if(t.protocol!==`http:`||!jZ(t.toString())&&!MZ(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 TXe(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 EXe(e){return e.replace(SXe,``).replaceAll(/./gsu,e=>DXe(e)?``:e).replace(CXe,`$1$2`)}function DXe(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function PZ(e){let t=null,n=null,r=EXe(e);kZ.lastIndex=0;for(let e of r.matchAll(kZ)){let r=AZ(TXe(e[0]));!r||!NZ(r)||(t=r,jZ(r)&&(n=r))}return n??t}function OXe(e){let t=null;for(let n of e){let e=n.event,r=PZ(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function kXe(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var AXe=`forge:terminal-state:v1`,FZ=[],jXe=200,IZ=8;function MXe(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:KZ(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!Ko(e)&&typeof t?.url==`string`&&!!NZ(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function NXe(){return hJ(typeof window<`u`?window.localStorage:void 0)}function PXe(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[$q]}function FXe(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 LZ(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 zZ(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function IXe(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function LXe(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=IXe(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():LZ(e[0]??`default`);i.push({id:RZ(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:RZ(LZ(e),a),terminalIds:[e]});return i.length===0?[{id:LZ($q),terminalIds:[$q]}]:i}function BZ(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 RXe(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||!BZ(r.terminalIds,i.terminalIds))return!1}return!0}function VZ(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&BZ(e.terminalIds,t.terminalIds)&&BZ(e.runningTerminalIds,t.runningTerminalIds)&&RXe(e.terminalGroups,t.terminalGroups)}var HZ=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[$q],runningTerminalIds:[],activeTerminalId:$q,terminalGroups:[{id:LZ($q),terminalIds:[$q]}],activeTerminalGroupId:LZ($q)});function UZ(){return{...HZ,terminalIds:[...HZ.terminalIds],runningTerminalIds:[...HZ.runningTerminalIds],terminalGroups:eQ(HZ.terminalGroups)}}function WZ(){return HZ}function GZ(e){let t=PXe(e.terminalIds),n=t.length>0?t:[$q],r=FXe(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=LXe(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??LZ(`default`)};return VZ(e,c)?e:c}function zXe(e){let t=GZ(e);if(t.terminalIds.length<=IZ)return t;let n=new Set,r=e=>{!e||n.size>=IZ||t.terminalIds.includes(e)&&n.add(e)};r($q),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 GZ({...t,terminalIds:i.length>0?i:[$q],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 KZ(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>Ko(e)?[[e,zXe(t)]]:[]))}function BXe(e){return VZ(GZ(e),HZ)}function VXe(e){return e.trim().length>0}function qZ(e){return Uo(e)}function JZ(e,t){return`${qZ(e)}\u0000${t}`}function YZ(e,t){return JZ(e,t)}function XZ(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function ZZ(e,t){let n=PZ(e);return n?{url:n,observedAt:t}:null}function HXe(e){return ZZ(e.history,e.updatedAt)}function QZ(e){return e.type===`output`?ZZ(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?ZZ(e.snapshot.history,e.snapshot.updatedAt):null}function $Z(e,t,n){if(!n)return e;let r=qZ(t),i=e[r];return i&&XZ(i.observedAt)>XZ(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function eQ(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function tQ(e,t,n,r){let i=JZ(n,r.terminalId),a=e[i]??FZ,o={id:t,event:r},s=a.length>=jXe?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function nQ(e,t,n,r){let i=JZ(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function rQ(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function iQ(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function aQ(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 UXe(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function WXe(e,t){let n=UXe(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 oQ(e,t,n){let r=GZ(e);if(!VXe(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=eQ(r.terminalGroups),s=zZ(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(LZ(t),e);return o.push({id:n,terminalIds:[t]}),GZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=zZ(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=RZ(LZ(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 GZ({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function sQ(e,t){let n=GZ(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function GXe(e,t){let n=GZ(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function KXe(e,t){return oQ(e,t,`split`)}function cQ(e,t,n){let r=oQ(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function lQ(e,t){let n=GZ(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 qXe(e,t){let n=GZ(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return UZ();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??LZ(a);return GZ({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function uQ(e,t,n){let r=GZ(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 dQ(e,t){return!t||t.threadId.length===0?WZ():e[qZ(t)]??WZ()}function fQ(e,t,n){if(t.threadId.length===0)return e;let r=qZ(t),i=dQ(e,t),a=n(i);if(a===i)return e;if(BXe(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function JXe(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?FZ:e[JZ(t,n)]??FZ}function YXe(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[YZ(t,n)]??null}function XXe(e,t){if(!t||t.threadId.length===0)return[];let n=`${qZ(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function ZXe(e,t){return!t||t.threadId.length===0?null:e[qZ(t)]??null}var pQ=Kt()(cJ(e=>{let t=(t,n)=>{e(e=>{let r=fQ(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=>sQ(e,n)),setTerminalHeight:(e,n)=>t(e,e=>GXe(e,n)),splitTerminal:(e,n)=>t(e,e=>KXe(e,n)),newTerminal:(e,n,r)=>t(e,e=>cQ(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=cQ(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=lQ(t,n)),r?.open&&(t=sQ(t,!0)),GZ(t)}),setActiveTerminal:(e,n)=>t(e,e=>lQ(e,n)),closeTerminal:(e,n)=>t(e,e=>qXe(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[qZ(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=qZ(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>uQ(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=YZ(t,n.terminalId),i=rQ(n),a=n.type===`started`||n.type===`restarted`;if(iQ(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?nQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):tQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=$Z(e.terminalPreviewUrlByThreadKey,t,QZ(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[YZ(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=qZ(t),i=YZ(t,n.terminalId),a=rQ(n),o=n.type===`started`||n.type===`restarted`;if(iQ(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=$Z(e.terminalPreviewUrlByThreadKey,t,QZ(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[YZ(t,n.terminalId)]:n.snapshot},s=fQ(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=cQ(r,n.terminalId)),t?(r=lQ(r,n.terminalId),r=sQ(r,!0)):(r=lQ(r,e.activeTerminalId),r=sQ(r,e.terminalOpen)),GZ(r)}),c={...c,[r]:WXe(c[r],n)});let d=kXe(n);d!==null&&(s=fQ(s,t,e=>uQ(e,n.terminalId,d)));let f=o&&a?nQ(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):tQ(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,[YZ(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:$Z(e.terminalPreviewUrlByThreadKey,t,HXe(n))})),clearTerminalState:t=>e(e=>{let n=qZ(t),r=fQ(e.terminalStateByThreadKey,t,()=>UZ()),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=aQ(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=qZ(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=aQ(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:AXe,version:4,storage:oJ(NXe),migrate:MXe,partialize:e=>({terminalStateByThreadKey:KZ(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function QXe(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 $Xe(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 mQ(e){let t=QXe(e).trim()||`Unknown browser error.`,n=$Xe(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 eZe(e){let t=mQ(e);return`${t.cause} ${t.nextAction}`}function tZe(e){let t=mQ(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var hQ={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function gQ(e){return Uo(e)}function nZe(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 rZe(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function _Q(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!nZe(t.display)||!rZe(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 iZe(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 vQ(e,t,n){return e[t]===n?e:{...e,[t]:n}}function aZe(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 oZe(e,t){let n=aZe(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 sZe(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 yQ(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function cZe(e,t){let n=yQ(t);return e.some(e=>yQ(e)===n)?e:[...e,t]}function lZe(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 uZe(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 dZe(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 fZe(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 pZe(e,t){let n=t.payload.tabId,r=jce(fZe(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 mZe(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function hZe(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 gZe(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!dZe(t,n))return i;let o=pZe(t,n);if(!o.decision.observe)return i;let s=mZe(t,n,o),c=o.decision.accept?hZe(s,n):s;return{browserStateByThreadKey:vQ(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var bQ=Kt(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=gQ(t),i=e.browserStateByThreadKey[r]??hQ,a=n?_Q({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:vQ(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=gQ(t),i=e.browserStateByThreadKey[r]??hQ,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=gQ(t),i=sZe(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=oZe(e.browserStateByThreadKey[r]??hQ,n);switch(n.type){case`session.started`:{if(iZe({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=_Q({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:vQ(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=_Q({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:vQ(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:vQ(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:lZe(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:uZe({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:vQ(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:vQ(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:vQ(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:vQ(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:vQ(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 gZe({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:vQ(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:vQ(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:cZe(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:vQ(e.browserStateByThreadKey,r,{...a,lastError:tZe(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=gQ(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 _Ze(e,t){return t?e[gQ(t)]??null:null}var vZe={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function yZe(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 bZe(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function xZe(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}var xQ=`forge:ui-state:v1`,SQ=[`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`],CQ=`months`,SZe=new Set([`weeks`,`months`,`quarters`]);function CZe(e){return typeof e==`string`&&SZe.has(e)?e:CQ}function wQ(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var TQ={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:CQ,projectLeadCompanion:vZe},EQ=new Set,DQ=[],OQ=new Map,kQ=!1;function wZe(){if(typeof window>`u`)return TQ;try{let e=window.localStorage.getItem(xQ);if(!e){for(let e of SQ){let t=window.localStorage.getItem(e);if(t)return AQ(JSON.parse(t)),TQ}return TQ}let t=JSON.parse(e);return AQ(t),{...TQ,projectGroupOrder:TZe(t.projectGroupOrderKeys),threadChangedFilesExpandedById:OZe(t.threadChangedFilesExpandedById),pinnedThreadById:EZe(t.pinnedThreadKeys),threadLinkedPrById:DZe(t.threadLinkedPrById),timelineWorkColumnWidth:wQ(t.timelineWorkColumnWidth??360),timelineScale:CZe(t.timelineScale)}}catch{return TQ}}function TZe(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function EZe(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 DZe(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 OZe(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 AQ(e){EQ.clear(),DQ.length=0;for(let t of e.expandedProjectCwds??[])typeof t==`string`&&t.length>0&&EQ.add(t);for(let t of e.projectOrderCwds??[])typeof t==`string`&&t.length>0&&!DQ.includes(t)&&DQ.push(t)}function kZe(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=OQ.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=OQ.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(xQ,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})),!kQ){kQ=!0;for(let e of SQ)window.localStorage.removeItem(e)}}catch{}}var jQ=new Yt(kZe,{wait:500});function MQ(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 NQ(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function AZe(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)||!MQ(r,t[e]))return!1;return!0}function jZe(e,t){let n=new Map(OQ),r=new Map([...n.entries()].map(([e,t])=>[t,e]));OQ.clear();for(let e of t)OQ.set(e.key,e.cwd);let i=n.size!==OQ.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(DQ.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)??(EQ.size>0?EQ.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)??DQ.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 MQ(e.projectExpandedById,a)&&NQ(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function MZe(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 MQ(e.threadLastVisitedAtById,r)&&AZe(e.threadChangedFilesExpandedById,i)&&MQ(e.pinnedThreadById,a)&&MQ(e.threadLinkedPrById,o)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o}}function NZe(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 PZe(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 FZe(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 PQ(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 IZe(e,t){return PQ(e,t,e.pinnedThreadById[t]!==!0)}function LZe(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function RZe(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function zZe(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}function BZe(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function VZe(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function HZe(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function UZe(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function WZe(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 GZe(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 NQ(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function KZe(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 FQ=Kt(e=>({...wZe(),syncProjects:t=>e(e=>jZe(e,t)),syncProjectGroups:t=>e(e=>GZe(e,t)),syncThreads:t=>e(e=>MZe(e,t)),markThreadVisited:(t,n)=>e(e=>NZe(e,t,n)),markThreadUnread:(t,n)=>e(e=>PZe(e,t,n)),clearThreadUi:t=>e(e=>FZe(e,t)),setThreadPinned:(t,n)=>e(e=>PQ(e,t,n)),toggleThreadPinned:t=>e(e=>IZe(e,t)),setThreadLinkedPr:(t,n)=>e(e=>LZe(e,t,n)),clearThreadLinkedPr:t=>e(e=>RZe(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>zZe(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>VZe(e,t,n)),toggleProject:t=>e(e=>HZe(e,t)),setProjectExpanded:(t,n)=>e(e=>UZe(e,t,n)),reorderProjects:(t,n)=>e(e=>WZe(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>KZe(e,t,n)),setLastActiveProject:t=>e(e=>BZe(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:wQ(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:bZe(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 qZe(e){FQ.getState().openProjectLeadCompanion(e)}FQ.subscribe(e=>jQ.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{jQ.flush()});var JZe=xt(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),YZe=class extends Ot()(`effect/http/FetchHttpClient/RequestInit`){},XZe=Kre(et(Ure((e,t,n,r)=>{let i=r.getRef(JZe),a=r.context.mapUnsafe.get(YZe.key)??{},o=a.headers?en(vn(a.headers),e.headers):e.headers,s=r=>Ze(Pee({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new En({reason:new nne({request:e,cause:t})})}),t=>Hte(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 bt(dte(e.body.stream),s)}return s(void 0)}))),ZZe=ste.pipe(S,It(e=>{if(Qn(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=Oee(e.reason.response.headers[`retry-after`]).pipe(See(Ore),ute(()=>5));return et(A(t))}return et(A(1))})),QZe=Xe(function*(e){let t=yield*Tt(),n=At(t,Dre),r=At(t,je),i=He(t),o=p(Me(e.exportInterval),mee),s,c=Vre(At(t,Hi)).pipe(Ui(De(Ki,!1)),Wre({schedule:ZZe,times:3})),l=sr({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(l=en(vn(e.headers),l));let d=Mre(e.url,{headers:l}),f=[],m=Dt(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return rt;s!==void 0&&(s=void 0);let t=f;if(e.maxBatchSize!==`disabled`){if(f.length===0)return rt;f=[]}return c.execute(Bi(d,e.body(t))).pipe(dee,kee(!1))}).pipe(Ue(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,f=[],Tee(`Disabling exporter for 60 seconds`,e)):rt),u({package:`@effect/opentelemetry`,module:e.label}));return yield*zt(r,m.pipe(wt,st,Kee(e.shutdownTimeout))),yield*a(o).pipe(Rt(m),Qe,Mt(r)),{push(t){s===void 0&&(f.push(t),e.maxBatchSize!==`disabled`&&f.length>=e.maxBatchSize&&fe(i(m),r))}}}),$Ze=e=>{let t=e.attributes?IQ(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}},eQe=Xe(function*(e){let t={...yield*Ml(Ln(Nl(Gn,Gn)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*Ml(Gn,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*Ml(Ln(Gn),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],$Ze({serviceName:n,serviceVersion:r,attributes:t})},l),tQe=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},IQ=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:LQ(r)});return t},LQ=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(LQ)}};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:i(e)}}},RQ=class extends Ot()(`effect/observability/OtlpSerialization`){},nQe=pe(RQ,{traces:e=>fn(e),metrics:e=>fn(e),logs:e=>fn(e)}),rQe=Xe(function*(e){let t=yield*eQe(e.resource),n=yield*RQ,r={name:tQe(t)},i=yield*QZe({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??A(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??A(3)});function a(e){e.sampled&&i.push(oQe(e))}return ye({span(e){return aQe({...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})}),iQe={_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)}},aQe=e=>{let t=Object.assign(Object.create(iQe),e);return t.traceId=x(t.parent)?t.parent.value.traceId:zQ(32),t.spanId=zQ(16),t.events=[],t},zQ=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},oQe=e=>{let t=e.status,n=IQ(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?IQ(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=cQe;else if(ot(t.exit.cause))i={code:BQ.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=cte(t.exit.cause);if(i={code:BQ.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:o(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:sQe[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:IQ(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},BQ={Unset:0,Ok:1,Error:2},sQe={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},cQe={code:BQ.Ok},lQe=1e4,uQe={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":Ir?`electron`:`browser`,"service.version":ml}},dQe=Ee(XZe,nQe,pe(Gi,()=>!0)),VQ=null,HQ=null,UQ=null,WQ=null,GQ=0,KQ=Promise.resolve(),fQe=pe(Vee,ye({span(e){return VQ?.span(e)??new c(e)}}));function pQe(e={}){return e.exportIntervalMs===void 0&&WQ!==null||(KQ=KQ.finally(()=>mQe(e))),KQ}async function mQe(e){let t=hr(`/api/observability/v1/traces`),n=fr()?.bearerToken,r=Math.max(10,e.exportIntervalMs??lQe),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(WQ===i&&VQ!==null)return;WQ=i;let a=++GQ,o=HQ,s=UQ;VQ=null,HQ=null,UQ=null,await qQ(o,s);let c=al(dQe),l=c.runSync(Re());try{let e=await c.runPromise(ee(l)(rQe({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:uQe})));if(a!==GQ){await qQ(c,l);return}VQ=e,HQ=c,UQ=l}catch(e){await qQ(c,l),a===GQ&&console.warn(`Failed to configure client tracing exporter`,{error:hQe(e),otlpTracesUrl:t})}}async function qQ(e,t){e!==null&&t!==null&&await e.runPromise(Be(t,St)).catch(()=>void 0).finally(()=>{e.dispose()})}function hQe(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var JQ=15e3,YQ=new Map,XQ=Wt([]).pipe(Ut,Vt(`slow-rpc-ack-requests`));function ZQ(e){Ht.set(XQ,[...e])}function QQ(){return Ht.get(XQ)}var $Q=`global`;function gQe(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)}function _Qe(e,t,n=$Q){if(!gQe(t))return;n$(e,n),xQe();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:JQ},a=t$(n,e),o=setTimeout(()=>{YQ.delete(a),bQe(i)},JQ);YQ.set(a,{request:i,timeoutId:o})}function vQe(e,t=$Q){n$(e,t);let n=QQ();n.some(n=>n.clientId===t&&n.requestId===e)&&ZQ(n.filter(n=>n.clientId!==t||n.requestId!==e))}function e$(e){for(let[t,n]of YQ)n.request.clientId===e&&(clearTimeout(n.timeoutId),YQ.delete(t));ZQ(QQ().filter(t=>t.clientId!==e))}function yQe(){for(let e of YQ.values())clearTimeout(e.timeoutId);YQ.clear(),ZQ([])}function t$(e,t){return`${e}:${t}`}function n$(e,t){let n=t$(t,e),r=YQ.get(n);r&&(clearTimeout(r.timeoutId),YQ.delete(n))}function bQe(e){let t=[...QQ(),e];if(t.length<=256){ZQ(t);return}ZQ(t.slice(-256))}function xQe(){for(;YQ.size>=256;){let e=YQ.keys().next().value;if(e===void 0)return;let t=YQ.get(e);if(!t)return;n$(t.request.requestId,t.request.clientId)}}function SQe(){return dr(XQ)}var CQe=jo(Wn),r$=1;function wQe(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function i$(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 TQe(){return{onAttempt:Ane,onOpen:jne,onError:e=>{Tne(e)},onClose:e=>{Mne(e)},trackGlobalConnection:!0}}function EQe(e){let t=TQe(),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 DQe(e,t){let n=r$;r$+=1;let r=EQe(t),i=typeof e==`function`?ft(()=>e()).pipe(Ze(e=>i$(e)),nte(e=>ct(()=>{r.onError(wQe(e))})),l):i$(e),a=pe(ca,(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=la(i).pipe(E(a)),s=It(y(10),e=>et(Ve(wne(e)??0)));return dt(Po,Ze(Fo({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`?vQe(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&e$(i),r(e))).pipe(Ke(ct(()=>{e$(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&_Qe(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(E(Ee(o,Ao)))}var OQe=Ve(250),a$=()=>void 0,o$=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=ze(Me(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},kQe=new Set([`OrchestrationGetSnapshotError`]);function AQe(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&kQe.has(t)}function jQe(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?MQe(e):String(e)}function MQe(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 NQe=4e3,PQe=1e4,FQe=500,s$=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??NQe,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??PQe,sessionCloseGraceMs:r?.sessionCloseGraceMs??FQe},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=Dt(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(jt({duration:o,orElse:()=>r(new o$(o))}));return await n.runtime.runPromise(s)}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:a$},i=ze(Me(n?.retryDelay??OQe));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=a$}catch(e){if(r.cancelCurrentStream=a$,!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=jQe(e);return kK(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await IQe(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){AQe(e)||BK(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=>{BK(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(Be(e.clientScope,St)),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:DQe(this.url,this.lifecycleHandlers),makeClient:CQe},t=al(Ee(e.layer,fQe)),n=t.runSync(Re());return{runtime:t,clientScope:n,clientPromise:t.runPromise(ee(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(ft(()=>e.clientPromise).pipe(bt(e=>qee(t(e),e=>ct(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if($ee(e)){a();return}o(Fe(e.cause))}}),completed:s}}};function IQe(e){return new Promise(t=>{setTimeout(t,e)})}var c$=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,LQe=/^[A-Za-z0-9_-]+$/;function RQe(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+=c$[o>>>18&63],t+=c$[o>>>12&63],n+1<e.byteLength&&(t+=c$[o>>>6&63]),n+2<e.byteLength&&(t+=c$[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function zQe(e){if(e.length===0||!LQe.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=c$.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 l$(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 BQe(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 ${pne}.`);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:RQe(a),sha256:await l$(a)})}return{totalBytes:e.byteLength,sha256:await l$(e),chunks:i}}async function VQe(e){let t=zQe(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 l$(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function HQe(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 VQe(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 l$(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var u$=`forge`,UQe=RegExp(`^${u$}\\/[0-9a-f]{8}$`);function WQe(){return`${u$}/${de(vte).replace(/-/g,``).slice(0,8).toLowerCase()}`}function GQe(e){return UQe.test(e.trim().toLowerCase())}function KQe(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 qQe(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 JQe(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 d$(e){return`https://${e}`}function YQe(e){return e===`github.com`||e.includes(`github`)}function XQe(e){return e===`gitlab.com`||e.includes(`gitlab`)}function ZQe(e){return e===`bitbucket.org`}function QQe(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function $Qe(e){let t=JQe(e);if(!t)return null;let n=KQe(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?YQe(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:d$(t)}:XQe(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:d$(t)}:ZQe(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:d$(t)}:QQe(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:d$(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:d$(t)}:null}var e$e={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function f$(e,t){return{...e,...t??e$e}}function t$e(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function n$e(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 r$e(e,t){switch(t._tag){case`snapshot`:return f$(t.local,t.remote);case`localUpdated`:return f$(t.local,e?t$e(e):null);case`remoteUpdated`:return f$(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:n$e(e),t.remote)}}var i$e=262144,a$e=250;function o$e(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function s$e(e){return new Promise(t=>setTimeout(t,e))}function c$e(e){let t=Tce({controllerId:crypto.randomUUID(),maxPendingWriteBytes:i$e}),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(!kK(o$e(e)))throw e;await s$e(a$e)}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()}}}var l$e=2e4,u$e=12e4,d$e=3e5;function f$e(e){return e instanceof o$||kK(e instanceof Error?e.message:String(e))}async function p$e(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?d$e:l$e,r=()=>e.request(e=>e[ln.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!f$e(t))throw t;return await e.reconnect(),await r()}}function p$(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function m$(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>m$e(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 HQe({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function m$e(e,t,n){if(e.protocolError===null){if(t.kind===`started`){h$e(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`){g$e(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function h$e(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 g$e(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 _$e(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${ane}-byte write limit.`);let i=await BQe(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{p$(n?.signal);let r=await v$e(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await y$e(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await b$e(e,a),t}}function v$e(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 y$e(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;p$(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[M.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}p$(i?.signal),await e.request(e=>e[M.workspaceCommitWriteFile]({transferId:t}))}}async function b$e(e,t){await e.request(e=>e[M.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}function h$(e){let t=c$e(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{Cne(),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))},projects:{searchEntries:t=>e.request(e=>e[M.projectsSearchEntries](t)),readFile:(t,n)=>m$(e,e=>e[M.workspaceReadFile](t),n),writeFile:(t,n)=>_$e(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[M.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[M.projectCheckoutDeletionExecute](t))},codeGraph:{summary:t=>e.request(e=>e[M.codeGraphSummary](t)),neighborhood:t=>e.request(e=>e[M.codeGraphNeighborhood](t)),search:t=>e.request(e=>e[M.codeGraphSearch](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=r$e(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:u$e})},orchestration:{dispatchCommand:t=>p$e(e,t),getTurnDiff:(t,n)=>m$(e,e=>e[ln.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>m$(e,e=>e[ln.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[ln.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[ln.subscribeThread](t),n,r)}}}var x$e=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function g$(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!x$e.has(t)?null:t}function _$(e,t){return e===401||e===403||g$(t)!==null}function S$e(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return _$(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}function C$e(e){return new Promise(t=>globalThis.setTimeout(t,e))}function v$(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function y$(e){if(e?.aborted)throw v$()}function w$e(e,t){return t?t.aborted?Promise.reject(v$()):new Promise((n,r)=>{let i=()=>r(v$());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function T$e(e,t){return t?t.aborted?Promise.reject(v$()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(v$())};t.addEventListener(`abort`,a,{once:!0})}):C$e(e)}var b$=`forge.deviceRegistry.deviceKey`,x$=`forge.deviceRegistry.runtimeId`;function E$e(e){let t=w$(b$,e.desktopIdentity?.deviceKey,`device`),n=w$(x$,e.desktopIdentity?.runtimeId,`runtime`),r=C$(e.desktopIdentity?.hostKey),i=A$e(),a=e.desktopAvailable?`desktop`:j$e(),o=e.desktopAvailable?k$e(e.desktopIdentity)??M$e(i):N$e(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 S$(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return E$e({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function C$(e){let t=e?.trim()??``;return t.length>0?t:null}function w$(e,t,n){let r=C$(t);return r?(bJ(e,r),r):O$e(e,n)}function D$e(){return yJ(x$)}function T$(){return yJ(b$)}function O$e(e,t){let n=yJ(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return bJ(e,r),r}function k$e(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function A$e(){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 j$e(){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 M$e(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function N$e(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var E$=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function D$(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new E$(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new E$(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function P$e(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 F$e(e){if(!e.deviceKey)throw new E$(`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 E$(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new E$(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function I$e(e,t){let n=async()=>F$e(await P$e(t));return{acquireRoute:async()=>{let r=await n(),i=await Sce();try{return wce({route:await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Yn],protocolMinVersion:4,protocolMaxVersion:4,...Cce(i)}),runtimeId:e,endpoint:i})}catch(e){if(e instanceof rl)throw new E$(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return D$(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 D$(e)}}}}var O$=`forge.relayControlJournal.v1`;function k$(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var L$e={read:()=>k$().getItem(O$),write:e=>k$().setItem(O$,e)},A$=null,j$=Kt()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function R$e(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));j$.getState().replace(Object.fromEntries([...t].map(t=>[t,Ise(e.records,t)])))})}function M$(){return A$===null&&(A$=Vc({storage:L$e}),R$e(A$)),A$}function z$e(){let e=(0,ul.c)(1),t=j$(V$e),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,F.useEffect)(B$e,n),t}function B$e(){M$()}function V$e(e){return e.byRuntimeId}function H$e(e){let t=M$();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 U$e=6e4;function W$e(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 G$e(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 K$e(e){let t=await fetch(hr(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),lr({method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})})),n=await t.json().catch(()=>null);if(!t.ok){let e=_$(t.status,n)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${t.status}).`;throw Object.assign(Error(W$e(n,e)),{status:t.status,...g$(n)?{code:g$(n)}:{}})}return G$e(n)}function q$e(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+U$e}function F$(e){let t=e.requestDescriptor??K$e,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=()=>i||(i=t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId}}).then(async t=>(await e.validateDescriptor?.(t),await e.persistDescriptor?.(t),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>e?.forceRefresh||a||q$e(r,n())?o():Promise.resolve(r),invalidate:()=>{a=!0}}}var J$e=12e4,Y$e=3e4,I$=3e4;function L$(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 X$e(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function Z$e(e){let t=e.now??Date.now,n=e.renewalSkewMs??J$e,r=!1,i=null,a=null,o=L$(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=L$(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()+I$;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},I$),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=L$(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=X$e(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()+Y$e?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}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=hX(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||Y$(t,e.record):t!==null&&Y$(t,e.registryExpectation.record)}var Q$e=9e5,Z$=32,Q$=()=>void 0;function $$(e,t){return Uo(zo(e,t))}function e1(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function $$e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=yZ(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=vZ(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&&!$$e(e)}function n1(e){if(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Q$)return!0;let t=M1(e.environmentId);return t?(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{if(e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`snapshot`){bZ.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),bZ.getState().clearThreadSubscriptionError(e.environmentId,e.threadId);return}C1e(t.event,e.environmentId)},{onError:t=>eXe(e.environmentId,e.threadId,t)}),!0):!1}function r1(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=j1(()=>{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$,a1e(),!0):!1}var a1=null;function e1e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=yZ(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=vZ(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function t1e(e){e.unsubscribe!==Q$&&(e.unsubscribe(),e.unsubscribe=Q$),n1(e)||r1(e)}function n1e(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`){t1e(e);return}M1(e.environmentId)?.reconnect().catch(t=>{BK(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 r1e(){let e=Date.now();for(let t of W$.values()){let n=vXe({isWorking:e1e(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:yXe,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&n1e(t,n,e-t.lastEventAt)}}function i1e(){a1===null&&(a1=setInterval(r1e,bXe))}function a1e(){W$.size>0||a1!==null&&(clearInterval(a1),a1=null)}function o1e(e){for(let[t,n]of W$)n.environmentId===e&&i1(t)}function s1e(e){let t=zo(e.environmentId,e.threadId),n=bZ.getState(),r=vZ(n,t);if(!r)return null;let i=yZ(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 c1e(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=s1e(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function l1e(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 u1e(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)))},Q$e))}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)&&u1e(e)}function d1e(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 f1e(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),i1e(),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 p1e(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],m1e=9e4;function h1e(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function g1e(e){if(S$e(e))return!1;let t=h1e(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 _1e(e){return f1[e]??f1[f1.length-1]}function v1e(){return m1e}function y1e(e,t){if(!UY(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}. The VM may still be starting.`))},v1e())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function p1(e){xX.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function m1(e){let t=u1();xX.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),dX.getState().markConnected(e,t)}function h1(e,t){xX.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function g1(e,t){xX.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:u1(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:u1()}:{}})}function _1(e,t){xX.getState().patch(e,{connectionState:`error`,...p1e(t)})}function b1e(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=pZ(bZ.getState());FQ.getState().syncProjects(e.map(e=>({key:Ho(Ro(e.environmentId,e.id)),cwd:e.cwd})))}function y1(){let e=mZ(bZ.getState());FQ.getState().syncThreads(e.map(e=>({key:Uo(zo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),bJe(e.map(e=>zo(e.environmentId,e.id)))}function x1e(){v1(),y1();let e=tXe({snapshotThreads:mZ(bZ.getState()).map(e=>({key:Uo(zo(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:zY.getState().listDraftThreadKeys()});pQ.getState().removeOrphanedTerminalStates(e)}function b1(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function S1e(e,t){if(e.length===0)return;let n=nXe(e),r=b1e(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()),bZ.getState().applyOrchestrationEvents(r,t),i){let e=pZ(bZ.getState());FQ.getState().syncProjects(e.map(e=>({key:Ho(Ro(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=mZ(bZ.getState());FQ.getState().syncThreads(e.map(e=>({key:Uo(zo(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=zY.getState();for(let e of n.promoteDraftThreadIds)BY(zo(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(zo(t,e)),FQ.getState().clearThreadUi(Uo(zo(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=zo(t,e);pQ.getState().removeTerminalState(n),bQ.getState().clearBrowserState(n)}c1(t)}function C1e(e,t){S1e([e],t)}function w1e(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?zo(t,n):null,i=r?vZ(bZ.getState(),r):void 0;switch(bZ.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:v1();return;case`thread-upserted`:y1(),!i&&r&&BY(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(pQ.getState().removeTerminalState(r),bQ.getState().clearBrowserState(r)),d1e(t,e.thread.id),o1();return;case`thread-removed`:r&&(i1(Uo(r)),zY.getState().clearDraftThread(r),FQ.getState().clearThreadUi(Uo(r)),pQ.getState().removeTerminalState(r),bQ.getState().clearBrowserState(r)),y1();return}}function T1e(e,t){return e.invalidateQueries({queryKey:wZ.all(t)})}function x1(e){return{onWelcome:(t,n)=>{e?.(t),G$&&T1e(G$.queryClient,n)},applyShellEvent:w1e,syncShellSnapshot:(e,t)=>{let n=c1e(e,t);bZ.getState().syncServerShellSnapshot(n,t),l1e(t,n.threads.map(e=>e.id)),c1(t),x1e()},applyTerminalEvent:(e,t)=>{let n=zo(t,an.make(e.threadId)),r=vZ(bZ.getState(),n),i=zY.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&pQ.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=zo(t,an.make(e.threadId)),r=vZ(bZ.getState(),n),i=zY.getState().getDraftThreadByRef(n)!==null;b1({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&bQ.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{_1(t,e)}}}function S1(){if(typeof window>`u`)return;let e=cr();if(e?.primaryMode===`cloud`&&e.bearerToken)return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function E1e(){if(typeof window>`u`)return;let e=cr(),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 D1e(e){let t=Gie(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return h$(new s$(async()=>{await mr().catch(()=>null);let e=S1();if(e)try{return await DZ({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})}catch(e){throw lq(e)&&_r(`ws-token`),e}return TGe(t)}))}function O1e(e){return h$(new s$(()=>DZ({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken}),{trackGlobalConnection:!1,onAttempt:()=>{p1(e.environmentId)},onOpen:()=>{m1(e.environmentId)},onError:t=>{xX.getState().patch(e.environmentId,{connectionState:`error`,lastError:t,lastErrorAt:u1()})},onClose:t=>{g1(e.environmentId,t.reason)}}))}function C1(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`)}function k1e(e){let t=e.runtimeId?.trim();if(t)return t;let n=WY(e.environmentId);if(!n)throw Error(`Saved Cloud environment ${e.environmentId} is missing its runtime id.`);return n}function A1e(e,t,n){let r=e;return F$({runtimeId:k1e(e),...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...t===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:t,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await EZ({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(n&&!n())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...I1(r),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:Kn(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:u1()};await _X(t),await yX(t.environmentId),dX.getState().upsert(t),r=t}})}function j1e(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 M1e(e,t,n){return n()&&xX.getState().ensure(e.environmentId),h$(new s$(async()=>{let n=await t.acquire(),r=t=>DZ({wsBaseUrl:t.wsBaseUrl,httpBaseUrl:t.httpBaseUrl,bearerToken:t.bearerToken,...UY(e.environmentId)?{runtimeTicket:t.bearerToken}:{}});try{return await r(n)}catch(n){if(!UY(e.environmentId)||!lq(n))throw n;return r(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&p1(e.environmentId)},onOpen:()=>{n()&&m1(e.environmentId)},onError:r=>{UY(e.environmentId)&&C1(r)&&t.invalidate?.(),n()&&xX.getState().patch(e.environmentId,{connectionState:`error`,lastError:r,lastErrorAt:u1()})},onClose:r=>{UY(e.environmentId)&&(r.code===1008||C1(r.reason))&&t.invalidate?.(),n()&&g1(e.environmentId,r.reason)}}))}async function w1(e,t,n,r,i,a,o){let s=await t.acquire(),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),EZ({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);if(!r())return!1;xX.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=hX(e.environmentId);return r()&&l.authenticated&&u&&dX.getState().upsert({...u,lastAuthenticatedPullRequestCapability:c.environment.capabilities?.pullRequests===!0}),!0}function T1(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 E1(e){let t=R$.get(e);return t?(R$.delete(e),o1e(e),l1(),await t.dispose(),!0):!1}function D1(){let e=Iq();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 T1(OZ({kind:`primary`,knownEnvironment:e,client:D1e(e),resolveEnvironmentId:()=>Iq()?.environmentId??e.environmentId,...r?{readiness:n?{bearerToken:n.bearerToken}:{}}:{},...x1()}))}async function N1e(e,t,n){let r=R$.get(e.environmentId);if(r)return r;let i=UY(e.environmentId),a=()=>X$({record:e,generation:t,registryExpectation:n?.registryExpectation??{kind:`existing-record`,record:e}}),o=i?n?.bearerToken:n?.bearerToken??await vX(e.environmentId);if(!i&&!o)throw a()&&xX.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 s=i?A1e(e,o??void 0,a):j1e({record:e,bearerToken:o}),c=await s.acquire();if(!a())throw Error(`Saved environment changed while its connection was being acquired.`);let l=n?.client??M1e(e,s,a),u=Io({id:e.environmentId,label:e.label,source:`manual`,target:{httpBaseUrl:c.httpBaseUrl,wsBaseUrl:c.wsBaseUrl}}),d=i&&c.expiresAt?Z$e({initialDescriptor:{httpBaseUrl:c.httpBaseUrl,wsBaseUrl:c.wsBaseUrl,bearerToken:c.bearerToken,expiresAt:c.expiresAt},renew:async()=>{let e=await s.acquire({forceRefresh:!0});return{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken,expiresAt:e.expiresAt??null}},onState:t=>{a()&&xX.getState().patch(e.environmentId,{providerAuthority:t})}}):null,f=OZ({kind:`saved`,knownEnvironment:{...u,environmentId:e.environmentId},client:l,readiness:{bearerToken:c.bearerToken},tolerateReportedEnvironmentIdentity:i,refreshMetadata:async()=>{await w1(e,s,l,a)},...d?{ensureProviderAuthority:d.ensureLive,onDispose:d.dispose}:{},onConfigSnapshot:t=>{a()&&xX.getState().patch(e.environmentId,{descriptor:t.environment,serverConfig:t})},...x1(t=>{a()&&xX.getState().patch(e.environmentId,{descriptor:t.environment})})});try{if(!await y1e(e.environmentId,w1(e,s,l,a,n?.role??null,n?.serverConfig??null,n?.signal))||!a())throw Error(`Saved environment changed while its connection was being acquired.`);return T1(f)}catch(t){throw a()&&_1(e.environmentId,t),await f.dispose().catch(()=>void 0),t}}async function O1(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=N1e(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 k1(e){await nX(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 P1(e)}))}function A1(){G$?.stop(),G$=null}function j1(e){return U$.add(e),()=>{U$.delete(e)}}function M1(e){return R$.get(e)??null}function P1e(e){let t=M1(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function N1(){return D1()}async function F1e(){let e=E1e();if(!e)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let t=await cXe({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return R$.get(t.environmentId)||T1(OZ({kind:`desktop-local`,knownEnvironment:{...Io({id:t.environmentId,label:e.label,source:`desktop-managed`,target:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}),environmentId:t.environmentId,label:t.label},client:O1e({environmentId:t.environmentId,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:e.bearerToken}),...x1()}))}async function I1e(e){let t=nn.make(e.runtimeId),n=R$.get(t);if(n)return n;p1(t);let r=M$(),i=I$e(e.runtimeId,{apiClient:oq,getStoredDeviceKey:T$,buildDeviceRegistration:S$,controlSessionId:r.controlSessionId}),a=await i.acquireRoute(),o=a,s=xce({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=h$(new s$(a.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:s,makeClient:bce(Yn)})),l=OZ({kind:`saved`,knownEnvironment:{...Io({id:t,label:e.label,source:`manual`,target:{httpBaseUrl:fr()?.target.httpBaseUrl??a.relayWebSocketUrl,wsBaseUrl:a.relayWebSocketUrl}}),environmentId:t},client:c,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>{h1(t,e)},...x1(e=>{xX.getState().patch(t,{descriptor:e.environment})})});try{let[,e]=await Promise.all([l.ensureBootstrapped(),c.server.getConfig()]);return h1(t,e),m1(t),T1(l)}catch(e){throw _1(t,e),await l.dispose().catch(()=>void 0),e}}function L1e(e){let t=nn.make(e.runtimeId),n=R$.get(t);if(n)return Promise.resolve(n);let r=z$.get(t);if(r)return r;let i=I1e(e).finally(()=>{z$.delete(t)});return z$.set(t,i),i}async function P1(e){R$.get(e)?.kind===`saved`&&(xX.getState().clear(e),await E1(e).catch(()=>!1))}function F1(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 R1e(e){let t=e.environmentId;B$.set(t,(B$.get(t)??0)+1);try{return M1(t)||await L1(e),!0}catch{return F1([t]),!1}}async function z1e(){await pX();let e=(await Promise.all(qJe().map(async e=>await R1e(e)?e.environmentId:null))).flatMap(e=>e===null?[]:[e]),t=!1;return()=>{t||(t=!0,F1(e))}}async function B1e(e){J$(e),dX.getState().remove(e),await yX(e),await P1(e)}function I1(e){let t=hX(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=xX.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}async function V1e(e){let t=nn.make(e.environment.environmentId),n=hX(t),{kind:r,cmmdOrganizationId:i,cmmdProjectId:a,runtimeId:o,runtimeTicketExpiresAt:s}=e.environment,c={environmentId:t,label:e.environment.label,wsBaseUrl:Kn(e.environment.wsBaseUrl),httpBaseUrl:e.environment.httpBaseUrl,createdAt:n?.createdAt??u1(),lastConnectedAt:u1(),...r===void 0?{}:{kind:r},...i===void 0?{}:{cmmdOrganizationId:i},...a===void 0?{}:{cmmdProjectId:a},...o===void 0?{}:{runtimeId:o},...s===void 0?{}:{runtimeTicketExpiresAt:s}};y$(e.signal);let l=mX(),u=n?await vX(c.environmentId):null;J$(c.environmentId),await E1(c.environmentId).catch(()=>!1),await L1(c,{bearerToken:e.bearerToken,registryExpectation:n?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}});let d=!1;try{return y$(e.signal),await _X(c),d=!0,y$(e.signal),await yX(c.environmentId),y$(e.signal),dX.getState().upsert(I1(c)),c}catch(t){throw await E1(c.environmentId).catch(()=>!1),u&&await YJe(c.environmentId,u),d&&await nX(l),y$(e.signal),t}}async function L1(e,t){if(!UY(e.environmentId))return O1(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){y$(t?.signal);try{let n=await O1(e,t);return await w$e(n.ensureBootstrapped(),t?.signal),n}catch(a){if(i=a,!r())throw a;if(await E1(e.environmentId).catch(()=>!1),y$(t?.signal),n>=7||!g1e(a))throw r()&&_1(e.environmentId,a),a;let o=_1e(n);t?.onBootstrapRetry?.({attempt:n+2,maxAttempts:d1,retryDelayMs:o,error:a}),r()&&xX.getState().patch(e.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await T$e(o,t?.signal)}}let a=i instanceof Error?i:Error(String(i));throw r()&&_1(e.environmentId,a),a}async function H1e(e){await R$.get(e)?.ensureBootstrapped()}async function U1e(e){let t=R$.get(e);if(!UY(e)){await t?.ensureProviderAuthority?.();return}if(!t?.ensureProviderAuthority)throw Error(`Cloud runtime provider authority is not available.`);await t.ensureProviderAuthority()}function W1e(e){if(G$?.queryClient===e)return G$.refCount+=1,()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&A1())};A1(),K$=!1;let t=new MKe(()=>{K$&&(K$=!1,e.invalidateQueries({queryKey:CZ.all}),e.invalidateQueries({queryKey:SZ.all}))},{wait:100,leading:!1,trailing:!0});D1(),mr().catch(()=>void 0);let n=dX.subscribe(()=>{fX()&&k1(mX())});return pX().then(()=>k1(mX())).catch(()=>void 0),G$={queryClient:e,queryInvalidationThrottler:t,refCount:1,stop:()=>{n(),t.cancel()}},()=>{!G$||G$.queryClient!==e||(--G$.refCount,G$.refCount===0&&A1())}}function R1(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var z1=Object.freeze({data:null,error:null,cause:null,isPending:!1}),B1=Object.freeze({...z1,isPending:!0}),G1e=Wt(z1).pipe(Ut,Vt(`git-status:null`)),V1=()=>void 0,H1=new Map,K1e=new Set,U1=new Map,W1=new Map,q1e=1e3,G1=hte(e=>(K1e.add(e),Wt(B1).pipe(Ut,Vt(`git-status:${e}`))));function K1(e){return e.environmentId===null||R1(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function q1(e){if(e.environmentId===null)return null;let t=M1(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function J1(e){let t=K1(e);return t===null?z1:Ht.get(G1(t))}function J1e(e,t){let n=K1(e);if(n===null)return V1;let r=H1.get(n);return r?(r.refCount+=1,()=>Y1(n)):(H1.set(n,{refCount:1,unsubscribe:Z1e(n,e,t)}),()=>Y1(n))}function Y1e(e,t){let n=K1(e),r=R1(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??q1(e)?.client;if(!i)return Promise.resolve(J1(e).data);let a=U1.get(n);if(a)return a;let o=W1.get(n)??0;if(Date.now()-o<q1e)return Promise.resolve(J1(e).data);W1.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{U1.delete(n)});return U1.set(n,s),s}function X1e(e){let t=(0,ul.c)(4),n=K1(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>J1e({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=dr(n===null?G1e:G1(n));return n===null?z1:a}function Y1(e){let t=H1.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),H1.delete(e)))}function Z1e(e,t,n){let r=R1(t.cwd);if(r===null)return V1;let i=null,a=V1,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:q1(t);if(!o){i!==null&&(a(),a=V1,i=null),X1(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=Q1e(e,r,o.client))},s=n?V1:j1(o);return o(),()=>{s(),a()}}function Q1e(e,t,n){return X1(e),n.onStatus({cwd:t},t=>{Ht.set(G1(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{X1(e)}})}function X1(e){let t=G1(e),n=Ht.get(t),r=n.data===null?B1:{...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 Z1(e,t){return Wt(t).pipe(Ut,Vt(e))}function Q1(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var $1e=[],e0e=[],t0e=[],n0e=e=>e?.availableEditors??$1e,r0e=e=>e?.keybindings??e0e,i0e=e=>e?.keybindingsConfigPath??null,a0e=e=>e?.observability??null,o0e=e=>e?.providers??t0e,s0e=e=>e?.settings??vne,$1=Z1(`server-welcome`,null),e0=Z1(`server-config`,null),t0=Z1(`server-config-updated`,null),c0e=Z1(`server-providers-updated`,null);function n0(){return Ht.get(e0)}function l0e(){return Ht.get(t0)}function r0(e){s0(e),c0({providers:e.providers}),l0(Q1(e),`snapshot`)}function u0e(e){switch(e.type){case`snapshot`:r0(e.config);return;case`keybindingsUpdated`:{let t=n0();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};s0(n),l0(Q1(n),e.type);return}case`providerStatuses`:i0(e.payload);return;case`settingsUpdated`:a0(e.payload.settings);return;case`environmentUpdated`:o0(e.payload.environment);return}}function i0(e){let t=n0();if(c0(e),!t)return;let n={...t,providers:e.providers};s0(n),l0(Q1(n),`providerStatuses`)}function a0(e){let t=n0();if(!t)return;let n={...t,settings:e};s0(n),l0(Q1(n),`settingsUpdated`)}function o0(e){let t=n0();if(Pq()?.environmentId===e.environmentId&&Fq(e),!t)return;let n={...t,environment:e};s0(n),l0(Q1(n),`environmentUpdated`)}function d0e(e){Ht.set($1,e)}function f0e(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&d0e(e.payload)}),e.subscribeConfig(e=>{u0e(e)})];return n0()===null&&e.getConfig().then(e=>{t||n0()!==null||r0(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var p0e=1;function s0(e){Ht.set(e0,e)}function c0(e){Ht.set(c0e,e)}function l0(e,t){Ht.set(t0,{id:p0e++,payload:e,source:t})}function u0(e,t){let n=(0,F.useRef)(t);n.current=t;let r=(0,F.useCallback)(e=>{e!==null&&n.current(e)},[]);bne(e,r,{immediate:!0})}function m0e(){return dr(e0)}function d0(){return dr(e0,s0e)}function h0e(){return dr(e0,o0e)}function g0e(){return dr(e0,r0e)}function _0e(){return dr(e0,n0e)}function v0e(){return dr(e0,i0e)}function y0e(){return dr(e0,a0e)}function b0e(e){u0($1,e)}function x0e(e){u0(t0,e)}function S0e(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 C0e(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 w0e(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 T0e(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 S0e(e)){if(n){i.appendChild(C0e(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=w0e({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 f0;function E0e(){return p0(N1().client)}function p0(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 o0(n.environment),n}}}function D0e(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 O0e(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):T0e(e,t)},persistence:{getClientSettings:$Y,setClientSettings:eX,getSavedEnvironmentRegistry:tX,setSavedEnvironmentRegistry:nX,getSavedEnvironmentSecret:rX,setSavedEnvironmentSecret:iX,removeSavedEnvironmentSecret:aX},server:p0(e)}}function m0(){if(typeof window>`u`)return;if(f0)return f0;let e=O0e(N1().client);return window.nativeApi?(f0=D0e(e,window.nativeApi),f0):(f0=e,f0)}function k0e(){let e=m0();if(!e)throw Error(`Local API not found`);return e}function h0(e,t){if(!Ne(e)||!Ne(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]=Ne(t)&&Ne(r)?h0(t,r):r}return n}var g0=`[CLIENT_SETTINGS]`,_0=new Set,v0=rr,y0=!1,b0=null;function A0e(){for(let e of _0)e()}function x0(){return v0}function S0(e){v0=e,A0e()}function j0e(e){return _0.add(e),M0e(),()=>{_0.delete(e)}}async function M0e(){if(y0)return;if(b0)return b0;let e=(async()=>{try{let e=await $Y();e&&S0(e)}catch(e){console.error(`${g0} hydrate failed`,e)}finally{y0=!0}})().finally(()=>{b0===e&&(b0=null)});return b0=e,b0}function N0e(e){S0(e),eX(e).catch(e=>{console.error(`${g0} persist failed`,e)})}var P0e=new Set(yne(Kte.fields));function F0e(e){let t={},n={};for(let[r,i]of Object.entries(e))P0e.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function C0(e){let t=d0(),n=(0,F.useSyncExternalStore)(j0e,x0,()=>rr),r=(0,F.useMemo)(()=>({...t,...n}),[n,t]);return(0,F.useMemo)(()=>e?e(r):r,[r,e])}function w0(){let e=(0,ul.c)(2),t=I0e,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(_ne)},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 I0e(e){let{serverPatch:t,clientPatch:n}=F0e(e);if(Object.keys(t).length>0){let e=n0();e&&a0(h0(e.settings,t)),N1().client.server.updateSettings(t)}Object.keys(n).length>0&&N0e({...x0(),...n})}function L0e(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var T0=new Map;function E0(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=T0.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,L0e(e,t));return T0.set(n,i),i}function R0e(e,t){return E0(t,!0).format(new Date(e))}function z0e(e,t){return E0(t,!1).format(new Date(e))}function D0(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 B0e(e){let t=D0(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}var V0e=[{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 H0e(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 U0e(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:H0e(r-n)}function O0(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function W0e(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?O0(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function k0(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 A0(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 G0e(e){let t=new Map,n=[...e].toSorted(J0);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?or.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?k0(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&&A0(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function K0e(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 q0e(e){let t=new Map,n=[...e].toSorted(J0);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?or.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=K0e(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&&A0(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function J0e(e,t){if(!t)return null;let n=[...e].toSorted(J0),r=null;for(let e of n){let t=M0(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 Y0e(e,t){let n=[...e].toSorted(J0),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&&J0(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 j0(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 z0(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?z0(n):null}function X0e(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 z0(n)}}return j0(t,e.latestTurn?.turnId??null)}function Z0e(e){return e!==null&&e.implementedAt===null}function Q0e(e,t){let n=$0e();return c2e([...e].toSorted(J0).filter(e=>!t||e.turnId===t||e2e(e)).filter(e=>e.kind!==`tool.started`).filter(e=>e.kind!==`task.started`).filter(e=>e.kind!==`context-window.updated`).filter(e=>e.summary!==`Checkpoint captured`).filter(e=>n||e.kind!==`runtime.warning`).filter(e=>!t2e(e)).map(n2e)).map(({activityKind:e,collapseKey:t,...n})=>n)}function $0e(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function e2e(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function t2e(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 n2e(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=C2e(t),r=k2e(t),i=w2e(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=D2e(t),d=O2e(t);if(!s&&t&&typeof t.detail==`string`&&t.detail.length>0){let e=G0(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=r2e(t);if(f)l.githubConfirmation=f,l.tone=`approval`,l.label=`GitHub action needs approval`,l.toolTitle=P0(f.operation),l.detail=F0(f);else{let e=M0(t);e&&(l.githubActionRequired=e,l.tone=`approval`,l.label=I0(e.action),l.toolTitle=`GitHub setup required`,l.detail=R0(e))}let p=f2e(l);return p&&(l.collapseKey=p),l}function r2e(e){for(let t of N0(e)){if(t.userActionRequired!==`confirm_github_tool`)continue;let e=B0(t.confirmation),n=B0(e?.request),r=V0(e?.confirmationId),i=V0(e?.toolName),a=V0(e?.operation);if(!(!r||!i||!a||!n))return{confirmationId:r,toolName:i,operation:a,request:n}}return null}function M0(e){let t=N0(e)[0];if(!t)return null;let n=V0(t.userActionRequired);return!n||n===`confirm_github_tool`?null:{action:n,toolName:V0(t.toolName),message:V0(t.error)??V0(t.message)}}function N0(e){if(!e)return[];let t=[],n=new Set,r=(e,i)=>{if(i>8||e==null)return;if(typeof e==`string`){let n=V0(e);if(!n)return;let r=i2e(n);r&&V0(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(V0(a.userActionRequired)){t.push(a);return}for(let e of Object.values(a))r(e,i+1)};return r(e,0),t}function i2e(e){try{return B0(JSON.parse(e))}catch{return null}}function P0(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 F0(e){return[V0(e.request.repoFullName)??(V0(e.request.owner)&&V0(e.request.name)?`${V0(e.request.owner)}/${V0(e.request.name)}`:null),V0(e.request.cwd),V0(e.request.branch),V0(e.request.title)].filter(Boolean).join(` - `)}function I0(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 L0(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 R0(e){return e.action===`connect_cmmd`?L0(e.action):e.message??L0(e.action)}function a2e(e,t){return e.action===t.action&&e.toolName===t.toolName&&e.message===t.message}function o2e(e){switch(e){case`connect_cmmd`:return`Reconnect Forge`;case`connect_github`:return`Connect GitHub`;default:return`Open Git settings`}}function s2e(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(`
1019
+ `)}function c2e(e){let t=[];for(let n of e){let e=t.at(-1);if(e&&l2e(e,n)){t[t.length-1]=u2e(e,n);continue}t.push(n)}return t}function l2e(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 u2e(e,t){let n=d2e(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 d2e(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function f2e(e){if(e.activityKind!==`tool.updated`&&e.activityKind!==`tool.completed`)return;let t=p2e(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 p2e(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}function z0(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function B0(e){return e&&typeof e==`object`?e:null}function V0(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function H0(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 m2e(e){let t=H0(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function h2e(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 g2e=[{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 _2e(e){return g2e.find(t=>t.executables.includes(e))}function v2e(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=H0(r);return i.length>0?i:null}function y2e(e){let t=h2e(e);if(!t||t.rest.length===0)return e;let n=m2e(t.executable);if(!n)return e;let r=_2e(n);return r?v2e(t.rest,r.wrapperFlagPattern)??e:e}function b2e(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function U0(e){let t=V0(e);if(t)return t;if(!Array.isArray(e))return null;let n=e.map(e=>V0(e)).filter(e=>e!==null);return n.length===0?null:n.map(e=>b2e(e)).join(` `)}function x2e(e){let t=U0(e);return t?y2e(t):null}function S2e(e,t){let n=U0(e);return!n||t===null||n===t?null:n}function C2e(e){let t=B0(e?.data),n=B0(t?.item),r=B0(n?.result),i=B0(n?.input),a=V0(e?.itemType),o=V0(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?G0(o).output:null];for(let e of s){let t=x2e(e);if(t)return{command:t,rawCommand:S2e(e,t)}}return{command:null,rawCommand:null}}function w2e(e){return T2e(e)??V0(e?.title)}function T2e(e){if(!e)return null;let t=B0(e.data),n=B0(t?.item),r=B0(n?.input)??B0(t?.input),i=V0(e.title),a=V0(e.itemType),o=V0(n?.name)??V0(n?.toolName)??V0(t?.name)??V0(e.toolName)??i,s=V0(e.detail),c=[o,i,a,s].filter(Boolean).join(` `).toLowerCase();if(!c.includes(`browser`)&&!c.includes(`forge-browser`))return null;switch(E2e(o,r,s)){case`open-session`:return`Opened browser session`;case`name-session`:return`Named browser session`;case`new-tab`:return W0(r)??`Opened browser tab`;case`navigate`:return W0(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 E2e(e,t,n){let r=[V0(t?.type)??V0(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 W0(e){let t=V0(e?.url)??V0(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 G0(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 D2e(e){if(typeof e?.itemType==`string`&&jte(e.itemType))return e.itemType}function O2e(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:k0(e?.requestType)??void 0}function K0(e,t,n){let r=V0(n);!r||t.has(r)||(t.add(r),e.push(r))}function q0(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(q0(i,t,n,r+1),t.length>=12)return;return}let i=B0(e);if(i){K0(t,n,i.path),K0(t,n,i.filePath),K0(t,n,i.relativePath),K0(t,n,i.filename),K0(t,n,i.newPath),K0(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(q0(i[e],t,n,r+1),t.length>=12))return}}function k2e(e){let t=[],n=new Set;return q0(B0(e?.data),t,n,0),t}function J0(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=Y0(e.kind)-Y0(t.kind);return r===0?e.id.localeCompare(t.id):r}function Y0(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 A2e(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}function j2e(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=M2e(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:F0(t),tone:`approval`,toolTitle:P0(t.operation),githubConfirmation:t}}]:[]});return[...r,...i,...a,...o].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function M2e(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=I2e(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=N2e(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 N2e(e,t,n){if(!P2e(e))return null;let r=F2e(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?V0(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function P2e(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 F2e(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 I2e(e,t){return t.exec(e)?.[1]??null}function L2e(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 R2e(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 z2e(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function B2e(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}function X0(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}:{},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:{searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},codeGraph:{summary:e.codeGraph.summary,neighborhood:e.codeGraph.neighborhood,search:e.codeGraph.search},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 Z0(e){if(typeof window>`u`||!e)return;let t=M1(e);return t?X0(t.client):void 0}function V2e(e){let t=(0,ul.c)(4),n;t[0]===e?n=t[1]:(n=()=>M1(e),t[0]=e,t[1]=n);let r=(0,F.useSyncExternalStore)(j1,n,H2e),i,a;return t[2]===r?a=t[3]:(a=r?X0(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function H2e(){return null}function U2e(e){let t=Z0(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}function W2e(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=Zt(i),[,o]=F.useState(!1),s=qt(K2e).current,c=qt(G2e).current,l=F.useRef(0),u=F.useRef(!0),d=F.useRef([]),f=F.useRef(null),p=Zt(()=>{u.current||(u.current=!0,o(e=>!e))}),m=Zt((e,t)=>{c.set(e,t),p()}),h=Zt(e=>{c.delete(e),p()}),g=Zt(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(!Y2e(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&Q0(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=J2e(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=Zt(()=>{let[e,t]=q2e(c),n=g(e);_(t),d.current=e,u.current=!1,s.forEach(e=>e(n)),a(n)});Xt(()=>(u.current||g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),Xt(()=>{u.current&&v()}),Xt(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=Zt(e=>(s.add(e),()=>{s.delete(e)})),b=F.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,Fr.jsx)(Ste.Provider,{value:b,children:t})}function G2e(){return new Map}function K2e(){return new Set}function q2e(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)=>Q0(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 J2e(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function Y2e(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 Q0(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var $0=[`preview`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`graph`,`pull-request`],e2={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function t2(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function X2e(e,t,n){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n}}function n2(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 r2(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var Z2e=`workspace:pull-requests`;function i2(e){return typeof e==`object`&&!!e}function Q2e(e){return typeof e==`string`&&$0.includes(e)}function a2(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function $2e(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function e4e(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:a2(e.revealLine),revealRequestId:$2e(e.revealRequestId)}}function t4e(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 n4e(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?_n.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var r4e=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function o2(e){return typeof e==`string`&&e.length>0}function s2(e){return e===null||typeof e==`string`}function i4e(e){return e===void 0||s2(e)}function a4e(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=a2(e.number),c=e.title;return![o2(t)&&r4e.has(t),o2(n),s2(r),o2(i),o2(a),o2(o),s!==null,i4e(c)].every(Boolean)||!o2(t)||!o2(n)?null:n2({provider:t,environmentId:nn.make(n),repositoryLinkId:r,projectId:sn.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function o4e(e){if(!i2(e)||!Q2e(e.kind))return null;let t=e.kind;return t===`file`?e4e(e):t===`preview`?t4e(e):t===`diff`?n4e(e):t===`pull-request`?a4e(e):{id:t,kind:t}}function s4e(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=o4e(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function c4e(e){if(!i2(e))return null;let t=s4e(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 l4e(e){if(!i2(e)||!i2(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===Z2e)continue;let e=c4e(r);e&&(t[n]=e)}return{byThreadKey:t}}var u4e=`forge:right-panel-state`,d4e=3,f4e=e=>e===`workspace:pull-requests`;function p4e(e){return`draft:${e}`}function m4e(e){return e.startsWith(`draft:`)}function h4e(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var c2=(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}),l2=(e,t,n)=>{let r=e[t]??e2,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}},g4e=Kt()(cJ(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,e.surfaces.find(e=>e.kind===n)??r2(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return c2({...e,surfaces:t},t2(n))})})),revealBrowser:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,e.surfaces.find(e=>e.kind===`preview`)??t2(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:l2(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)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>{let t=`file:${n}`,i=e.surfaces.find(e=>e.id===t&&e.kind===`file`),a=X2e(n,h4e(r),(i?.revealRequestId??0)+1);return{...e,isOpen:!0,activeSurfaceId:a.id,surfaces:i?e.surfaces.map(e=>e.id===a.id?a:e):[...e.surfaces,a]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>c2(e,n2(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:l2(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:l2(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:l2(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:l2(e.byThreadKey,t,()=>e2)})),show:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:l2(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:l2(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:u4e,version:d4e,storage:oJ(()=>vJ),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!m4e(e)&&!f4e(e)))}),migrate:e=>l4e(e)}));function _4e(e){return t=>e?fZ(t,e.environmentId).projectById[e.projectId]:void 0}function u2(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=fZ(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=AX(o,a.threadId),r)}}function v4e(e){return u2(()=>e)}function y4e(e){return t=>{if(e)return fZ(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function b4e(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=fZ(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 x4e(e){return u2(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 d2=`forge:last-editor`;function f2(e){let t=new Set(e),n=qq(d2,Bn);if(n&&t.has(n))return n;let r=zte.find(e=>t.has(e.id))?.id??null;return r&&Jq(d2,r,Bn),r??null}async function S4e(e,t){let{availableEditors:n}=await e.server.getConfig(),r=f2(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}var C4e=/https?:\/\/[^\s"'`<>]+/g,w4e=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,T4e=/[.,;!?]+$/;function E4e(e){let t=e.replace(T4e,``);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 D4e(e,t){return e.start<t.end&&t.start<e.end}function p2(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=E4e(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=>D4e(s,e))||i.push(s)}return i}function m2(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function O4e(e){return e.startsWith(`/`)||m2(e)}function h2(e){return m2(e)||/[A-Za-z]:\\/.test(e)}function g2(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function k4e(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 _2(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 A4e(e){let t=p2(e,`url`,C4e,[]),n=p2(e,`path`,w4e,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function j4e(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 v2(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 M4e(e,t){return{start:v2(e.segments,t.start),end:v2(e.segments,t.end-1)}}function N4e(e,t){return e.start.y<=t&&t<=e.end.y}function P4e(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:yte(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function F4e(e,t){let{path:n,line:r,column:i}=_2(e),a=n;if(n.startsWith(`~/`)){let e=k4e(t);if(e){let t=h2(e)?`\\`:`/`;a=g2(e,n.slice(2),t)}}else O4e(n)||(a=g2(t,n,h2(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var y2=`diffs-container`,I4e=(()=>{try{return!1}catch{return!1}})(),L4e=/(?=^From [a-f0-9]+ .+$)/m,R4e=/(?=^diff --git)/gm,z4e=/(?<=\n)/,B4e=/^(---|\+\+\+)\s+([^\t\r\n]+)/,V4e=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,H4e=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,U4e=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,b2=`header-prefix`,x2=`header-filename-suffix`,S2=`header-metadata`,C2=`header-custom`,w2={dark:`pierre-dark`,light:`pierre-light`},W4e=`data-theme-css`,G4e=`data-unsafe-css`,K4e=`data-diffs-scrollbar-measure`,q4e=`data-diffs-code-view-header`,J4e=`data-diffs-code-view-footer`,T2=`--diffs-scrollbar-gutter-measured`,Y4e=1e5,E2={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},X4e={...E2,hunkLineCount:1},Z4e={paddingTop:8,paddingBottom:8,gap:8},Q4e={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},$4e=Object.freeze({fromStart:0,fromEnd:0}),e3e={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},t3e={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},D2=new Set,O2=null;function k2(e){D2.add(e),O2??=requestAnimationFrame(j2)}function A2(e){D2.delete(e)&&D2.size===0&&O2!=null&&(cancelAnimationFrame(O2),O2=null)}function j2(e){let t=new Set(D2);D2.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}O2=D2.size>0?requestAnimationFrame(j2):null}function M2(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 N2(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function n3e(e,t){let n=e?.theme??w2,r=t?.theme??w2,i=P2(e),a=P2(t);return N2(n,r)&&M2(e,t,[`theme`,`parseDiffOptions`])&&M2(i,a)}function P2(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function F2(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function r3e({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 I2(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function L2(e,t){return e-(t===0?0:1)}function R2(e,t){return L2(e,t)+t}var z2=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}},i3e=new class extends z2{};function a3e(e,t,n){return i3e.diff(e,t,n)}function B2(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 V2(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 H2(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 U2(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 W2(e,t){return H2(e,t,``)}function G2(e,t){return U2(e,t,``)}function K2(e,t){return t.slice(0,o3e(e,t))}function o3e(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 q2(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 J2(e,t){if(t)return X2(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Y2(e,t){if(t)return X2(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function X2(e,t){if(!t)return[Y2(e),J2(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=q2(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var Z2=`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}`,s3e=RegExp(`[${Z2}]+|\\s+|[^${Z2}]`,`ug`);new class extends z2{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=q2(e,r)}else n=e.match(s3e)||[];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)&&Q2(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&Q2(n,i,r,null,t.intlSegmenter),e}};function Q2(e,t,n,r,i){if(t&&n){let[a,o]=X2(t.value,i),[s,c]=X2(n.value,i);if(e){let r=B2(a,s);e.value=U2(e.value,s,r),t.value=W2(t.value,r),n.value=W2(n.value,r)}if(r){let e=V2(o,c);r.value=H2(r.value,c,e),t.value=G2(t.value,e),n.value=G2(n.value,e)}}else if(n){if(e){let e=Y2(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Y2(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Y2(r.value,i),[a,o]=X2(t.value,i),s=B2(n,a);t.value=W2(t.value,s);let c=V2(W2(n,s),o);t.value=G2(t.value,c),r.value=H2(r.value,n,c),e.value=U2(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Y2(r.value,i),n=K2(J2(t.value,i),e);t.value=G2(t.value,n)}else if(e){let n=K2(J2(e.value,i),Y2(t.value,i));t.value=W2(t.value,n)}}var c3e=new class extends z2{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Z2}]+|[^\\S\\n\\r]+|[^${Z2}]`,`ug`);return e.match(t)||[]}};function l3e(e,t,n){return c3e.diff(e,t,n)}var u3e=new class extends z2{constructor(){super(...arguments),this.tokenize=e4}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
1020
1020
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
1021
1021
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
1022
1022
  `)&&(e=e.slice(0,-1)),t.endsWith(`
1023
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function $2(e,t,n){return s3e.diff(e,t,n)}function e4(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
1024
- `));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 c3e(e){return e==`.`||e==`!`||e==`?`}new class extends z2{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(c3e(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 z2{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends z2{constructor(){super(...arguments),this.tokenize=e4}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(t4(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 t4(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]=t4(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]=t4(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends z2{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function l3e(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function n4(e){if(!l3e(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 r4={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function i4(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;$2(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l($2(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||d3e(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(`
1023
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function $2(e,t,n){return u3e.diff(e,t,n)}function e4(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
1024
+ `));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 d3e(e){return e==`.`||e==`!`||e==`?`}new class extends z2{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(d3e(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 z2{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends z2{constructor(){super(...arguments),this.tokenize=e4}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(t4(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 t4(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]=t4(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]=t4(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends z2{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function f3e(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function n4(e){if(!f3e(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 r4={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function i4(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;$2(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l($2(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||m3e(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(`
1025
1025
  `)?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 a4(e,t){if(t||=r4,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=>a4(e,t)).join(`
1026
1026
  `)}let n=[];if(e.isGit){if(t=r4,!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 `+n4(r)+` `+n4(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 `+n4((e.oldFileName??``).replace(/^a\//,``))),n.push(`rename to `+n4((e.newFileName??``).replace(/^b\//,``)))),e.isCopy&&(n.push(`copy from `+n4((e.oldFileName??``).replace(/^a\//,``))),n.push(`copy to `+n4((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(`--- `+n4(e.oldFileName)+(e.oldHeader?` `+e.oldHeader:``)),n.push(`+++ `+n4(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(`
1027
1027
  `)+`
1028
- `}function u3e(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;i4(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?a4(e,o.headerOptions):void 0)}}))}else{let s=i4(e,t,n,r,i,a,o);return s?a4(s,o?.headerOptions):void 0}}function d3e(e){let t=e.endsWith(`
1028
+ `}function p3e(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;i4(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?a4(e,o.headerOptions):void 0)}}))}else{let s=i4(e,t,n,r,i,a,o);return s?a4(s,o?.headerOptions):void 0}}function m3e(e){let t=e.endsWith(`
1029
1029
  `),n=e.split(`
1030
1030
  `).map(e=>e+`
1031
- `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function o4(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 l4({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 f3e(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 p3e(e){return c4({tagName:`div`,properties:{"data-gutter":``},children:e})}function m3e(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 h3e(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 g3e(){return c4({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[l4({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function _3e(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function u4(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`],f4=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};f4.prototype.normal={},f4.prototype.property={},f4.prototype.space=void 0;function p4(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new f4(n,r,t)}function m4(e){return e.toLowerCase()}var h4=class{constructor(e,t){this.attribute=t,this.property=e}};h4.prototype.attribute=``,h4.prototype.booleanish=!1,h4.prototype.boolean=!1,h4.prototype.commaOrSpaceSeparated=!1,h4.prototype.commaSeparated=!1,h4.prototype.defined=!1,h4.prototype.mustUseProperty=!1,h4.prototype.number=!1,h4.prototype.overloadedBoolean=!1,h4.prototype.property=``,h4.prototype.spaceSeparated=!1,h4.prototype.space=void 0;var g4=e({boolean:()=>_4,booleanish:()=>v4,commaOrSpaceSeparated:()=>S4,commaSeparated:()=>x4,number:()=>$,overloadedBoolean:()=>y4,spaceSeparated:()=>b4}),v3e=0,_4=C4(),v4=C4(),y4=C4(),$=C4(),b4=C4(),x4=C4(),S4=C4();function C4(){return 2**++v3e}var w4=Object.keys(g4),T4=class extends h4{constructor(e,t,n,r){let i=-1;if(super(e,t),E4(this,`space`,r),typeof n==`number`)for(;++i<w4.length;){let e=w4[i];E4(this,w4[i],(n&g4[e])===g4[e])}}};T4.prototype.defined=!0;function E4(e,t,n){n&&(e[t]=n)}function D4(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new T4(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[m4(r)]=r,n[m4(a.attribute)]=r}return new f4(t,n,e.space)}var O4=D4({properties:{ariaActiveDescendant:null,ariaAtomic:v4,ariaAutoComplete:null,ariaBusy:v4,ariaChecked:v4,ariaColCount:$,ariaColIndex:$,ariaColSpan:$,ariaControls:b4,ariaCurrent:null,ariaDescribedBy:b4,ariaDetails:null,ariaDisabled:v4,ariaDropEffect:b4,ariaErrorMessage:null,ariaExpanded:v4,ariaFlowTo:b4,ariaGrabbed:v4,ariaHasPopup:null,ariaHidden:v4,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:b4,ariaLevel:$,ariaLive:null,ariaModal:v4,ariaMultiLine:v4,ariaMultiSelectable:v4,ariaOrientation:null,ariaOwns:b4,ariaPlaceholder:null,ariaPosInSet:$,ariaPressed:v4,ariaReadOnly:v4,ariaRelevant:null,ariaRequired:v4,ariaRoleDescription:b4,ariaRowCount:$,ariaRowIndex:$,ariaRowSpan:$,ariaSelected:v4,ariaSetSize:$,ariaSort:null,ariaValueMax:$,ariaValueMin:$,ariaValueNow:$,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function k4(e,t){return t in e?e[t]:t}function A4(e,t){return k4(e,t.toLowerCase())}var y3e=D4({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:x4,acceptCharset:b4,accessKey:b4,action:null,allow:null,allowFullScreen:_4,allowPaymentRequest:_4,allowUserMedia:_4,alt:null,as:null,async:_4,autoCapitalize:null,autoComplete:b4,autoFocus:_4,autoPlay:_4,blocking:b4,capture:null,charSet:null,checked:_4,cite:null,className:b4,cols:$,colSpan:null,content:null,contentEditable:v4,controls:_4,controlsList:b4,coords:$|x4,crossOrigin:null,data:null,dateTime:null,decoding:null,default:_4,defer:_4,dir:null,dirName:null,disabled:_4,download:y4,draggable:v4,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:_4,formTarget:null,headers:b4,height:$,hidden:y4,high:$,href:null,hrefLang:null,htmlFor:b4,httpEquiv:b4,id:null,imageSizes:null,imageSrcSet:null,inert:_4,inputMode:null,integrity:null,is:null,isMap:_4,itemId:null,itemProp:b4,itemRef:b4,itemScope:_4,itemType:b4,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:_4,low:$,manifest:null,max:null,maxLength:$,media:null,method:null,min:null,minLength:$,multiple:_4,muted:_4,name:null,nonce:null,noModule:_4,noValidate:_4,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:_4,optimum:$,pattern:null,ping:b4,placeholder:null,playsInline:_4,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:_4,referrerPolicy:null,rel:b4,required:_4,reversed:_4,rows:$,rowSpan:$,sandbox:b4,scope:null,scoped:_4,seamless:_4,selected:_4,shadowRootClonable:_4,shadowRootDelegatesFocus:_4,shadowRootMode:null,shape:null,size:$,sizes:null,slot:null,span:$,spellCheck:v4,src:null,srcDoc:null,srcLang:null,srcSet:null,start:$,step:null,style:null,tabIndex:$,target:null,title:null,translate:null,type:null,typeMustMatch:_4,useMap:null,value:v4,width:$,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:b4,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:_4,declare:_4,event:null,face:null,frame:null,frameBorder:null,hSpace:$,leftMargin:$,link:null,longDesc:null,lowSrc:null,marginHeight:$,marginWidth:$,noResize:_4,noHref:_4,noShade:_4,noWrap:_4,object:null,profile:null,prompt:null,rev:null,rightMargin:$,rules:null,scheme:null,scrolling:v4,standby:null,summary:null,text:null,topMargin:$,valueType:null,version:null,vAlign:null,vLink:null,vSpace:$,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:_4,disableRemotePlayback:_4,prefix:null,property:null,results:$,security:null,unselectable:null},space:`html`,transform:A4}),b3e=D4({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:S4,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:b4,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:_4,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:x4,g2:x4,glyphName:x4,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:S4,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:b4,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:$,pointsAtY:$,pointsAtZ:$,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:S4,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:S4,rev:S4,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:S4,requiredFeatures:S4,requiredFonts:S4,requiredFormats:S4,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:S4,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:$,strokeOpacity:$,strokeWidth:null,style:null,surfaceScale:$,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:S4,tabIndex:$,tableValues:null,target:null,targetX:$,targetY:$,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:S4,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:k4}),j4=D4({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()}}),M4=D4({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:A4}),N4=D4({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),x3e=/[A-Z]/g,P4=/-[a-z]/g,S3e=/^data[-\w.:]+$/i;function F4(e,t){let n=m4(t),r=t,i=h4;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&S3e.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(P4,w3e);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!P4.test(e)){let n=e.replace(x3e,C3e);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=T4}return new i(r,t)}function C3e(e){return`-`+e.toLowerCase()}function w3e(e){return e.charAt(1).toUpperCase()}var I4=p4([O4,y3e,j4,M4,N4],`html`),L4=p4([O4,b3e,j4,M4,N4],`svg`),R4={}.hasOwnProperty;function z4(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&R4.call(t,e)){let n=String(t[e]);i=R4.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 T3e=/["&'<>`]/g,E3e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,D3e=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,O3e=/[|\\{}()[\]^$+*?.]/g,B4=new WeakMap;function k3e(e,t){if(e=e.replace(t.subset?A3e(t.subset):T3e,r),t.subset||t.escapeOnly)return e;return e.replace(E3e,n).replace(D3e,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 A3e(e){let t=B4.get(e);return t||(t=j3e(e),B4.set(e,t)),t}function j3e(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(O3e,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var M3e=/[\dA-Fa-f]/;function N3e(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!M3e.test(String.fromCharCode(t))?r:r+`;`}var P3e=/\d/;function F3e(e,t,n){let r=`&#`+String(e);return n&&t&&!P3e.test(String.fromCharCode(t))?r:r+`;`}var I3e=`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(`.`),V4={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:`€`},L3e=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],H4={}.hasOwnProperty,U4={},W4;for(W4 in V4)H4.call(V4,W4)&&(U4[V4[W4]]=W4);var R3e=/[^\dA-Za-z]/;function z3e(e,t,n,r){let i=String.fromCharCode(e);if(H4.call(U4,i)){let e=U4[i],a=`&`+e;return n&&I3e.includes(e)&&!L3e.includes(e)&&(!r||t&&t!==61&&R3e.test(String.fromCharCode(t)))?a:a+`;`}return``}function B3e(e,t,n){let r=N3e(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=z3e(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=F3e(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function G4(e,t){return k3e(e,Object.assign({format:B3e},t))}var V3e=/^>|^->|<!--|-->|--!>|<!-$/g,H3e=[`>`],U3e=[`<`,`>`];function W3e(e,t,n,r){return r.settings.bogusComments?`<?`+G4(e.value,Object.assign({},r.settings.characterReferences,{subset:H3e}))+`>`:`<!--`+e.value.replace(V3e,i)+`-->`;function i(e){return G4(e,Object.assign({},r.settings.characterReferences,{subset:U3e}))}}function G3e(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function K4(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 K3e(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 q4(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function q3e(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function J4(e){return e.join(` `).trim()}var J3e=/[ \t\n\f\r]/g;function Y4(e){return typeof e==`object`?e.type===`text`&&X4(e.value):X4(e)}function X4(e){return e.replace(J3e,``)===``}var Z4=$4(1),Q4=$4(-1),Y3e=[];function $4(e){return t;function t(t,n,r){let i=t?t.children:Y3e,a=(n||0)+e,o=i[a];if(!r)for(;o&&Y4(o);)a+=e,o=i[a];return o}}var X3e={}.hasOwnProperty;function e3(e){return t;function t(t,n,r){return X3e.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var t3=e3({body:Q3e,caption:n3,colgroup:n3,dd:n6e,dt:t6e,head:n3,html:Z3e,li:e6e,optgroup:r6e,option:i6e,p:$3e,rp:r3,rt:r3,tbody:o6e,td:i3,tfoot:s6e,th:i3,thead:a6e,tr:c6e});function n3(e,t,n){let r=Z4(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&Y4(r.value.charAt(0)))}function Z3e(e,t,n){let r=Z4(n,t);return!r||r.type!==`comment`}function Q3e(e,t,n){let r=Z4(n,t);return!r||r.type!==`comment`}function $3e(e,t,n){let r=Z4(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 e6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`li`}function t6e(e,t,n){let r=Z4(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function n6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function r3(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function r6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function i6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function a6e(e,t,n){let r=Z4(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function o6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function s6e(e,t,n){return!Z4(n,t)}function c6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function i3(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var l6e=e3({body:f6e,colgroup:p6e,head:d6e,html:u6e,tbody:m6e});function u6e(e){let t=Z4(e,-1);return!t||t.type!==`comment`}function d6e(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 f6e(e){let t=Z4(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&Y4(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function p6e(e,t,n){let r=Q4(n,t),i=Z4(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&t3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function m6e(e,t,n){let r=Q4(n,t),i=Z4(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&t3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var a3={name:[[`
1031
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function o4(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 l4({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 h3e(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 g3e(e){return c4({tagName:`div`,properties:{"data-gutter":``},children:e})}function _3e(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 v3e(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 y3e(){return c4({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[l4({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function b3e(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function u4(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`],f4=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};f4.prototype.normal={},f4.prototype.property={},f4.prototype.space=void 0;function p4(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new f4(n,r,t)}function m4(e){return e.toLowerCase()}var h4=class{constructor(e,t){this.attribute=t,this.property=e}};h4.prototype.attribute=``,h4.prototype.booleanish=!1,h4.prototype.boolean=!1,h4.prototype.commaOrSpaceSeparated=!1,h4.prototype.commaSeparated=!1,h4.prototype.defined=!1,h4.prototype.mustUseProperty=!1,h4.prototype.number=!1,h4.prototype.overloadedBoolean=!1,h4.prototype.property=``,h4.prototype.spaceSeparated=!1,h4.prototype.space=void 0;var g4=e({boolean:()=>_4,booleanish:()=>v4,commaOrSpaceSeparated:()=>S4,commaSeparated:()=>x4,number:()=>$,overloadedBoolean:()=>y4,spaceSeparated:()=>b4}),x3e=0,_4=C4(),v4=C4(),y4=C4(),$=C4(),b4=C4(),x4=C4(),S4=C4();function C4(){return 2**++x3e}var w4=Object.keys(g4),T4=class extends h4{constructor(e,t,n,r){let i=-1;if(super(e,t),E4(this,`space`,r),typeof n==`number`)for(;++i<w4.length;){let e=w4[i];E4(this,w4[i],(n&g4[e])===g4[e])}}};T4.prototype.defined=!0;function E4(e,t,n){n&&(e[t]=n)}function D4(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new T4(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[m4(r)]=r,n[m4(a.attribute)]=r}return new f4(t,n,e.space)}var O4=D4({properties:{ariaActiveDescendant:null,ariaAtomic:v4,ariaAutoComplete:null,ariaBusy:v4,ariaChecked:v4,ariaColCount:$,ariaColIndex:$,ariaColSpan:$,ariaControls:b4,ariaCurrent:null,ariaDescribedBy:b4,ariaDetails:null,ariaDisabled:v4,ariaDropEffect:b4,ariaErrorMessage:null,ariaExpanded:v4,ariaFlowTo:b4,ariaGrabbed:v4,ariaHasPopup:null,ariaHidden:v4,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:b4,ariaLevel:$,ariaLive:null,ariaModal:v4,ariaMultiLine:v4,ariaMultiSelectable:v4,ariaOrientation:null,ariaOwns:b4,ariaPlaceholder:null,ariaPosInSet:$,ariaPressed:v4,ariaReadOnly:v4,ariaRelevant:null,ariaRequired:v4,ariaRoleDescription:b4,ariaRowCount:$,ariaRowIndex:$,ariaRowSpan:$,ariaSelected:v4,ariaSetSize:$,ariaSort:null,ariaValueMax:$,ariaValueMin:$,ariaValueNow:$,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function k4(e,t){return t in e?e[t]:t}function A4(e,t){return k4(e,t.toLowerCase())}var S3e=D4({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:x4,acceptCharset:b4,accessKey:b4,action:null,allow:null,allowFullScreen:_4,allowPaymentRequest:_4,allowUserMedia:_4,alt:null,as:null,async:_4,autoCapitalize:null,autoComplete:b4,autoFocus:_4,autoPlay:_4,blocking:b4,capture:null,charSet:null,checked:_4,cite:null,className:b4,cols:$,colSpan:null,content:null,contentEditable:v4,controls:_4,controlsList:b4,coords:$|x4,crossOrigin:null,data:null,dateTime:null,decoding:null,default:_4,defer:_4,dir:null,dirName:null,disabled:_4,download:y4,draggable:v4,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:_4,formTarget:null,headers:b4,height:$,hidden:y4,high:$,href:null,hrefLang:null,htmlFor:b4,httpEquiv:b4,id:null,imageSizes:null,imageSrcSet:null,inert:_4,inputMode:null,integrity:null,is:null,isMap:_4,itemId:null,itemProp:b4,itemRef:b4,itemScope:_4,itemType:b4,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:_4,low:$,manifest:null,max:null,maxLength:$,media:null,method:null,min:null,minLength:$,multiple:_4,muted:_4,name:null,nonce:null,noModule:_4,noValidate:_4,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:_4,optimum:$,pattern:null,ping:b4,placeholder:null,playsInline:_4,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:_4,referrerPolicy:null,rel:b4,required:_4,reversed:_4,rows:$,rowSpan:$,sandbox:b4,scope:null,scoped:_4,seamless:_4,selected:_4,shadowRootClonable:_4,shadowRootDelegatesFocus:_4,shadowRootMode:null,shape:null,size:$,sizes:null,slot:null,span:$,spellCheck:v4,src:null,srcDoc:null,srcLang:null,srcSet:null,start:$,step:null,style:null,tabIndex:$,target:null,title:null,translate:null,type:null,typeMustMatch:_4,useMap:null,value:v4,width:$,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:b4,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:_4,declare:_4,event:null,face:null,frame:null,frameBorder:null,hSpace:$,leftMargin:$,link:null,longDesc:null,lowSrc:null,marginHeight:$,marginWidth:$,noResize:_4,noHref:_4,noShade:_4,noWrap:_4,object:null,profile:null,prompt:null,rev:null,rightMargin:$,rules:null,scheme:null,scrolling:v4,standby:null,summary:null,text:null,topMargin:$,valueType:null,version:null,vAlign:null,vLink:null,vSpace:$,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:_4,disableRemotePlayback:_4,prefix:null,property:null,results:$,security:null,unselectable:null},space:`html`,transform:A4}),C3e=D4({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:S4,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:b4,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:_4,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:x4,g2:x4,glyphName:x4,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:S4,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:b4,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:$,pointsAtY:$,pointsAtZ:$,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:S4,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:S4,rev:S4,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:S4,requiredFeatures:S4,requiredFonts:S4,requiredFormats:S4,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:S4,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:$,strokeOpacity:$,strokeWidth:null,style:null,surfaceScale:$,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:S4,tabIndex:$,tableValues:null,target:null,targetX:$,targetY:$,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:S4,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:k4}),j4=D4({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()}}),M4=D4({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:A4}),N4=D4({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),w3e=/[A-Z]/g,P4=/-[a-z]/g,T3e=/^data[-\w.:]+$/i;function F4(e,t){let n=m4(t),r=t,i=h4;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&T3e.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(P4,D3e);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!P4.test(e)){let n=e.replace(w3e,E3e);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=T4}return new i(r,t)}function E3e(e){return`-`+e.toLowerCase()}function D3e(e){return e.charAt(1).toUpperCase()}var I4=p4([O4,S3e,j4,M4,N4],`html`),L4=p4([O4,C3e,j4,M4,N4],`svg`),R4={}.hasOwnProperty;function z4(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&R4.call(t,e)){let n=String(t[e]);i=R4.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 O3e=/["&'<>`]/g,k3e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,A3e=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,j3e=/[|\\{}()[\]^$+*?.]/g,B4=new WeakMap;function M3e(e,t){if(e=e.replace(t.subset?N3e(t.subset):O3e,r),t.subset||t.escapeOnly)return e;return e.replace(k3e,n).replace(A3e,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 N3e(e){let t=B4.get(e);return t||(t=P3e(e),B4.set(e,t)),t}function P3e(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(j3e,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var F3e=/[\dA-Fa-f]/;function I3e(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!F3e.test(String.fromCharCode(t))?r:r+`;`}var L3e=/\d/;function R3e(e,t,n){let r=`&#`+String(e);return n&&t&&!L3e.test(String.fromCharCode(t))?r:r+`;`}var z3e=`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(`.`),V4={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:`€`},B3e=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],H4={}.hasOwnProperty,U4={},W4;for(W4 in V4)H4.call(V4,W4)&&(U4[V4[W4]]=W4);var V3e=/[^\dA-Za-z]/;function H3e(e,t,n,r){let i=String.fromCharCode(e);if(H4.call(U4,i)){let e=U4[i],a=`&`+e;return n&&z3e.includes(e)&&!B3e.includes(e)&&(!r||t&&t!==61&&V3e.test(String.fromCharCode(t)))?a:a+`;`}return``}function U3e(e,t,n){let r=I3e(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=H3e(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=R3e(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function G4(e,t){return M3e(e,Object.assign({format:U3e},t))}var W3e=/^>|^->|<!--|-->|--!>|<!-$/g,G3e=[`>`],K3e=[`<`,`>`];function q3e(e,t,n,r){return r.settings.bogusComments?`<?`+G4(e.value,Object.assign({},r.settings.characterReferences,{subset:G3e}))+`>`:`<!--`+e.value.replace(W3e,i)+`-->`;function i(e){return G4(e,Object.assign({},r.settings.characterReferences,{subset:K3e}))}}function J3e(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function K4(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 Y3e(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 q4(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function X3e(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function J4(e){return e.join(` `).trim()}var Z3e=/[ \t\n\f\r]/g;function Y4(e){return typeof e==`object`?e.type===`text`&&X4(e.value):X4(e)}function X4(e){return e.replace(Z3e,``)===``}var Z4=$4(1),Q4=$4(-1),Q3e=[];function $4(e){return t;function t(t,n,r){let i=t?t.children:Q3e,a=(n||0)+e,o=i[a];if(!r)for(;o&&Y4(o);)a+=e,o=i[a];return o}}var $3e={}.hasOwnProperty;function e3(e){return t;function t(t,n,r){return $3e.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var t3=e3({body:t6e,caption:n3,colgroup:n3,dd:a6e,dt:i6e,head:n3,html:e6e,li:r6e,optgroup:o6e,option:s6e,p:n6e,rp:r3,rt:r3,tbody:l6e,td:i3,tfoot:u6e,th:i3,thead:c6e,tr:d6e});function n3(e,t,n){let r=Z4(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&Y4(r.value.charAt(0)))}function e6e(e,t,n){let r=Z4(n,t);return!r||r.type!==`comment`}function t6e(e,t,n){let r=Z4(n,t);return!r||r.type!==`comment`}function n6e(e,t,n){let r=Z4(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 r6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`li`}function i6e(e,t,n){let r=Z4(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function a6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function r3(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function o6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function s6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function c6e(e,t,n){let r=Z4(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function l6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function u6e(e,t,n){return!Z4(n,t)}function d6e(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function i3(e,t,n){let r=Z4(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var f6e=e3({body:h6e,colgroup:g6e,head:m6e,html:p6e,tbody:_6e});function p6e(e){let t=Z4(e,-1);return!t||t.type!==`comment`}function m6e(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 h6e(e){let t=Z4(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&Y4(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function g6e(e,t,n){let r=Q4(n,t),i=Z4(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&t3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function _6e(e,t,n){let r=Q4(n,t),i=Z4(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&t3(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var a3={name:[[`
1032
1032
  \f\r &/=>`.split(``),`
1033
1033
  \f\r "&'/=>\``.split(``)],[`\0
1034
1034
  \f\r "&'/<=>`.split(``),`\0
@@ -1036,10 +1036,10 @@ If init has been called in the preload and contextIsolation is disabled, is not
1036
1036
  \f\r &>`.split(``),`\0
1037
1037
  \f\r "&'<=>\``.split(``)],[`\0
1038
1038
  \f\r "&'<=>\``.split(``),`\0
1039
- \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function h6e(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=L4);let l=g6e(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!l6e(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||!t3(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function g6e(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=_6e(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 _6e(e,t,n){let r=F4(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=G4(r.attribute,Object.assign({},e.settings.characterReferences,{subset:a3.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?q4:J4)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=G4(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:a3.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&K4(n,o)>K4(n,e.alternative)&&(o=e.alternative),s=o+G4(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?a3.single:a3.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var v6e=[`<`,`&`];function o3(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:G4(e.value,Object.assign({},r.settings.characterReferences,{subset:v6e}))}function y6e(e,t,n,r){return r.settings.allowDangerousHtml?e.value:o3(e,t,n,r)}function b6e(e,t,n,r){return r.all(e)}var x6e=z4(`type`,{invalid:S6e,unknown:C6e,handlers:{comment:W3e,doctype:G3e,element:h6e,raw:y6e,root:b6e,text:o3}});function S6e(e){throw Error("Expected node, not `"+e+"`")}function C6e(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var w6e={},T6e={},E6e=[];function s3(e,t){let n=t||w6e,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:D6e,all:O6e,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||T6e,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?L4:I4,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function D6e(e,t,n){return x6e(e,t,n,this)}function O6e(e){let t=[],n=e&&e.children||E6e,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var k6e=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(),A2(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||F2(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&&u4(e.composedPath())||(_3(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||(_3(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if(_3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){_3(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();_3(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);_3(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=u3(i)&&this.hoveredLine?.lineElement===i.lineElement;l3(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),l3(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),u3(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(N6e(i)&&p!=null){p(i);break}if(M6e(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!u3(i))break;l3(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,_3(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})()),_3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),_3(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();u4(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(_3e(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(g3e());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(f3(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&&u4(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=f3(e);if(t&&u4(n))return;let r=F6e(e);return r==null?this.pathFromAnnotationSlot(e):f3(r)}pathFromAnnotationSlot(e){let t=L6e(I6e(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:f3(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=p3(t)?t:p3(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)}F2(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,k2(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=()=>{A2(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!m3(this.renderedSelectedLinesState,n),i=!m3(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);P6e(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=g3(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=g3(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:h3(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:h3(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 A6e({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:j6e({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 j6e({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 l3(e){return e!=null&&`kind`in e&&e.kind===`token`}function u3(e){return c3(e)||l3(e)}function M6e(e){return`type`in e&&e.type===`line-info`}function N6e(e){return`kind`in e&&e.kind===`merge-conflict-action`}function P6e(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 f3(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function F6e(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 I6e(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 L6e(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 p3(e){return e!=null&&typeof e.elementFromPoint==`function`}function R6e(e,t){return e===t||F2(e??void 0,t??void 0)}function m3(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&R6e(e?.range??null,t.range)}function h3(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function g3(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 _3(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 z6e=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),H6e(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`?U6e(t):W6e(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:B6e(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:V6e(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&v3(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 B6e(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function V6e(e){return Math.max(Math.ceil(e),0)}function H6e(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?v3(e,{codeWidthChanged:!0,numberWidthChanged:!0}):y3(e))}function v3(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 y3(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 U6e(e){e.codeElement.isConnected&&y3(e)}function W6e(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 b3=new Map,x3=new Map,G6e=new Map,S3=new Set;function K6e(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!S3.has(t))return!1;return!0}function C3(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(S3.has(n.name))continue;let e=b3.get(n.name);e??(e=n,b3.set(n.name,e)),S3.add(e.name),t.loadLanguageSync(e.data)}}function w3(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var T3=Object.defineProperty,q6e=Object.getOwnPropertyDescriptor,J6e=Object.getOwnPropertyNames,Y6e=Object.prototype.hasOwnProperty,X6e=(e,t)=>{let n={};for(var r in e)T3(n,r,{get:e[r],enumerable:!0});return t||T3(n,Symbol.toStringTag,{value:`Module`}),n},E3=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=J6e(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Y6e.call(e,s)&&s!==n&&T3(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=q6e(t,s))||r.enumerable});return e},Z6e=(e,t,n)=>(E3(e,t,`default`),n&&E3(n,t,`default`)),D3=[{id:`abap`,name:`ABAP`,import:(()=>N(()=>import(`./abap-LROWj-KX.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>N(()=>import(`./actionscript-3-Zed3jmNX.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>N(()=>import(`./ada-CtyzA0hN.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>N(()=>import(`./angular-html-CNXPMsN2.js`).then(e=>e.n),__vite__mapDeps([5,1,6,7,8])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>N(()=>import(`./angular-ts-8naLoWoA.js`),__vite__mapDeps([9,5,1,6,7,8,10])))},{id:`apache`,name:`Apache Conf`,import:(()=>N(()=>import(`./apache-DODhmGy0.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>N(()=>import(`./apex-Cxjhvl8F.js`),[]))},{id:`apl`,name:`APL`,import:(()=>N(()=>import(`./apl-9RqlfC4L.js`),__vite__mapDeps([11,7,1,8,6,12,13,14])))},{id:`applescript`,name:`AppleScript`,import:(()=>N(()=>import(`./applescript-BA8pREjw.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>N(()=>import(`./ara-_mddMYXO.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>N(()=>import(`./asciidoc-CNa7WEti.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>N(()=>import(`./asm-jeLQAw2_.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>N(()=>import(`./astro-DEOUVaUL.js`),__vite__mapDeps([15,7,1,8,14,16,17,18])))},{id:`awk`,name:`AWK`,import:(()=>N(()=>import(`./awk-BHyKjtjL.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>N(()=>import(`./ballerina-BfZjA9rU.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>N(()=>import(`./bat-kE8pgIUp.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>N(()=>import(`./beancount-CiM2Y4Mv.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>N(()=>import(`./berry-cvN1pfOg.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>N(()=>import(`./bibtex-Dq_6gS0v.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>N(()=>import(`./bicep-BKirlFmO.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>N(()=>import(`./bird2-BaBjamNo.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>N(()=>import(`./blade-qhaBLKQC.js`),__vite__mapDeps([19,7,1,8,6,12,13,14,20,21])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>N(()=>import(`./bsl-COh4injU.js`),__vite__mapDeps([22,23])))},{id:`c`,name:`C`,import:(()=>N(()=>import(`./c-Dy_bYPSr.js`).then(e=>e.n),__vite__mapDeps([24,1])))},{id:`c3`,name:`C3`,import:(()=>N(()=>import(`./c3-Dw0crHdI.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>N(()=>import(`./cadence-CDxy0mZB.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>N(()=>import(`./cairo-D9XerGFI.js`),__vite__mapDeps([25,26])))},{id:`clarity`,name:`Clarity`,import:(()=>N(()=>import(`./clarity-CJMRjLgh.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>N(()=>import(`./clojure-vt6YVffw.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>N(()=>import(`./cmake-zaNLyYCh.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>N(()=>import(`./cobol-P2hn7TXm.js`),__vite__mapDeps([27,6,1,7,8,13])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>N(()=>import(`./codeowners-BLq4YEA8.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>N(()=>import(`./codeql-B7CMTiO8.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>N(()=>import(`./coffee-TsaJbZkc.js`),__vite__mapDeps([28,7,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>N(()=>import(`./common-lisp-B_5E2Zdx.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>N(()=>import(`./coq-J2IMDYw9.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>N(()=>import(`./cpp-lB26TbTP.js`).then(e=>e.n),__vite__mapDeps([29,1,21,30,31,24])))},{id:`crystal`,name:`Crystal`,import:(()=>N(()=>import(`./crystal-BMAMEN5_.js`),__vite__mapDeps([32,7,1,8,6,21,24,33])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>N(()=>import(`./csharp-fzmjUXps.js`),[]))},{id:`css`,name:`CSS`,import:(()=>N(()=>import(`./css-5Tn8jvjX.js`).then(e=>e.n),__vite__mapDeps([8,1])))},{id:`csv`,name:`CSV`,import:(()=>N(()=>import(`./csv-Bf0U-6f3.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>N(()=>import(`./cue-BY48eITb.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>N(()=>import(`./cypher-IKTMlLMg.js`),[]))},{id:`d`,name:`D`,import:(()=>N(()=>import(`./d-AQsP4WHv.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>N(()=>import(`./dart-BNjrvU6P.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>N(()=>import(`./dax-CxU10Az9.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>N(()=>import(`./desktop-BPZJDk0d.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>N(()=>import(`./diff-sVB8Iqu1.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>N(()=>import(`./docker-Bwu1puZT.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>N(()=>import(`./dotenv-jbv5-1M2.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>N(()=>import(`./dream-maker-DmOedZGu.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>N(()=>import(`./edge-BsY6Dvy0.js`),__vite__mapDeps([34,6,1,7,8,16,20])))},{id:`elixir`,name:`Elixir`,import:(()=>N(()=>import(`./elixir-BZz-hqbR.js`),__vite__mapDeps([35,6,1,7,8])))},{id:`elm`,name:`Elm`,import:(()=>N(()=>import(`./elm-BRjWHXlm.js`),__vite__mapDeps([36,31,1,24])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>N(()=>import(`./emacs-lisp-BpAdiruH.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>N(()=>import(`./erb-DyHbZJUF.js`),__vite__mapDeps([37,6,1,7,8,38,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>N(()=>import(`./erlang-BAaIl4Bp.js`),__vite__mapDeps([44,45])))},{id:`fennel`,name:`Fennel`,import:(()=>N(()=>import(`./fennel-vnCz-bp5.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>N(()=>import(`./fish-CdU5E-YQ.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>N(()=>import(`./fluent-B-wMfSdQ.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>N(()=>import(`./fortran-fixed-form-DWZWCeWi.js`),__vite__mapDeps([46,47])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>N(()=>import(`./fortran-free-form-DJxAWUrC.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>N(()=>import(`./fsharp-wFdh0YAg.js`),__vite__mapDeps([48,45])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>N(()=>import(`./gdresource-C5OXSCS9.js`),__vite__mapDeps([49,50,51])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>N(()=>import(`./gdscript-Cu0HLvj-.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>N(()=>import(`./gdshader-CaVCQW9t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>N(()=>import(`./genie-81Ym91c5.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>N(()=>import(`./gherkin-DkNejeYB.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>N(()=>import(`./git-commit-BJn43XzB.js`),__vite__mapDeps([52,53])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>N(()=>import(`./git-rebase-D753LgR4.js`),__vite__mapDeps([54,33,1])))},{id:`gleam`,name:`Gleam`,import:(()=>N(()=>import(`./gleam-CXxOKPLQ.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>N(()=>import(`./glimmer-js-CWIQt_ca.js`),__vite__mapDeps([55,7,1,8,6,16])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>N(()=>import(`./glimmer-ts-Ntr1SeR3.js`),__vite__mapDeps([56,7,1,8,6,16])))},{id:`glsl`,name:`GLSL`,import:(()=>N(()=>import(`./glsl-XlVJTcyG.js`).then(e=>e.n),__vite__mapDeps([31,1,24])))},{id:`gn`,name:`GN`,import:(()=>N(()=>import(`./gn-MSqZd-DI.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>N(()=>import(`./gnuplot-BU0qbpb4.js`),[]))},{id:`go`,name:`Go`,import:(()=>N(()=>import(`./go-wxR-9SwJ.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>N(()=>import(`./graphql-B7KqOeHs.js`).then(e=>e.n),__vite__mapDeps([40,1,7,16,18,41])))},{id:`groovy`,name:`Groovy`,import:(()=>N(()=>import(`./groovy-DSk78kL2.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>N(()=>import(`./hack-CTggiz-m.js`),__vite__mapDeps([57,6,1,7,8,21])))},{id:`haml`,name:`Ruby Haml`,import:(()=>N(()=>import(`./haml-B-iWdzkM.js`).then(e=>e.n),__vite__mapDeps([39,1,7,8])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>N(()=>import(`./handlebars-D1AkJdZI.js`),__vite__mapDeps([58,7,1,8,6,43])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>N(()=>import(`./haskell-C9o3JN9u.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>N(()=>import(`./haxe-DaP2bSo8.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>N(()=>import(`./hcl-BIytkqmc.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>N(()=>import(`./hjson-C1zWdMgl.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>N(()=>import(`./hlsl-DWiTaAA1.js`),[]))},{id:`html`,name:`HTML`,import:(()=>N(()=>import(`./html-B9culvuL.js`).then(e=>e.n),__vite__mapDeps([6,1,7,8])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>N(()=>import(`./html-derivative-PDPS4pLY.js`),__vite__mapDeps([20,6,1,7,8])))},{id:`http`,name:`HTTP`,import:(()=>N(()=>import(`./http-DiXWLGkE.js`),__vite__mapDeps([59,12,1,13,14,33,40,7,16,18,41])))},{id:`hurl`,name:`Hurl`,import:(()=>N(()=>import(`./hurl-BZDc3Jtw.js`),__vite__mapDeps([60,12,1,13,61,40,7,16,18,41])))},{id:`hxml`,name:`HXML`,import:(()=>N(()=>import(`./hxml-DWvzLpTo.js`),__vite__mapDeps([62,63])))},{id:`hy`,name:`Hy`,import:(()=>N(()=>import(`./hy-Ds_GzKxg.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>N(()=>import(`./imba-B3p-95Tz.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>N(()=>import(`./ini-BCZzyugf.js`),[]))},{id:`java`,name:`Java`,import:(()=>N(()=>import(`./java-DD8v6SCw.js`).then(e=>e.n),__vite__mapDeps([13,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>N(()=>import(`./javascript-B0UuInDI.js`).then(e=>e.n),__vite__mapDeps([7,1])))},{id:`jinja`,name:`Jinja`,import:(()=>N(()=>import(`./jinja-C3Dq7ihL.js`),__vite__mapDeps([64,6,1,7,8])))},{id:`jison`,name:`Jison`,import:(()=>N(()=>import(`./jison-DSf4rHmh.js`),__vite__mapDeps([65,7,1])))},{id:`json`,name:`JSON`,import:(()=>N(()=>import(`./json-Bub81p9x.js`).then(e=>e.n),__vite__mapDeps([14,1])))},{id:`json5`,name:`JSON5`,import:(()=>N(()=>import(`./json5-Cr45pYdl.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>N(()=>import(`./jsonc-DejAVvbR.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>N(()=>import(`./jsonl-BhvlfaAU.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>N(()=>import(`./jsonnet-B4DARtC8.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>N(()=>import(`./jssm-v4-OP_5d.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>N(()=>import(`./jsx-CVsoW34k.js`).then(e=>e.n),__vite__mapDeps([41,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>N(()=>import(`./julia-CZXumuBX.js`),__vite__mapDeps([66,7,1,21,26,29,30,31,24,67])))},{id:`just`,name:`Just`,import:(()=>N(()=>import(`./just-D0yza6K2.js`),__vite__mapDeps([68,7,1,16,26,33,38,8,6,12,13,21,24,29,30,31,39,40,18,41,42,43,69])))},{id:`kdl`,name:`KDL`,import:(()=>N(()=>import(`./kdl-8ym1832d.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>N(()=>import(`./kotlin-CcbhymCF.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>N(()=>import(`./kusto-DMGKZzBv.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>N(()=>import(`./latex-B_y1lnEN.js`),__vite__mapDeps([70,71,67,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>N(()=>import(`./lean-bXh3gprK.js`),[]))},{id:`less`,name:`Less`,import:(()=>N(()=>import(`./less-CSmnzIFU.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>N(()=>import(`./liquid-DP7VlZYW.js`),__vite__mapDeps([72,7,1,8,6,14])))},{id:`llvm`,name:`LLVM IR`,import:(()=>N(()=>import(`./llvm-DUoS0-pw.js`),[]))},{id:`log`,name:`Log file`,import:(()=>N(()=>import(`./log-BIqQq7Jp.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>N(()=>import(`./logo-Cs1kujUE.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>N(()=>import(`./lua-BAG7dOge.js`).then(e=>e.n),__vite__mapDeps([42,1,24])))},{id:`luau`,name:`Luau`,import:(()=>N(()=>import(`./luau-eSZmVAzO.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>N(()=>import(`./make-CIzCWu7S.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>N(()=>import(`./markdown-DG21OhJI.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>N(()=>import(`./marko-Cp7qGCQm.js`),__vite__mapDeps([73,8,1,10,16,74])))},{id:`matlab`,name:`MATLAB`,import:(()=>N(()=>import(`./matlab-EiT0RLQ3.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>N(()=>import(`./mdc-B8NVymwE.js`),__vite__mapDeps([75,20,6,1,7,8,43,45])))},{id:`mdx`,name:`MDX`,import:(()=>N(()=>import(`./mdx-C01_hC3d.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>N(()=>import(`./mermaid-Dz-no_Jv.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>N(()=>import(`./mipsasm-D90bWS0h.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>N(()=>import(`./mojo-DOLhITWn.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>N(()=>import(`./moonbit-CHTUEk7V.js`),[]))},{id:`move`,name:`Move`,import:(()=>N(()=>import(`./move-CK-0gOBi.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>N(()=>import(`./narrat-DgAJUdop.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>N(()=>import(`./nextflow-DcTewtep.js`),__vite__mapDeps([76,77])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>N(()=>import(`./nextflow-groovy-_1_mDVJM.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>N(()=>import(`./nginx-DJl5z2aR.js`),__vite__mapDeps([78,42,1,24])))},{id:`nim`,name:`Nim`,import:(()=>N(()=>import(`./nim-Dg-nY8m2.js`),__vite__mapDeps([79,7,1,8,6,12,13,24,31,45])))},{id:`nix`,name:`Nix`,import:(()=>N(()=>import(`./nix-DCMsGE7_.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>N(()=>import(`./nushell-DT5gyZDY.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>N(()=>import(`./objective-c-B8Jd5h2r.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>N(()=>import(`./objective-cpp-Dz0aBqgz.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>N(()=>import(`./ocaml-CQiknyOY.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>N(()=>import(`./odin-Cv1RGQlJ.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>N(()=>import(`./openscad-BkJxYYxv.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>N(()=>import(`./pascal-CLMyIhtO.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>N(()=>import(`./perl-CI7jecTq.js`),__vite__mapDeps([69,7,1,8,6,12,13,21])))},{id:`php`,name:`PHP`,import:(()=>N(()=>import(`./php-ChFP9CBe.js`),__vite__mapDeps([80,7,1,8,6,12,13,14,21])))},{id:`pkl`,name:`Pkl`,import:(()=>N(()=>import(`./pkl-4qoS1nk5.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>N(()=>import(`./plsql-BZgizt09.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>N(()=>import(`./po-UJUAZnPc.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>N(()=>import(`./polar-1hu5VYAD.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>N(()=>import(`./postcss-DmNgU5nO.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>N(()=>import(`./powerquery-B_F1S-PM.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>N(()=>import(`./powershell-CcACwhoV.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>N(()=>import(`./prisma-BOL2U0jw.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>N(()=>import(`./prolog-DLpHWoJM.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>N(()=>import(`./proto-C6rr-anU.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>N(()=>import(`./pug-B0fl0unF.js`),__vite__mapDeps([81,7,1,8,6])))},{id:`puppet`,name:`Puppet`,import:(()=>N(()=>import(`./puppet-BEIAlwYm.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>N(()=>import(`./purescript-B9ZdNr6o.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>N(()=>import(`./python-Cb0jrteY.js`),[]))},{id:`qml`,name:`QML`,import:(()=>N(()=>import(`./qml-7gZ29K0p.js`),__vite__mapDeps([82,7,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>N(()=>import(`./qmldir-Dd7NOmhe.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>N(()=>import(`./qss-FIUlZXIi.js`),[]))},{id:`r`,name:`R`,import:(()=>N(()=>import(`./r-BY2iEdK7.js`).then(e=>e.n),__vite__mapDeps([67,1])))},{id:`racket`,name:`Racket`,import:(()=>N(()=>import(`./racket-Bp3pwKpz.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>N(()=>import(`./raku-B56QJp9J.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>N(()=>import(`./razor-CZy2ujiF.js`),__vite__mapDeps([83,6,1,7,8,84])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>N(()=>import(`./reg-JsTjqUvS.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>N(()=>import(`./regexp-BieKZPiU.js`).then(e=>e.n),__vite__mapDeps([30,1])))},{id:`rel`,name:`Rel`,import:(()=>N(()=>import(`./rel-H9z9ElKp.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>N(()=>import(`./riscv-CgTvcEUc.js`),[]))},{id:`ron`,name:`RON`,import:(()=>N(()=>import(`./ron-lNfouVF0.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>N(()=>import(`./rosmsg-DAdxH_2o.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>N(()=>import(`./rst-CfjqtaYt.js`),__vite__mapDeps([85,7,1,20,6,8,26,86,29,21,30,31,24,33,43,38,12,13,39,40,16,18,41,42])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>N(()=>import(`./ruby-CSzE8NZD.js`),__vite__mapDeps([38,7,1,8,6,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>N(()=>import(`./rust-BxKwBtjZ.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>N(()=>import(`./sas-BRUw9CAa.js`),__vite__mapDeps([87,21,1])))},{id:`sass`,name:`Sass`,import:(()=>N(()=>import(`./sass-Cq28TOIy.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>N(()=>import(`./scala-DWtqJq97.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>N(()=>import(`./scheme-f_29tAtt.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>N(()=>import(`./scss-4x_6pmF2.js`).then(e=>e.n),__vite__mapDeps([10,1,8])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>N(()=>import(`./sdbl-DSLJ-P-D.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>N(()=>import(`./shaderlab-BbCj-Nnu.js`),__vite__mapDeps([88,89])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>N(()=>import(`./shellscript-BCP1gymp.js`).then(e=>e.n),__vite__mapDeps([33,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>N(()=>import(`./shellsession-D5Ijwb2H.js`),__vite__mapDeps([90,33,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>N(()=>import(`./smalltalk-DhUd0PTG.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>N(()=>import(`./solidity-4kXvD_Np.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>N(()=>import(`./soy-DQ7pPiO3.js`),__vite__mapDeps([91,6,1,7,8])))},{id:`sparql`,name:`SPARQL`,import:(()=>N(()=>import(`./sparql-FctWdqhV.js`),__vite__mapDeps([92,93])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>N(()=>import(`./splunk-BHvp_1jf.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>N(()=>import(`./sql-D4jklS0K.js`).then(e=>e.n),__vite__mapDeps([21,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>N(()=>import(`./ssh-config-DPxyQOwo.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>N(()=>import(`./stata-WbvGE-VS.js`),__vite__mapDeps([94,21,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>N(()=>import(`./stylus-BJGv9v6m.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>N(()=>import(`./surrealql-D-lvEuCC.js`),__vite__mapDeps([95,7,1])))},{id:`svelte`,name:`Svelte`,import:(()=>N(()=>import(`./svelte-bkJnqoJz.js`),__vite__mapDeps([96,7,1,8,16,17])))},{id:`swift`,name:`Swift`,import:(()=>N(()=>import(`./swift-BRMPCQ8s.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>N(()=>import(`./system-verilog-unXCtYEM.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>N(()=>import(`./systemd-DMP8LtoP.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>N(()=>import(`./talonscript-DKj9SUFt.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>N(()=>import(`./tasl-DfbnofhG.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>N(()=>import(`./tcl-3lRv9QAg.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>N(()=>import(`./templ-BrwbaRfa.js`),__vite__mapDeps([97,7,1,8,98])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>N(()=>import(`./terraform-BUkpGk8X.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>N(()=>import(`./tex-atcWI7rk.js`),__vite__mapDeps([71,67,1])))},{id:`toml`,name:`TOML`,import:(()=>N(()=>import(`./toml-DcsBOcfE.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>N(()=>import(`./ts-tags-CbY-UhSH.js`),__vite__mapDeps([99,7,1,8,6,12,13,16,21,31,24])))},{id:`tsv`,name:`TSV`,import:(()=>N(()=>import(`./tsv-DBhLzXgA.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>N(()=>import(`./tsx-Dfm676IJ.js`).then(e=>e.n),__vite__mapDeps([18,1])))},{id:`turtle`,name:`Turtle`,import:(()=>N(()=>import(`./turtle-Cy-vlDVE.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>N(()=>import(`./twig-83VHDTty.js`),__vite__mapDeps([100,7,1,8,10,26,38,6,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43,80,14])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>N(()=>import(`./typescript-BjG390PS.js`).then(e=>e.n),__vite__mapDeps([16,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>N(()=>import(`./typespec-Bw7rXpj9.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>N(()=>import(`./typst-B5gcflLE.js`),[]))},{id:`v`,name:`V`,import:(()=>N(()=>import(`./v-Et7D_FFJ.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>N(()=>import(`./vala-Cr_427sR.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>N(()=>import(`./vb-C1ZV48h8.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>N(()=>import(`./verilog-DuSmBq84.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>N(()=>import(`./vhdl-B8esgYLn.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>N(()=>import(`./viml-D2kc47l-.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>N(()=>import(`./vue-DQ8jEd0y.js`),__vite__mapDeps([101,7,1,8,6,14,16,20])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>N(()=>import(`./vue-html-aJaNf4Hi.js`),__vite__mapDeps([102,7,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>N(()=>import(`./vue-vine-DtwgVsbD.js`),__vite__mapDeps([103,7,1,8,10,17,74,104])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>N(()=>import(`./vyper-1412mFSh.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>N(()=>import(`./wasm-DQl9NXb9.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>N(()=>import(`./wenyan-BHYfOwae.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>N(()=>import(`./wgsl-CABXWmYu.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>N(()=>import(`./wikitext-C9vmSFvn.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>N(()=>import(`./wit-BEquzb_H.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>N(()=>import(`./wolfram-DjIRxOnX.js`),[]))},{id:`xml`,name:`XML`,import:(()=>N(()=>import(`./xml-CW-6mCqa.js`).then(e=>e.n),__vite__mapDeps([12,1,13])))},{id:`xsl`,name:`XSL`,import:(()=>N(()=>import(`./xsl-D3pa6zbH.js`),__vite__mapDeps([105,12,1,13])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>N(()=>import(`./yaml-_V1dSWlR.js`).then(e=>e.n),__vite__mapDeps([43,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>N(()=>import(`./zenscript-DdEB5ubh.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>N(()=>import(`./zig-BEKcs0kj.js`),[]))}],Q6e=Object.fromEntries(D3.map(e=>[e.id,e.import])),$6e=Object.fromEntries(D3.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),O3={...Q6e,...$6e},e8e=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>N(()=>import(`./andromeeda-D31WLT5P.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>N(()=>import(`./aurora-x-BIZngTGb.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>N(()=>import(`./ayu-dark-BTD8xVc9.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>N(()=>import(`./ayu-light-D7xKEusv.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>N(()=>import(`./ayu-mirage-qJUwSbPq.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-frappe-B4sAcwk0.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>N(()=>import(`./catppuccin-latte-DecxX0gz.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-macchiato-BFSQiDGE.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-mocha-CbkMvM3n.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>N(()=>import(`./dark-plus-BsmboJU0.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>N(()=>import(`./dracula-pEM8UtUB.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>N(()=>import(`./dracula-soft-6O902lvw.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>N(()=>import(`./everforest-dark-utNaWtRp.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>N(()=>import(`./everforest-light-BaQRbn6J.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>N(()=>import(`./github-dark-CIQKoOfz.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>N(()=>import(`./github-dark-default-B9J1oSSu.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>N(()=>import(`./github-dark-dimmed-Cjxj8pr1.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>N(()=>import(`./github-dark-high-contrast-CwLrrVWj.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>N(()=>import(`./github-light-BwgDLKgy.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>N(()=>import(`./github-light-default-CvZcSn34.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>N(()=>import(`./github-light-high-contrast-BEgh5-t0.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-hard-B8hKnBA2.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-medium-BMsBIAue.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-soft-Ab4YgDuw.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-hard-CSvJlA6-.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-medium-DEqih13U.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-soft-BXAwGvsE.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>N(()=>import(`./horizon-CTbU81KM.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>N(()=>import(`./horizon-bright-A29WP75k.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>N(()=>import(`./houston-C6joqys8.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-dragon-CYAflrk_.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>N(()=>import(`./kanagawa-lotus-Bs1Cg0Wk.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-wave-Em57xRwo.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>N(()=>import(`./laserwave-BeanxcuT.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>N(()=>import(`./light-plus-Cm4cQqPB.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>N(()=>import(`./material-theme-BHAnJl9J.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>N(()=>import(`./material-theme-darker-CRRtDtXT.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>N(()=>import(`./material-theme-lighter-CQrceBGq.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>N(()=>import(`./material-theme-ocean-BI_Y-1iW.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>N(()=>import(`./material-theme-palenight-CXs0FVc0.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>N(()=>import(`./min-dark-CTq8U-ql.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>N(()=>import(`./min-light-DcyukTrd.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>N(()=>import(`./monokai-BkViQDB6.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>N(()=>import(`./night-owl-CyLMGdWW.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>N(()=>import(`./night-owl-light-CGNiexOZ.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>N(()=>import(`./nord-VHEVEskW.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>N(()=>import(`./one-dark-pro-Dbu7-kmV.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>N(()=>import(`./one-light-C3nGIMSq.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>N(()=>import(`./plastic-CTOaCiVH.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>N(()=>import(`./poimandres-CLJC4Lgo.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>N(()=>import(`./red-CADA8Ax5.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-BwnPqkn2.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>N(()=>import(`./rose-pine-dawn-BDooGGMs.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-moon-BbWDyHMx.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>N(()=>import(`./slack-dark-qIhBihkn.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>N(()=>import(`./slack-ochin-Bq46O_aY.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>N(()=>import(`./snazzy-light-DgV51X3a.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>N(()=>import(`./solarized-dark-CQhTHMeY.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>N(()=>import(`./solarized-light-pPW5VQgL.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>N(()=>import(`./synthwave-84-NM23wD8q.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>N(()=>import(`./tokyo-night-BRSCr0BO.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>N(()=>import(`./vesper-CmzrwarA.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>N(()=>import(`./vitesse-black-DOh9RtZG.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>N(()=>import(`./vitesse-dark-DUf7vAJu.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>N(()=>import(`./vitesse-light-BnEKpw7k.js`),[]))}].map(e=>[e.id,e.import])),t8e=e({createOnigurumaEngine:()=>z3,getDefaultWasmLoader:()=>v8e,loadWasm:()=>I3,setDefaultWasmLoader:()=>_8e}),k3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function n8e(){return 2147483648}function r8e(){return typeof performance<`u`?performance.now():Date.now()}var i8e=(e,t)=>e+(t-e%t)%t;async function a8e(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=n8e();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,i8e(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:r8e,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 o8e=Object.defineProperty,s8e=(e,t,n)=>t in e?o8e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A3=(e,t,n)=>s8e(e,typeof t==`symbol`?t:t+``,n),j3=null;function c8e(e){throw new k3(e.UTF8ToString(e.getLastOnigError()))}var M3=class e{constructor(t){A3(this,`utf16Length`),A3(this,`utf8Length`),A3(this,`utf16Value`),A3(this,`utf8Value`),A3(this,`utf16OffsetToUtf8`),A3(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}},N3=class e{constructor(t){if(A3(this,`id`,++e.LAST_ID),A3(this,`_onigBinding`),A3(this,`content`),A3(this,`utf16Length`),A3(this,`utf8Length`),A3(this,`utf16OffsetToUtf8`),A3(this,`utf8OffsetToUtf16`),A3(this,`ptr`),!j3)throw new k3(`Must invoke loadWasm first.`);this._onigBinding=j3,this.content=t;let n=new M3(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=j3.omalloc(1e4),e._sharedPtrInUse=!0,j3.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(j3)}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)}};A3(N3,`LAST_ID`,0),A3(N3,`_sharedPtr`,0),A3(N3,`_sharedPtrInUse`,!1);var P3=N3,l8e=class{constructor(e){if(A3(this,`_onigBinding`),A3(this,`_ptr`),!j3)throw new k3(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new M3(e[r]);t[r]=i.createString(j3),n[r]=i.utf8Length}let r=j3.omalloc(4*e.length);j3.HEAPU32.set(t,r/4);let i=j3.omalloc(4*e.length);j3.HEAPU32.set(n,i/4);let a=j3.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)j3.ofree(t[n]);j3.ofree(i),j3.ofree(r),a===0&&c8e(j3),this._onigBinding=j3,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 P3(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 u8e(e){return typeof e.instantiator==`function`}function d8e(e){return typeof e.default==`function`}function f8e(e){return e.data!==void 0}function p8e(e){return typeof Response<`u`&&e instanceof Response}function m8e(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 F3;function I3(e){if(F3)return F3;async function t(){j3=await a8e(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),u8e(n)?n=await n.instantiator(t):d8e(n)?n=await n.default(t):(f8e(n)&&(n=n.data),p8e(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await h8e(n)(t):await g8e(n)(t):m8e(n)||n instanceof WebAssembly.Module?n=await L3(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await L3(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return F3=t(),F3}function L3(e){return t=>WebAssembly.instantiate(e,t)}function h8e(e){return t=>WebAssembly.instantiateStreaming(e,t)}function g8e(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var R3;function _8e(e){R3=e}function v8e(){return R3}async function z3(e){return e&&await I3(e),{createScanner(e){return new l8e(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new P3(e)}}}var B3=X6e({});Z6e(B3,t8e);var V3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function y8e(e){return H3(e)}function H3(e){return Array.isArray(e)?b8e(e):e instanceof RegExp?e:typeof e==`object`?x8e(e):e}function b8e(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=H3(e[n]);return t}function x8e(e){let t={};for(let n in e)t[n]=H3(e[n]);return t}function U3(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function W3(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?W3(e.substring(0,e.length-1)):e.substr(~t+1)}var G3=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,K3=class{static hasCaptures(e){return e!==null&&(G3.lastIndex=0,G3.test(e))}static replaceCaptures(e,t,n){return e.replace(G3,(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 q3(e,t){return e<t?-1:+(e>t)}function J3(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=q3(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Y3(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 X3(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var Z3=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}},Q3=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(w8e(e),t)}static createFromParsedTheme(e,t){return E8e(e,t)}_cachedMatchRoot=new Z3(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=>S8e(e.parent,t.parentScopes));return n?new e6(n.fontStyle,n.foreground,n.background):null}},$3=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 S8e(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&&!C8e(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function C8e(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var e6=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function w8e(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`&&Y3(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&Y3(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 T8e(l,u,e,o,s,c)}}return n}var T8e=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}},t6=(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))(t6||{});function E8e(e,t){e.sort((e,t)=>{let n=q3(e.scope,t.scope);return n!==0||(n=J3(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 D8e(t),o=new e6(n,a.getId(r),a.getId(i)),s=new k8e(new n6(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 Q3(a,o,s)}var D8e=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)}},O8e=Object.freeze([]),n6=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||O8e,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)}},k8e=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(),n6.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(J3(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 n6(e,t,n,r,i))}},r6=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=j8e(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 A8e(e){return e}function j8e(e){return e}function i6(e,t){let n=[],r=M8e(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(a6(i)){let e=[];do e.push(i),i=r.next();while(a6(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 a6(e){return!!e&&!!e.match(/[\w\.:]+/)}function M8e(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 o6(e){typeof e.dispose==`function`&&e.dispose()}var s6=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},N8e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},P8e=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))}},F8e=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 P8e;for(let n of e)I8e(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 I8e(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?l6({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];u6([r],t,n)}}function l6(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&u6(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&u6(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function u6(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?U3({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&u6(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=d6(i);switch(a.kind){case 0:l6({...t,selfGrammar:t.baseGrammar},n);break;case 1:l6(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):l6(i,n)}else a.kind===4?n.add(new N8e(a.scopeName,a.ruleName)):n.add(new s6(a.scopeName))}}}var L8e=class{kind=0},R8e=class{kind=1},z8e=class{constructor(e){this.ruleName=e}kind=2},B8e=class{constructor(e){this.scopeName=e}kind=3},V8e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function d6(e){if(e===`$base`)return new L8e;if(e===`$self`)return new R8e;let t=e.indexOf(`#`);return t===-1?new B8e(e):t===0?new z8e(e.substring(1)):new V8e(e.substring(0,t),e.substring(t+1))}var H8e=/\\(\d+)/,f6=/\\(\d+)/g,U8e=-1,p6=-2;function m6(e){return e}function h6(e){return e}var g6=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=K3.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=K3.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${W3(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:K3.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:K3.replaceCaptures(this._contentName,e,t)}},W8e=class extends g6{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!`)}},G8e=class extends g6{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new x6(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 S6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},_6=class extends g6{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 S6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},v6=class extends g6{_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 x6(i,this.id),this.beginCaptures=a,this._end=new x6(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 S6;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}},y6=class extends g6{_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 x6(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new x6(o,p6),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 S6;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 S6,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},b6=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new W8e(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new G8e(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=U3({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new _6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new y6(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 v6(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 _6||e instanceof v6||e instanceof y6)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},x6=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`&&H8e.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 f6.lastIndex=0,this.source.replace(f6,(e,t)=>X3(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}},S6=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 C6(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 C6(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},C6=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(`
1040
- `)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},w6=class{constructor(e,t){this.languageId=e,this.tokenType=t}},K8e=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new w6(e,8),this._embeddedLanguagesMatcher=new q8e(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 w6(0,0);_getBasicScopeAttributes=new Z3(e=>new w6(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/},q8e=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])=>X3(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 T6=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function E6(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=J8e(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 T6(i,!0);f()}return new T6(i,!1);function f(){let o=Y8e(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===U8e){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),O6(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 v6){let r=o;O6(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 y6){let r=o;O6(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(O6(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 J8e(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 y6&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Q8e(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==p6){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),O6(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 Y8e(e,t,n,r,i,a){let o=X8e(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Z8e(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 X8e(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=D6(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 Z8e(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}=D6(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 D6(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Q8e(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function O6(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));E6(e,p,n&&d.start===0,d.start,f,i,!1,0),o6(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 $8e(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var $8e=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function e5e(e,t,n,r,i,a,o,s){return new n5e(e,t,n,r,i,a,o,s)}function k6(e,t,n,r,i){let a=i6(t,A6),o=b6.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 A6(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(t5e(t[r],e))return n=r+1,!0;return!1})}function t5e(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 n5e=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new K8e(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=j6(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=i6(e,A6);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)k6(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&&k6(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(m6(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[h6(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]=j6(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=b6.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===N6.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=r6.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?M6.createRootAndLookUpScopeName(a,r,this):M6.createRoot(`unknown`,r),t=new N6(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
1041
- `;let a=this.createOnigString(e),o=a.content.length,s=new i5e(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=E6(this,a,i,0,t,s,!0,r);return o6(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function j6(e,t){return e=y8e(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 M6=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=$3.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new $3(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new $3(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),r6.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}},N6=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)?M6.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:h6(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=M6.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,m6(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,M6.fromExtension(r,n.contentNameScopesList))}},r5e=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):i6(e,A6).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>i6(e,A6).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}},i5e=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=r6.set(n,0,A8e(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=r6.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}},a5e=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,e5e(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},o5e=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new a5e(Q3.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(Q3.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 r5e(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new F8e(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)}},P6=N6.NULL;function F6(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 I6(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function s5e(e){return Array.isArray(e)?e:[e]}async function L6(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function R6(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function z6(e){return e===`ansi`||R6(e)}function B6(e){return e===`none`}function V6(e){return B6(e)}function H6(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 U6={light:`#333333`,dark:`#bbbbbb`},W6={light:`#fffffe`,dark:`#1e1e1e`},G6=`__shiki_resolved`;function K6(e){if(e?.[G6])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`?U6.light:U6.dark,n||=t.type===`light`?W6.light:W6.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,G6,{enumerable:!1,writable:!1,value:!0}),t}async function q6(e){return Array.from(new Set((await Promise.all(e.filter(e=>!z6(e)).map(async e=>await L6(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function J6(e){return(await Promise.all(e.map(async e=>V6(e)?null:K6(await L6(e))))).filter(e=>!!e)}function Y6(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 V3(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var c5e=class extends o5e{_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=K6(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=Q3.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=Y6(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 V3(`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))}},l5e=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}},X6=0;function u5e(e){X6+=1,e.warnings!==!1&&X6>=10&&X6%10==0&&console.warn(`[Shiki] ${X6} 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 V3("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(K6),i=new c5e(new l5e(e.engine,n),r,n,e.langAlias),a;function o(t){return Y6(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new V3(`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 V3(`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 q6(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await J6(e))}function g(){if(t)throw new V3(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--X6)}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 d5e(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([J6(e.themes||[]),q6(e.langs||[]),e.engine]);return u5e({...e,themes:t,langs:n,engine:r})}var Z6=new WeakMap;function Q6(e,t){Z6.set(e,t)}function $6(e){return Z6.get(e)}var e8=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(s5e(n).map(e=>[e,P6])),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 f5e(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function f5e(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 p5e(e,t){if(!(e instanceof e8))throw new V3(`Invalid grammar state`);return e.getInternalStack(t)}function t8(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(R6(e.resolveLangAlias(n.lang||`text`))||B6(r))return H6(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 V3(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new V3(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return h5e(t,o,i,a,n)}function m5e(...e){if(e.length===2)return $6(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(R6(i)||B6(a))throw new V3(`Plain language does not have grammar state`);if(i===`ansi`)throw new V3(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new e8(n8(n,c,o,s,r).stateStack,c.name,o.name)}function h5e(e,t,n,r,i){let a=n8(e,t,n,r,i),o=new e8(a.stateStack,t.name,n.name);return Q6(a.tokens,o),a.tokens}function n8(e,t,n,r,i){let a=F6(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=H6(e),l=i.grammarState?p5e(i.grammarState,n.name)??P6:i.grammarContextCode==null?P6:n8(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=I6(r[r6.getForeground(s)],a),l=r6.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`?g5e(t.scopes):_5e(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function g5e(e){return e.map(e=>({scopeName:e}))}function _5e(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:y5e(e,i,t.slice(0,r))}}return n}function r8(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function v5e(e,t,n){if(!r8(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)r8(e[r],n[i])&&--r,--i;return r===-1}function y5e(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(v5e(e,t,n)){r.push(a);break}return r}function i8(e,t,n,r=t8){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:$6(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=b5e(...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 e8(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&Q6(s,c),s}function b5e(...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 a8(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 x5e(e){let t=H6(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 S5e(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 o8=`light-dark()`,C5e=[`color`,`background-color`];function w5e(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 T5e(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?w5e(e,t):e})):e}function E5e(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&&C5e.includes(a))if(r===o8&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new V3('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&t6.Italic&&(t[`font-style`]=`italic`),e.fontStyle&t6.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&t6.Underline&&n.push(`underline`),e.fontStyle&t6.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 D5e(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=x5e(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new V3(`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 V3(`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 V3(`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)}));O5e(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 T5e(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 V3(`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+=l8(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new V3(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new V3(`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&&a8(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 O5e(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new V3(`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 V3(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function l8(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(l8).join(``):``}var k5e=[D5e()];function u8(e){let t=A5e(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...k5e]}function A5e(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`],f8={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function j5e(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 p8(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 M5e(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)f8[r]&&t.push({type:`setDecoration`,value:f8[r]});else if(r<=29){let e=f8[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=p8(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=p8(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 N5e(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=j5e(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=M5e(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 P5e={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 F5e(e=P5e){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 I5e={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 L5e(e,t,n){let r=F6(e,n),i=H6(t),a=F5e(Object.fromEntries(d8.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||I5e[t]]}))),o=N5e();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=I6(i,r),o=I6(o,r),n.decorations.has(`dim`)&&(i=R5e(i));let s=t6.None;return n.decorations.has(`bold`)&&(s|=t6.Bold),n.decorations.has(`italic`)&&(s|=t6.Italic),n.decorations.has(`underline`)&&(s|=t6.Underline),n.decorations.has(`strikethrough`)&&(s|=t6.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function R5e(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 m8(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!R6(r)&&!B6(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return L5e(r,t,n)}return t8(e,t,n)}function h8(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 V3("`themes` option must not be empty");let p=i8(e,t,n,m8);if(c=$6(p),l&&o8!==l&&!f.find(e=>e.color===l))throw new V3(`\`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=>E5e(e,h,u,l,d))),c&&Q6(a,c);let g=f.map(e=>F6(e.theme,n));i=g8(f,m,g,u,l,`fg`,d),r=g8(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=F6(n.theme,n);a=m8(e,t,n);let l=e.getTheme(n.theme);r=I6(l.bg,s),i=I6(l.fg,s),o=l.name,c=$6(a)}else throw new V3("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function g8(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=I6(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===o8&&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 V3('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${I6(t[r][a],n[r])||`inherit`}, ${I6(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function _8(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>_8(e,t,n),codeToTokens:(t,n)=>h8(e,t,n)}){let i=t;for(let e of u8(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=h8(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=B5e(a):d===`never`&&(a=V5e(a)),f&&(a=H5e(a));let p={...r,get source(){return i}};for(let e of u8(n))a=e.tokens?.call(p,a)||a;return z5e(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function z5e(e,t,n,r=$6(e)){let i=u8(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:a8,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:`
1042
- `}));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&&Q6(m,r),m}function B5e(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&t6.Underline||i.fontStyle&t6.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 V5e(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 H5e(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&t6.Underline||e.fontStyle&t6.Strikethrough),o=n.fontStyle&&(n.fontStyle&t6.Underline||n.fontStyle&t6.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var U5e=s3;function W5e(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>_8(e,t,n),codeToTokens:(t,n)=>h8(e,t,n)},i=U5e(_8(e,t,n,r));for(let e of u8(n))i=e.postprocess?.call(r,i,n)||i;return i}async function G5e(e){let t=await d5e(e);return{getLastGrammarState:(...e)=>m5e(t,...e),codeToTokensBase:(e,n)=>m8(t,e,n),codeToTokensWithThemes:(e,n)=>i8(t,e,n),codeToTokens:(e,n)=>h8(t,e,n),codeToHast:(e,n)=>_8(t,e,n),codeToHtml:(e,n)=>W5e(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function K5e(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,z6(n))return[];let r=t[n];if(!r)throw new V3(`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(V6(e))return`none`;if(typeof e==`string`){let t=n[e];if(!t)throw new V3(`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 G5e({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 q5e(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 J5e(e,t){let n=q5e(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 v8=K5e({langs:O3,themes:e8e,engine:()=>(0,B3.createOnigurumaEngine)(N(()=>import(`./wasm-BSSg2JG2.js`),[]))}),{codeToHtml:Y5e,codeToHast:X5e,codeToTokens:Z5e,codeToTokensBase:Q5e,codeToTokensWithThemes:$5e,getSingletonHighlighter:e7e,getLastGrammarState:t7e}=J5e(v8,{guessEmbeddedLanguages:S5e}),y8=4294967295,n7e=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:y8,end:y8,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 b8(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function r7e(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var x8=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),S8=String.raw;function C8(e,t){if(e==null)throw Error(t??`Value expected`);return e}var w8=S8`\[\^?`,T8=`c.? | C(?:-.?)?|${S8`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${S8`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${S8`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${S8`o\{[^\}]*\}?`}|${S8`\d{1,3}`}`,E8=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,D8=new RegExp(S8`
1039
+ \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function v6e(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=L4);let l=y6e(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!f6e(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||!t3(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function y6e(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=b6e(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 b6e(e,t,n){let r=F4(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=G4(r.attribute,Object.assign({},e.settings.characterReferences,{subset:a3.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?q4:J4)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=G4(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:a3.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&K4(n,o)>K4(n,e.alternative)&&(o=e.alternative),s=o+G4(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?a3.single:a3.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var x6e=[`<`,`&`];function o3(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:G4(e.value,Object.assign({},r.settings.characterReferences,{subset:x6e}))}function S6e(e,t,n,r){return r.settings.allowDangerousHtml?e.value:o3(e,t,n,r)}function C6e(e,t,n,r){return r.all(e)}var w6e=z4(`type`,{invalid:T6e,unknown:E6e,handlers:{comment:q3e,doctype:J3e,element:v6e,raw:S6e,root:C6e,text:o3}});function T6e(e){throw Error("Expected node, not `"+e+"`")}function E6e(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var D6e={},O6e={},k6e=[];function s3(e,t){let n=t||D6e,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:A6e,all:j6e,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||O6e,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?L4:I4,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function A6e(e,t,n){return w6e(e,t,n,this)}function j6e(e){let t=[],n=e&&e.children||k6e,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var M6e=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(),A2(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||F2(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&&u4(e.composedPath())||(_3(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||(_3(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if(_3(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){_3(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();_3(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);_3(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=u3(i)&&this.hoveredLine?.lineElement===i.lineElement;l3(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),l3(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),u3(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(I6e(i)&&p!=null){p(i);break}if(F6e(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!u3(i))break;l3(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,_3(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})()),_3(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),_3(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();u4(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(b3e(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(y3e());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(f3(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&&u4(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=f3(e);if(t&&u4(n))return;let r=R6e(e);return r==null?this.pathFromAnnotationSlot(e):f3(r)}pathFromAnnotationSlot(e){let t=B6e(z6e(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:f3(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=p3(t)?t:p3(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)}F2(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,k2(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=()=>{A2(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!m3(this.renderedSelectedLinesState,n),i=!m3(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);L6e(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=g3(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=g3(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:h3(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:h3(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 N6e({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:P6e({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 P6e({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 l3(e){return e!=null&&`kind`in e&&e.kind===`token`}function u3(e){return c3(e)||l3(e)}function F6e(e){return`type`in e&&e.type===`line-info`}function I6e(e){return`kind`in e&&e.kind===`merge-conflict-action`}function L6e(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 f3(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function R6e(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 z6e(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 B6e(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 p3(e){return e!=null&&typeof e.elementFromPoint==`function`}function V6e(e,t){return e===t||F2(e??void 0,t??void 0)}function m3(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&V6e(e?.range??null,t.range)}function h3(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function g3(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 _3(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 H6e=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),G6e(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`?K6e(t):q6e(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:U6e(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:W6e(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&v3(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 U6e(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function W6e(e){return Math.max(Math.ceil(e),0)}function G6e(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?v3(e,{codeWidthChanged:!0,numberWidthChanged:!0}):y3(e))}function v3(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 y3(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 K6e(e){e.codeElement.isConnected&&y3(e)}function q6e(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 b3=new Map,x3=new Map,J6e=new Map,S3=new Set;function Y6e(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!S3.has(t))return!1;return!0}function C3(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(S3.has(n.name))continue;let e=b3.get(n.name);e??(e=n,b3.set(n.name,e)),S3.add(e.name),t.loadLanguageSync(e.data)}}function w3(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var T3=Object.defineProperty,X6e=Object.getOwnPropertyDescriptor,Z6e=Object.getOwnPropertyNames,Q6e=Object.prototype.hasOwnProperty,$6e=(e,t)=>{let n={};for(var r in e)T3(n,r,{get:e[r],enumerable:!0});return t||T3(n,Symbol.toStringTag,{value:`Module`}),n},E3=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Z6e(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Q6e.call(e,s)&&s!==n&&T3(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=X6e(t,s))||r.enumerable});return e},e8e=(e,t,n)=>(E3(e,t,`default`),n&&E3(n,t,`default`)),D3=[{id:`abap`,name:`ABAP`,import:(()=>N(()=>import(`./abap-LROWj-KX.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>N(()=>import(`./actionscript-3-Zed3jmNX.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>N(()=>import(`./ada-CtyzA0hN.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>N(()=>import(`./angular-html-CNXPMsN2.js`).then(e=>e.n),__vite__mapDeps([5,1,6,7,8])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>N(()=>import(`./angular-ts-8naLoWoA.js`),__vite__mapDeps([9,5,1,6,7,8,10])))},{id:`apache`,name:`Apache Conf`,import:(()=>N(()=>import(`./apache-DODhmGy0.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>N(()=>import(`./apex-Cxjhvl8F.js`),[]))},{id:`apl`,name:`APL`,import:(()=>N(()=>import(`./apl-9RqlfC4L.js`),__vite__mapDeps([11,7,1,8,6,12,13,14])))},{id:`applescript`,name:`AppleScript`,import:(()=>N(()=>import(`./applescript-BA8pREjw.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>N(()=>import(`./ara-_mddMYXO.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>N(()=>import(`./asciidoc-CNa7WEti.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>N(()=>import(`./asm-jeLQAw2_.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>N(()=>import(`./astro-DEOUVaUL.js`),__vite__mapDeps([15,7,1,8,14,16,17,18])))},{id:`awk`,name:`AWK`,import:(()=>N(()=>import(`./awk-BHyKjtjL.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>N(()=>import(`./ballerina-BfZjA9rU.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>N(()=>import(`./bat-kE8pgIUp.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>N(()=>import(`./beancount-CiM2Y4Mv.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>N(()=>import(`./berry-cvN1pfOg.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>N(()=>import(`./bibtex-Dq_6gS0v.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>N(()=>import(`./bicep-BKirlFmO.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>N(()=>import(`./bird2-BaBjamNo.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>N(()=>import(`./blade-qhaBLKQC.js`),__vite__mapDeps([19,7,1,8,6,12,13,14,20,21])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>N(()=>import(`./bsl-COh4injU.js`),__vite__mapDeps([22,23])))},{id:`c`,name:`C`,import:(()=>N(()=>import(`./c-Dy_bYPSr.js`).then(e=>e.n),__vite__mapDeps([24,1])))},{id:`c3`,name:`C3`,import:(()=>N(()=>import(`./c3-Dw0crHdI.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>N(()=>import(`./cadence-CDxy0mZB.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>N(()=>import(`./cairo-D9XerGFI.js`),__vite__mapDeps([25,26])))},{id:`clarity`,name:`Clarity`,import:(()=>N(()=>import(`./clarity-CJMRjLgh.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>N(()=>import(`./clojure-vt6YVffw.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>N(()=>import(`./cmake-zaNLyYCh.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>N(()=>import(`./cobol-P2hn7TXm.js`),__vite__mapDeps([27,6,1,7,8,13])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>N(()=>import(`./codeowners-BLq4YEA8.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>N(()=>import(`./codeql-B7CMTiO8.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>N(()=>import(`./coffee-TsaJbZkc.js`),__vite__mapDeps([28,7,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>N(()=>import(`./common-lisp-B_5E2Zdx.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>N(()=>import(`./coq-J2IMDYw9.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>N(()=>import(`./cpp-lB26TbTP.js`).then(e=>e.n),__vite__mapDeps([29,1,21,30,31,24])))},{id:`crystal`,name:`Crystal`,import:(()=>N(()=>import(`./crystal-BMAMEN5_.js`),__vite__mapDeps([32,7,1,8,6,21,24,33])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>N(()=>import(`./csharp-fzmjUXps.js`),[]))},{id:`css`,name:`CSS`,import:(()=>N(()=>import(`./css-5Tn8jvjX.js`).then(e=>e.n),__vite__mapDeps([8,1])))},{id:`csv`,name:`CSV`,import:(()=>N(()=>import(`./csv-Bf0U-6f3.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>N(()=>import(`./cue-BY48eITb.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>N(()=>import(`./cypher-IKTMlLMg.js`),[]))},{id:`d`,name:`D`,import:(()=>N(()=>import(`./d-AQsP4WHv.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>N(()=>import(`./dart-BNjrvU6P.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>N(()=>import(`./dax-CxU10Az9.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>N(()=>import(`./desktop-BPZJDk0d.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>N(()=>import(`./diff-sVB8Iqu1.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>N(()=>import(`./docker-Bwu1puZT.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>N(()=>import(`./dotenv-jbv5-1M2.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>N(()=>import(`./dream-maker-DmOedZGu.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>N(()=>import(`./edge-BsY6Dvy0.js`),__vite__mapDeps([34,6,1,7,8,16,20])))},{id:`elixir`,name:`Elixir`,import:(()=>N(()=>import(`./elixir-BZz-hqbR.js`),__vite__mapDeps([35,6,1,7,8])))},{id:`elm`,name:`Elm`,import:(()=>N(()=>import(`./elm-BRjWHXlm.js`),__vite__mapDeps([36,31,1,24])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>N(()=>import(`./emacs-lisp-BpAdiruH.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>N(()=>import(`./erb-DyHbZJUF.js`),__vite__mapDeps([37,6,1,7,8,38,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>N(()=>import(`./erlang-BAaIl4Bp.js`),__vite__mapDeps([44,45])))},{id:`fennel`,name:`Fennel`,import:(()=>N(()=>import(`./fennel-vnCz-bp5.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>N(()=>import(`./fish-CdU5E-YQ.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>N(()=>import(`./fluent-B-wMfSdQ.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>N(()=>import(`./fortran-fixed-form-DWZWCeWi.js`),__vite__mapDeps([46,47])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>N(()=>import(`./fortran-free-form-DJxAWUrC.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>N(()=>import(`./fsharp-wFdh0YAg.js`),__vite__mapDeps([48,45])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>N(()=>import(`./gdresource-C5OXSCS9.js`),__vite__mapDeps([49,50,51])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>N(()=>import(`./gdscript-Cu0HLvj-.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>N(()=>import(`./gdshader-CaVCQW9t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>N(()=>import(`./genie-81Ym91c5.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>N(()=>import(`./gherkin-DkNejeYB.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>N(()=>import(`./git-commit-BJn43XzB.js`),__vite__mapDeps([52,53])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>N(()=>import(`./git-rebase-D753LgR4.js`),__vite__mapDeps([54,33,1])))},{id:`gleam`,name:`Gleam`,import:(()=>N(()=>import(`./gleam-CXxOKPLQ.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>N(()=>import(`./glimmer-js-CWIQt_ca.js`),__vite__mapDeps([55,7,1,8,6,16])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>N(()=>import(`./glimmer-ts-Ntr1SeR3.js`),__vite__mapDeps([56,7,1,8,6,16])))},{id:`glsl`,name:`GLSL`,import:(()=>N(()=>import(`./glsl-XlVJTcyG.js`).then(e=>e.n),__vite__mapDeps([31,1,24])))},{id:`gn`,name:`GN`,import:(()=>N(()=>import(`./gn-MSqZd-DI.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>N(()=>import(`./gnuplot-BU0qbpb4.js`),[]))},{id:`go`,name:`Go`,import:(()=>N(()=>import(`./go-wxR-9SwJ.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>N(()=>import(`./graphql-B7KqOeHs.js`).then(e=>e.n),__vite__mapDeps([40,1,7,16,18,41])))},{id:`groovy`,name:`Groovy`,import:(()=>N(()=>import(`./groovy-DSk78kL2.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>N(()=>import(`./hack-CTggiz-m.js`),__vite__mapDeps([57,6,1,7,8,21])))},{id:`haml`,name:`Ruby Haml`,import:(()=>N(()=>import(`./haml-B-iWdzkM.js`).then(e=>e.n),__vite__mapDeps([39,1,7,8])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>N(()=>import(`./handlebars-D1AkJdZI.js`),__vite__mapDeps([58,7,1,8,6,43])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>N(()=>import(`./haskell-C9o3JN9u.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>N(()=>import(`./haxe-DaP2bSo8.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>N(()=>import(`./hcl-BIytkqmc.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>N(()=>import(`./hjson-C1zWdMgl.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>N(()=>import(`./hlsl-DWiTaAA1.js`),[]))},{id:`html`,name:`HTML`,import:(()=>N(()=>import(`./html-B9culvuL.js`).then(e=>e.n),__vite__mapDeps([6,1,7,8])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>N(()=>import(`./html-derivative-PDPS4pLY.js`),__vite__mapDeps([20,6,1,7,8])))},{id:`http`,name:`HTTP`,import:(()=>N(()=>import(`./http-DiXWLGkE.js`),__vite__mapDeps([59,12,1,13,14,33,40,7,16,18,41])))},{id:`hurl`,name:`Hurl`,import:(()=>N(()=>import(`./hurl-BZDc3Jtw.js`),__vite__mapDeps([60,12,1,13,61,40,7,16,18,41])))},{id:`hxml`,name:`HXML`,import:(()=>N(()=>import(`./hxml-DWvzLpTo.js`),__vite__mapDeps([62,63])))},{id:`hy`,name:`Hy`,import:(()=>N(()=>import(`./hy-Ds_GzKxg.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>N(()=>import(`./imba-B3p-95Tz.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>N(()=>import(`./ini-BCZzyugf.js`),[]))},{id:`java`,name:`Java`,import:(()=>N(()=>import(`./java-DD8v6SCw.js`).then(e=>e.n),__vite__mapDeps([13,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>N(()=>import(`./javascript-B0UuInDI.js`).then(e=>e.n),__vite__mapDeps([7,1])))},{id:`jinja`,name:`Jinja`,import:(()=>N(()=>import(`./jinja-C3Dq7ihL.js`),__vite__mapDeps([64,6,1,7,8])))},{id:`jison`,name:`Jison`,import:(()=>N(()=>import(`./jison-DSf4rHmh.js`),__vite__mapDeps([65,7,1])))},{id:`json`,name:`JSON`,import:(()=>N(()=>import(`./json-Bub81p9x.js`).then(e=>e.n),__vite__mapDeps([14,1])))},{id:`json5`,name:`JSON5`,import:(()=>N(()=>import(`./json5-Cr45pYdl.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>N(()=>import(`./jsonc-DejAVvbR.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>N(()=>import(`./jsonl-BhvlfaAU.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>N(()=>import(`./jsonnet-B4DARtC8.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>N(()=>import(`./jssm-v4-OP_5d.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>N(()=>import(`./jsx-CVsoW34k.js`).then(e=>e.n),__vite__mapDeps([41,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>N(()=>import(`./julia-CZXumuBX.js`),__vite__mapDeps([66,7,1,21,26,29,30,31,24,67])))},{id:`just`,name:`Just`,import:(()=>N(()=>import(`./just-D0yza6K2.js`),__vite__mapDeps([68,7,1,16,26,33,38,8,6,12,13,21,24,29,30,31,39,40,18,41,42,43,69])))},{id:`kdl`,name:`KDL`,import:(()=>N(()=>import(`./kdl-8ym1832d.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>N(()=>import(`./kotlin-CcbhymCF.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>N(()=>import(`./kusto-DMGKZzBv.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>N(()=>import(`./latex-B_y1lnEN.js`),__vite__mapDeps([70,71,67,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>N(()=>import(`./lean-bXh3gprK.js`),[]))},{id:`less`,name:`Less`,import:(()=>N(()=>import(`./less-CSmnzIFU.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>N(()=>import(`./liquid-DP7VlZYW.js`),__vite__mapDeps([72,7,1,8,6,14])))},{id:`llvm`,name:`LLVM IR`,import:(()=>N(()=>import(`./llvm-DUoS0-pw.js`),[]))},{id:`log`,name:`Log file`,import:(()=>N(()=>import(`./log-BIqQq7Jp.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>N(()=>import(`./logo-Cs1kujUE.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>N(()=>import(`./lua-BAG7dOge.js`).then(e=>e.n),__vite__mapDeps([42,1,24])))},{id:`luau`,name:`Luau`,import:(()=>N(()=>import(`./luau-eSZmVAzO.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>N(()=>import(`./make-CIzCWu7S.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>N(()=>import(`./markdown-DG21OhJI.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>N(()=>import(`./marko-Cp7qGCQm.js`),__vite__mapDeps([73,8,1,10,16,74])))},{id:`matlab`,name:`MATLAB`,import:(()=>N(()=>import(`./matlab-EiT0RLQ3.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>N(()=>import(`./mdc-B8NVymwE.js`),__vite__mapDeps([75,20,6,1,7,8,43,45])))},{id:`mdx`,name:`MDX`,import:(()=>N(()=>import(`./mdx-C01_hC3d.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>N(()=>import(`./mermaid-Dz-no_Jv.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>N(()=>import(`./mipsasm-D90bWS0h.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>N(()=>import(`./mojo-DOLhITWn.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>N(()=>import(`./moonbit-CHTUEk7V.js`),[]))},{id:`move`,name:`Move`,import:(()=>N(()=>import(`./move-CK-0gOBi.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>N(()=>import(`./narrat-DgAJUdop.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>N(()=>import(`./nextflow-DcTewtep.js`),__vite__mapDeps([76,77])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>N(()=>import(`./nextflow-groovy-_1_mDVJM.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>N(()=>import(`./nginx-DJl5z2aR.js`),__vite__mapDeps([78,42,1,24])))},{id:`nim`,name:`Nim`,import:(()=>N(()=>import(`./nim-Dg-nY8m2.js`),__vite__mapDeps([79,7,1,8,6,12,13,24,31,45])))},{id:`nix`,name:`Nix`,import:(()=>N(()=>import(`./nix-DCMsGE7_.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>N(()=>import(`./nushell-DT5gyZDY.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>N(()=>import(`./objective-c-B8Jd5h2r.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>N(()=>import(`./objective-cpp-Dz0aBqgz.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>N(()=>import(`./ocaml-CQiknyOY.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>N(()=>import(`./odin-Cv1RGQlJ.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>N(()=>import(`./openscad-BkJxYYxv.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>N(()=>import(`./pascal-CLMyIhtO.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>N(()=>import(`./perl-CI7jecTq.js`),__vite__mapDeps([69,7,1,8,6,12,13,21])))},{id:`php`,name:`PHP`,import:(()=>N(()=>import(`./php-ChFP9CBe.js`),__vite__mapDeps([80,7,1,8,6,12,13,14,21])))},{id:`pkl`,name:`Pkl`,import:(()=>N(()=>import(`./pkl-4qoS1nk5.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>N(()=>import(`./plsql-BZgizt09.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>N(()=>import(`./po-UJUAZnPc.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>N(()=>import(`./polar-1hu5VYAD.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>N(()=>import(`./postcss-DmNgU5nO.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>N(()=>import(`./powerquery-B_F1S-PM.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>N(()=>import(`./powershell-CcACwhoV.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>N(()=>import(`./prisma-BOL2U0jw.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>N(()=>import(`./prolog-DLpHWoJM.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>N(()=>import(`./proto-C6rr-anU.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>N(()=>import(`./pug-B0fl0unF.js`),__vite__mapDeps([81,7,1,8,6])))},{id:`puppet`,name:`Puppet`,import:(()=>N(()=>import(`./puppet-BEIAlwYm.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>N(()=>import(`./purescript-B9ZdNr6o.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>N(()=>import(`./python-Cb0jrteY.js`),[]))},{id:`qml`,name:`QML`,import:(()=>N(()=>import(`./qml-7gZ29K0p.js`),__vite__mapDeps([82,7,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>N(()=>import(`./qmldir-Dd7NOmhe.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>N(()=>import(`./qss-FIUlZXIi.js`),[]))},{id:`r`,name:`R`,import:(()=>N(()=>import(`./r-BY2iEdK7.js`).then(e=>e.n),__vite__mapDeps([67,1])))},{id:`racket`,name:`Racket`,import:(()=>N(()=>import(`./racket-Bp3pwKpz.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>N(()=>import(`./raku-B56QJp9J.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>N(()=>import(`./razor-CZy2ujiF.js`),__vite__mapDeps([83,6,1,7,8,84])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>N(()=>import(`./reg-JsTjqUvS.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>N(()=>import(`./regexp-BieKZPiU.js`).then(e=>e.n),__vite__mapDeps([30,1])))},{id:`rel`,name:`Rel`,import:(()=>N(()=>import(`./rel-H9z9ElKp.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>N(()=>import(`./riscv-CgTvcEUc.js`),[]))},{id:`ron`,name:`RON`,import:(()=>N(()=>import(`./ron-lNfouVF0.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>N(()=>import(`./rosmsg-DAdxH_2o.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>N(()=>import(`./rst-CfjqtaYt.js`),__vite__mapDeps([85,7,1,20,6,8,26,86,29,21,30,31,24,33,43,38,12,13,39,40,16,18,41,42])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>N(()=>import(`./ruby-CSzE8NZD.js`),__vite__mapDeps([38,7,1,8,6,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>N(()=>import(`./rust-BxKwBtjZ.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>N(()=>import(`./sas-BRUw9CAa.js`),__vite__mapDeps([87,21,1])))},{id:`sass`,name:`Sass`,import:(()=>N(()=>import(`./sass-Cq28TOIy.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>N(()=>import(`./scala-DWtqJq97.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>N(()=>import(`./scheme-f_29tAtt.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>N(()=>import(`./scss-4x_6pmF2.js`).then(e=>e.n),__vite__mapDeps([10,1,8])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>N(()=>import(`./sdbl-DSLJ-P-D.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>N(()=>import(`./shaderlab-BbCj-Nnu.js`),__vite__mapDeps([88,89])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>N(()=>import(`./shellscript-BCP1gymp.js`).then(e=>e.n),__vite__mapDeps([33,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>N(()=>import(`./shellsession-D5Ijwb2H.js`),__vite__mapDeps([90,33,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>N(()=>import(`./smalltalk-DhUd0PTG.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>N(()=>import(`./solidity-4kXvD_Np.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>N(()=>import(`./soy-DQ7pPiO3.js`),__vite__mapDeps([91,6,1,7,8])))},{id:`sparql`,name:`SPARQL`,import:(()=>N(()=>import(`./sparql-FctWdqhV.js`),__vite__mapDeps([92,93])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>N(()=>import(`./splunk-BHvp_1jf.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>N(()=>import(`./sql-D4jklS0K.js`).then(e=>e.n),__vite__mapDeps([21,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>N(()=>import(`./ssh-config-DPxyQOwo.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>N(()=>import(`./stata-WbvGE-VS.js`),__vite__mapDeps([94,21,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>N(()=>import(`./stylus-BJGv9v6m.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>N(()=>import(`./surrealql-D-lvEuCC.js`),__vite__mapDeps([95,7,1])))},{id:`svelte`,name:`Svelte`,import:(()=>N(()=>import(`./svelte-bkJnqoJz.js`),__vite__mapDeps([96,7,1,8,16,17])))},{id:`swift`,name:`Swift`,import:(()=>N(()=>import(`./swift-BRMPCQ8s.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>N(()=>import(`./system-verilog-unXCtYEM.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>N(()=>import(`./systemd-DMP8LtoP.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>N(()=>import(`./talonscript-DKj9SUFt.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>N(()=>import(`./tasl-DfbnofhG.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>N(()=>import(`./tcl-3lRv9QAg.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>N(()=>import(`./templ-BrwbaRfa.js`),__vite__mapDeps([97,7,1,8,98])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>N(()=>import(`./terraform-BUkpGk8X.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>N(()=>import(`./tex-atcWI7rk.js`),__vite__mapDeps([71,67,1])))},{id:`toml`,name:`TOML`,import:(()=>N(()=>import(`./toml-DcsBOcfE.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>N(()=>import(`./ts-tags-CbY-UhSH.js`),__vite__mapDeps([99,7,1,8,6,12,13,16,21,31,24])))},{id:`tsv`,name:`TSV`,import:(()=>N(()=>import(`./tsv-DBhLzXgA.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>N(()=>import(`./tsx-Dfm676IJ.js`).then(e=>e.n),__vite__mapDeps([18,1])))},{id:`turtle`,name:`Turtle`,import:(()=>N(()=>import(`./turtle-Cy-vlDVE.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>N(()=>import(`./twig-83VHDTty.js`),__vite__mapDeps([100,7,1,8,10,26,38,6,12,13,21,24,29,30,31,33,39,40,16,18,41,42,43,80,14])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>N(()=>import(`./typescript-BjG390PS.js`).then(e=>e.n),__vite__mapDeps([16,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>N(()=>import(`./typespec-Bw7rXpj9.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>N(()=>import(`./typst-B5gcflLE.js`),[]))},{id:`v`,name:`V`,import:(()=>N(()=>import(`./v-Et7D_FFJ.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>N(()=>import(`./vala-Cr_427sR.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>N(()=>import(`./vb-C1ZV48h8.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>N(()=>import(`./verilog-DuSmBq84.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>N(()=>import(`./vhdl-B8esgYLn.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>N(()=>import(`./viml-D2kc47l-.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>N(()=>import(`./vue-DQ8jEd0y.js`),__vite__mapDeps([101,7,1,8,6,14,16,20])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>N(()=>import(`./vue-html-aJaNf4Hi.js`),__vite__mapDeps([102,7,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>N(()=>import(`./vue-vine-DtwgVsbD.js`),__vite__mapDeps([103,7,1,8,10,17,74,104])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>N(()=>import(`./vyper-1412mFSh.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>N(()=>import(`./wasm-DQl9NXb9.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>N(()=>import(`./wenyan-BHYfOwae.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>N(()=>import(`./wgsl-CABXWmYu.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>N(()=>import(`./wikitext-C9vmSFvn.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>N(()=>import(`./wit-BEquzb_H.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>N(()=>import(`./wolfram-DjIRxOnX.js`),[]))},{id:`xml`,name:`XML`,import:(()=>N(()=>import(`./xml-CW-6mCqa.js`).then(e=>e.n),__vite__mapDeps([12,1,13])))},{id:`xsl`,name:`XSL`,import:(()=>N(()=>import(`./xsl-D3pa6zbH.js`),__vite__mapDeps([105,12,1,13])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>N(()=>import(`./yaml-_V1dSWlR.js`).then(e=>e.n),__vite__mapDeps([43,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>N(()=>import(`./zenscript-DdEB5ubh.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>N(()=>import(`./zig-BEKcs0kj.js`),[]))}],t8e=Object.fromEntries(D3.map(e=>[e.id,e.import])),n8e=Object.fromEntries(D3.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),O3={...t8e,...n8e},r8e=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>N(()=>import(`./andromeeda-D31WLT5P.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>N(()=>import(`./aurora-x-BIZngTGb.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>N(()=>import(`./ayu-dark-BTD8xVc9.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>N(()=>import(`./ayu-light-D7xKEusv.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>N(()=>import(`./ayu-mirage-qJUwSbPq.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-frappe-B4sAcwk0.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>N(()=>import(`./catppuccin-latte-DecxX0gz.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-macchiato-BFSQiDGE.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>N(()=>import(`./catppuccin-mocha-CbkMvM3n.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>N(()=>import(`./dark-plus-BsmboJU0.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>N(()=>import(`./dracula-pEM8UtUB.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>N(()=>import(`./dracula-soft-6O902lvw.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>N(()=>import(`./everforest-dark-utNaWtRp.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>N(()=>import(`./everforest-light-BaQRbn6J.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>N(()=>import(`./github-dark-CIQKoOfz.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>N(()=>import(`./github-dark-default-B9J1oSSu.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>N(()=>import(`./github-dark-dimmed-Cjxj8pr1.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>N(()=>import(`./github-dark-high-contrast-CwLrrVWj.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>N(()=>import(`./github-light-BwgDLKgy.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>N(()=>import(`./github-light-default-CvZcSn34.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>N(()=>import(`./github-light-high-contrast-BEgh5-t0.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-hard-B8hKnBA2.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-medium-BMsBIAue.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>N(()=>import(`./gruvbox-dark-soft-Ab4YgDuw.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-hard-CSvJlA6-.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-medium-DEqih13U.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>N(()=>import(`./gruvbox-light-soft-BXAwGvsE.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>N(()=>import(`./horizon-CTbU81KM.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>N(()=>import(`./horizon-bright-A29WP75k.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>N(()=>import(`./houston-C6joqys8.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-dragon-CYAflrk_.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>N(()=>import(`./kanagawa-lotus-Bs1Cg0Wk.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>N(()=>import(`./kanagawa-wave-Em57xRwo.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>N(()=>import(`./laserwave-BeanxcuT.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>N(()=>import(`./light-plus-Cm4cQqPB.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>N(()=>import(`./material-theme-BHAnJl9J.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>N(()=>import(`./material-theme-darker-CRRtDtXT.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>N(()=>import(`./material-theme-lighter-CQrceBGq.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>N(()=>import(`./material-theme-ocean-BI_Y-1iW.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>N(()=>import(`./material-theme-palenight-CXs0FVc0.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>N(()=>import(`./min-dark-CTq8U-ql.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>N(()=>import(`./min-light-DcyukTrd.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>N(()=>import(`./monokai-BkViQDB6.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>N(()=>import(`./night-owl-CyLMGdWW.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>N(()=>import(`./night-owl-light-CGNiexOZ.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>N(()=>import(`./nord-VHEVEskW.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>N(()=>import(`./one-dark-pro-Dbu7-kmV.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>N(()=>import(`./one-light-C3nGIMSq.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>N(()=>import(`./plastic-CTOaCiVH.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>N(()=>import(`./poimandres-CLJC4Lgo.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>N(()=>import(`./red-CADA8Ax5.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-BwnPqkn2.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>N(()=>import(`./rose-pine-dawn-BDooGGMs.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>N(()=>import(`./rose-pine-moon-BbWDyHMx.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>N(()=>import(`./slack-dark-qIhBihkn.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>N(()=>import(`./slack-ochin-Bq46O_aY.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>N(()=>import(`./snazzy-light-DgV51X3a.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>N(()=>import(`./solarized-dark-CQhTHMeY.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>N(()=>import(`./solarized-light-pPW5VQgL.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>N(()=>import(`./synthwave-84-NM23wD8q.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>N(()=>import(`./tokyo-night-BRSCr0BO.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>N(()=>import(`./vesper-CmzrwarA.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>N(()=>import(`./vitesse-black-DOh9RtZG.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>N(()=>import(`./vitesse-dark-DUf7vAJu.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>N(()=>import(`./vitesse-light-BnEKpw7k.js`),[]))}].map(e=>[e.id,e.import])),i8e=e({createOnigurumaEngine:()=>z3,getDefaultWasmLoader:()=>x8e,loadWasm:()=>I3,setDefaultWasmLoader:()=>b8e}),k3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function a8e(){return 2147483648}function o8e(){return typeof performance<`u`?performance.now():Date.now()}var s8e=(e,t)=>e+(t-e%t)%t;async function c8e(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=a8e();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,s8e(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:o8e,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 l8e=Object.defineProperty,u8e=(e,t,n)=>t in e?l8e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A3=(e,t,n)=>u8e(e,typeof t==`symbol`?t:t+``,n),j3=null;function d8e(e){throw new k3(e.UTF8ToString(e.getLastOnigError()))}var M3=class e{constructor(t){A3(this,`utf16Length`),A3(this,`utf8Length`),A3(this,`utf16Value`),A3(this,`utf8Value`),A3(this,`utf16OffsetToUtf8`),A3(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}},N3=class e{constructor(t){if(A3(this,`id`,++e.LAST_ID),A3(this,`_onigBinding`),A3(this,`content`),A3(this,`utf16Length`),A3(this,`utf8Length`),A3(this,`utf16OffsetToUtf8`),A3(this,`utf8OffsetToUtf16`),A3(this,`ptr`),!j3)throw new k3(`Must invoke loadWasm first.`);this._onigBinding=j3,this.content=t;let n=new M3(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=j3.omalloc(1e4),e._sharedPtrInUse=!0,j3.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(j3)}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)}};A3(N3,`LAST_ID`,0),A3(N3,`_sharedPtr`,0),A3(N3,`_sharedPtrInUse`,!1);var P3=N3,f8e=class{constructor(e){if(A3(this,`_onigBinding`),A3(this,`_ptr`),!j3)throw new k3(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new M3(e[r]);t[r]=i.createString(j3),n[r]=i.utf8Length}let r=j3.omalloc(4*e.length);j3.HEAPU32.set(t,r/4);let i=j3.omalloc(4*e.length);j3.HEAPU32.set(n,i/4);let a=j3.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)j3.ofree(t[n]);j3.ofree(i),j3.ofree(r),a===0&&d8e(j3),this._onigBinding=j3,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 P3(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 p8e(e){return typeof e.instantiator==`function`}function m8e(e){return typeof e.default==`function`}function h8e(e){return e.data!==void 0}function g8e(e){return typeof Response<`u`&&e instanceof Response}function _8e(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 F3;function I3(e){if(F3)return F3;async function t(){j3=await c8e(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),p8e(n)?n=await n.instantiator(t):m8e(n)?n=await n.default(t):(h8e(n)&&(n=n.data),g8e(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await v8e(n)(t):await y8e(n)(t):_8e(n)||n instanceof WebAssembly.Module?n=await L3(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await L3(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return F3=t(),F3}function L3(e){return t=>WebAssembly.instantiate(e,t)}function v8e(e){return t=>WebAssembly.instantiateStreaming(e,t)}function y8e(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var R3;function b8e(e){R3=e}function x8e(){return R3}async function z3(e){return e&&await I3(e),{createScanner(e){return new f8e(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new P3(e)}}}var B3=$6e({});e8e(B3,i8e);var V3=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function S8e(e){return H3(e)}function H3(e){return Array.isArray(e)?C8e(e):e instanceof RegExp?e:typeof e==`object`?w8e(e):e}function C8e(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=H3(e[n]);return t}function w8e(e){let t={};for(let n in e)t[n]=H3(e[n]);return t}function U3(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function W3(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?W3(e.substring(0,e.length-1)):e.substr(~t+1)}var G3=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,K3=class{static hasCaptures(e){return e!==null&&(G3.lastIndex=0,G3.test(e))}static replaceCaptures(e,t,n){return e.replace(G3,(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 q3(e,t){return e<t?-1:+(e>t)}function J3(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=q3(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Y3(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 X3(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var Z3=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}},Q3=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(D8e(e),t)}static createFromParsedTheme(e,t){return k8e(e,t)}_cachedMatchRoot=new Z3(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=>T8e(e.parent,t.parentScopes));return n?new e6(n.fontStyle,n.foreground,n.background):null}},$3=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 T8e(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&&!E8e(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function E8e(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var e6=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function D8e(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`&&Y3(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&Y3(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 O8e(l,u,e,o,s,c)}}return n}var O8e=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}},t6=(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))(t6||{});function k8e(e,t){e.sort((e,t)=>{let n=q3(e.scope,t.scope);return n!==0||(n=J3(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 A8e(t),o=new e6(n,a.getId(r),a.getId(i)),s=new M8e(new n6(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 Q3(a,o,s)}var A8e=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)}},j8e=Object.freeze([]),n6=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||j8e,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)}},M8e=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(),n6.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(J3(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 n6(e,t,n,r,i))}},r6=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=P8e(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 N8e(e){return e}function P8e(e){return e}function i6(e,t){let n=[],r=F8e(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(a6(i)){let e=[];do e.push(i),i=r.next();while(a6(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 a6(e){return!!e&&!!e.match(/[\w\.:]+/)}function F8e(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 o6(e){typeof e.dispose==`function`&&e.dispose()}var s6=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},I8e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},L8e=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))}},R8e=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 L8e;for(let n of e)z8e(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 z8e(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?l6({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];u6([r],t,n)}}function l6(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&u6(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&u6(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function u6(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?U3({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&u6(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=d6(i);switch(a.kind){case 0:l6({...t,selfGrammar:t.baseGrammar},n);break;case 1:l6(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):l6(i,n)}else a.kind===4?n.add(new I8e(a.scopeName,a.ruleName)):n.add(new s6(a.scopeName))}}}var B8e=class{kind=0},V8e=class{kind=1},H8e=class{constructor(e){this.ruleName=e}kind=2},U8e=class{constructor(e){this.scopeName=e}kind=3},W8e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function d6(e){if(e===`$base`)return new B8e;if(e===`$self`)return new V8e;let t=e.indexOf(`#`);return t===-1?new U8e(e):t===0?new H8e(e.substring(1)):new W8e(e.substring(0,t),e.substring(t+1))}var G8e=/\\(\d+)/,f6=/\\(\d+)/g,K8e=-1,p6=-2;function m6(e){return e}function h6(e){return e}var g6=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=K3.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=K3.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${W3(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:K3.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:K3.replaceCaptures(this._contentName,e,t)}},q8e=class extends g6{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!`)}},J8e=class extends g6{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new x6(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 S6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},_6=class extends g6{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 S6,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},v6=class extends g6{_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 x6(i,this.id),this.beginCaptures=a,this._end=new x6(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 S6;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}},y6=class extends g6{_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 x6(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new x6(o,p6),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 S6;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 S6,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},b6=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new q8e(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new J8e(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=U3({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new _6(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new y6(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 v6(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 _6||e instanceof v6||e instanceof y6)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},x6=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`&&G8e.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 f6.lastIndex=0,this.source.replace(f6,(e,t)=>X3(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}},S6=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 C6(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 C6(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},C6=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(`
1040
+ `)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},w6=class{constructor(e,t){this.languageId=e,this.tokenType=t}},Y8e=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new w6(e,8),this._embeddedLanguagesMatcher=new X8e(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 w6(0,0);_getBasicScopeAttributes=new Z3(e=>new w6(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/},X8e=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])=>X3(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 T6=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function E6(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Z8e(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 T6(i,!0);f()}return new T6(i,!1);function f(){let o=Q8e(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===K8e){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),O6(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 v6){let r=o;O6(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 y6){let r=o;O6(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(O6(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 Z8e(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 y6&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=t5e(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==p6){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),O6(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 Q8e(e,t,n,r,i,a){let o=$8e(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=e5e(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 $8e(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=D6(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 e5e(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}=D6(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 D6(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function t5e(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function O6(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));E6(e,p,n&&d.start===0,d.start,f,i,!1,0),o6(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 n5e(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var n5e=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function r5e(e,t,n,r,i,a,o,s){return new a5e(e,t,n,r,i,a,o,s)}function k6(e,t,n,r,i){let a=i6(t,A6),o=b6.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 A6(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(i5e(t[r],e))return n=r+1,!0;return!1})}function i5e(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 a5e=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new Y8e(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=j6(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=i6(e,A6);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)k6(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&&k6(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(m6(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[h6(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]=j6(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=b6.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===N6.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=r6.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?M6.createRootAndLookUpScopeName(a,r,this):M6.createRoot(`unknown`,r),t=new N6(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
1041
+ `;let a=this.createOnigString(e),o=a.content.length,s=new s5e(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=E6(this,a,i,0,t,s,!0,r);return o6(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function j6(e,t){return e=S8e(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 M6=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=$3.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new $3(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new $3(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),r6.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}},N6=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)?M6.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:h6(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=M6.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,m6(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,M6.fromExtension(r,n.contentNameScopesList))}},o5e=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):i6(e,A6).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>i6(e,A6).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}},s5e=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=r6.set(n,0,N8e(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=r6.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}},c5e=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,r5e(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},l5e=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new c5e(Q3.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(Q3.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 o5e(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new R8e(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)}},P6=N6.NULL;function F6(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 I6(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function u5e(e){return Array.isArray(e)?e:[e]}async function L6(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function R6(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function z6(e){return e===`ansi`||R6(e)}function B6(e){return e===`none`}function V6(e){return B6(e)}function H6(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 U6={light:`#333333`,dark:`#bbbbbb`},W6={light:`#fffffe`,dark:`#1e1e1e`},G6=`__shiki_resolved`;function K6(e){if(e?.[G6])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`?U6.light:U6.dark,n||=t.type===`light`?W6.light:W6.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,G6,{enumerable:!1,writable:!1,value:!0}),t}async function q6(e){return Array.from(new Set((await Promise.all(e.filter(e=>!z6(e)).map(async e=>await L6(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function J6(e){return(await Promise.all(e.map(async e=>V6(e)?null:K6(await L6(e))))).filter(e=>!!e)}function Y6(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 V3(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var d5e=class extends l5e{_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=K6(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=Q3.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=Y6(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 V3(`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))}},f5e=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}},X6=0;function p5e(e){X6+=1,e.warnings!==!1&&X6>=10&&X6%10==0&&console.warn(`[Shiki] ${X6} 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 V3("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(K6),i=new d5e(new f5e(e.engine,n),r,n,e.langAlias),a;function o(t){return Y6(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new V3(`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 V3(`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 q6(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await J6(e))}function g(){if(t)throw new V3(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--X6)}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 m5e(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([J6(e.themes||[]),q6(e.langs||[]),e.engine]);return p5e({...e,themes:t,langs:n,engine:r})}var Z6=new WeakMap;function Q6(e,t){Z6.set(e,t)}function $6(e){return Z6.get(e)}var e8=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(u5e(n).map(e=>[e,P6])),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 h5e(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function h5e(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 g5e(e,t){if(!(e instanceof e8))throw new V3(`Invalid grammar state`);return e.getInternalStack(t)}function t8(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(R6(e.resolveLangAlias(n.lang||`text`))||B6(r))return H6(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 V3(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new V3(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return v5e(t,o,i,a,n)}function _5e(...e){if(e.length===2)return $6(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(R6(i)||B6(a))throw new V3(`Plain language does not have grammar state`);if(i===`ansi`)throw new V3(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new e8(n8(n,c,o,s,r).stateStack,c.name,o.name)}function v5e(e,t,n,r,i){let a=n8(e,t,n,r,i),o=new e8(a.stateStack,t.name,n.name);return Q6(a.tokens,o),a.tokens}function n8(e,t,n,r,i){let a=F6(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=H6(e),l=i.grammarState?g5e(i.grammarState,n.name)??P6:i.grammarContextCode==null?P6:n8(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=I6(r[r6.getForeground(s)],a),l=r6.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`?y5e(t.scopes):b5e(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function y5e(e){return e.map(e=>({scopeName:e}))}function b5e(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:S5e(e,i,t.slice(0,r))}}return n}function r8(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function x5e(e,t,n){if(!r8(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)r8(e[r],n[i])&&--r,--i;return r===-1}function S5e(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(x5e(e,t,n)){r.push(a);break}return r}function i8(e,t,n,r=t8){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:$6(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=C5e(...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 e8(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&Q6(s,c),s}function C5e(...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 a8(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 w5e(e){let t=H6(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 T5e(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 o8=`light-dark()`,E5e=[`color`,`background-color`];function D5e(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 O5e(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?D5e(e,t):e})):e}function k5e(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&&E5e.includes(a))if(r===o8&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new V3('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&t6.Italic&&(t[`font-style`]=`italic`),e.fontStyle&t6.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&t6.Underline&&n.push(`underline`),e.fontStyle&t6.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 A5e(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=w5e(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new V3(`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 V3(`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 V3(`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)}));j5e(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 O5e(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 V3(`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+=l8(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new V3(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new V3(`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&&a8(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 j5e(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new V3(`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 V3(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function l8(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(l8).join(``):``}var M5e=[A5e()];function u8(e){let t=N5e(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...M5e]}function N5e(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`],f8={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function P5e(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 p8(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 F5e(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)f8[r]&&t.push({type:`setDecoration`,value:f8[r]});else if(r<=29){let e=f8[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=p8(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=p8(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 I5e(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=P5e(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=F5e(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 L5e={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 R5e(e=L5e){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 z5e={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 B5e(e,t,n){let r=F6(e,n),i=H6(t),a=R5e(Object.fromEntries(d8.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||z5e[t]]}))),o=I5e();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=I6(i,r),o=I6(o,r),n.decorations.has(`dim`)&&(i=V5e(i));let s=t6.None;return n.decorations.has(`bold`)&&(s|=t6.Bold),n.decorations.has(`italic`)&&(s|=t6.Italic),n.decorations.has(`underline`)&&(s|=t6.Underline),n.decorations.has(`strikethrough`)&&(s|=t6.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function V5e(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 m8(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!R6(r)&&!B6(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return B5e(r,t,n)}return t8(e,t,n)}function h8(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 V3("`themes` option must not be empty");let p=i8(e,t,n,m8);if(c=$6(p),l&&o8!==l&&!f.find(e=>e.color===l))throw new V3(`\`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=>k5e(e,h,u,l,d))),c&&Q6(a,c);let g=f.map(e=>F6(e.theme,n));i=g8(f,m,g,u,l,`fg`,d),r=g8(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=F6(n.theme,n);a=m8(e,t,n);let l=e.getTheme(n.theme);r=I6(l.bg,s),i=I6(l.fg,s),o=l.name,c=$6(a)}else throw new V3("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function g8(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=I6(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===o8&&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 V3('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${I6(t[r][a],n[r])||`inherit`}, ${I6(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function _8(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>_8(e,t,n),codeToTokens:(t,n)=>h8(e,t,n)}){let i=t;for(let e of u8(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=h8(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=U5e(a):d===`never`&&(a=W5e(a)),f&&(a=G5e(a));let p={...r,get source(){return i}};for(let e of u8(n))a=e.tokens?.call(p,a)||a;return H5e(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function H5e(e,t,n,r=$6(e)){let i=u8(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:a8,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:`
1042
+ `}));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&&Q6(m,r),m}function U5e(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&t6.Underline||i.fontStyle&t6.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 W5e(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 G5e(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&t6.Underline||e.fontStyle&t6.Strikethrough),o=n.fontStyle&&(n.fontStyle&t6.Underline||n.fontStyle&t6.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var K5e=s3;function q5e(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>_8(e,t,n),codeToTokens:(t,n)=>h8(e,t,n)},i=K5e(_8(e,t,n,r));for(let e of u8(n))i=e.postprocess?.call(r,i,n)||i;return i}async function J5e(e){let t=await m5e(e);return{getLastGrammarState:(...e)=>_5e(t,...e),codeToTokensBase:(e,n)=>m8(t,e,n),codeToTokensWithThemes:(e,n)=>i8(t,e,n),codeToTokens:(e,n)=>h8(t,e,n),codeToHast:(e,n)=>_8(t,e,n),codeToHtml:(e,n)=>q5e(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function Y5e(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,z6(n))return[];let r=t[n];if(!r)throw new V3(`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(V6(e))return`none`;if(typeof e==`string`){let t=n[e];if(!t)throw new V3(`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 J5e({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 X5e(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 Z5e(e,t){let n=X5e(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 v8=Y5e({langs:O3,themes:r8e,engine:()=>(0,B3.createOnigurumaEngine)(N(()=>import(`./wasm-BSSg2JG2.js`),[]))}),{codeToHtml:Q5e,codeToHast:$5e,codeToTokens:e7e,codeToTokensBase:t7e,codeToTokensWithThemes:n7e,getSingletonHighlighter:r7e,getLastGrammarState:i7e}=Z5e(v8,{guessEmbeddedLanguages:T5e}),y8=4294967295,a7e=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:y8,end:y8,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 b8(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function o7e(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var x8=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),S8=String.raw;function C8(e,t){if(e==null)throw Error(t??`Value expected`);return e}var w8=S8`\[\^?`,T8=`c.? | C(?:-.?)?|${S8`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${S8`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${S8`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${S8`o\{[^\}]*\}?`}|${S8`\d{1,3}`}`,E8=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,D8=new RegExp(S8`
1043
1043
  \\ (?:
1044
1044
  ${T8}
1045
1045
  | [gk]<[^>]*>?
@@ -1070,8 +1070,8 @@ If init has been called in the preload and contextIsolation is disabled, is not
1070
1070
  | ${w8}
1071
1071
  | &&
1072
1072
  | .
1073
- `.replace(/\s+/g,``),`gsu`);function i7e(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=C7e(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(D8.lastIndex=0;s=D8.exec(e);){let t=a7e(a,e,s[0],D8.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(D8.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`?T7e(e,u):e).flat(),flags:r}}function a7e(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=o7e(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:A8(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:g7e(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:j8(n)}}if(a===`K`)return{token:F8(`keep`,n)};if(a===`N`||a===`R`)return{token:P8(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:P8(`any`,n)};if(a===`X`)return{token:P8(`text_segment`,n)};let e=k8(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:b7e(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:y7e(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:I8(`group`,n)};if(n===`(?>`)return{token:I8(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:I8(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:I8(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:I8(`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:p7e(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
1074
- `,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:P8(`dot`,n)}:n===`^`||n===`$`?{token:A8(e.singleline?{"^":S8`\A`,$:S8`\Z`}[n]:n,n)}:n===`|`?{token:c7e(n)}:E8.test(n)?{tokens:E7e(n)}:{token:M8(b8(n),n)}}function o7e(e,t,n){let r=[N8(t[1]===`^`,t)],i=1,a;for(O8.lastIndex=n;a=O8.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(N8(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(M8(93,e));else if(i--,r.push(l7e(e)),!i)break}else{let t=s7e(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:O8.lastIndex||e.length}}function s7e(e){if(e[0]===`\\`)return k8(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!x8.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return P8(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?u7e(e):e===`&&`?d7e(e):M8(b8(e),e)}function k8(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return v7e(e);if(`dDhHsSwW`.includes(n))return x7e(e);if(e.startsWith(S8`\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 S7e(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 M8(b8(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return M8(w7e(e),e);if(L8.has(n))return M8(L8.get(n),e);if(/\d/.test(n))return f7e(t,e);if(e===`\\`)throw Error(S8`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return M8(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function c7e(e){return{type:`Alternator`,raw:e}}function A8(e,t){return{type:`Assertion`,kind:e,raw:t}}function j8(e){return{type:`Backreference`,raw:e}}function M8(e,t){return{type:`Character`,value:e,raw:t}}function l7e(e){return{type:`CharacterClassClose`,raw:e}}function u7e(e){return{type:`CharacterClassHyphen`,raw:e}}function d7e(e){return{type:`CharacterClassIntersector`,raw:e}}function N8(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function P8(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function F8(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:C8(n.flags),raw:t}}function f7e(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function p7e(e){return{type:`GroupClose`,raw:e}}function I8(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function m7e(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function h7e(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function g7e(e){return{type:`Subroutine`,raw:e}}var _7e=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),L8=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function v7e(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return M8(b8(t.toUpperCase())-64,e)}function y7e(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=z8(n),o=z8(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),F8(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,I8(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function b7e(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=_7e.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 m7e(l,r??null,i?.split(`,`)??null,e)}function R8(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 h7e(t,n,r,e)}function x7e(e){let t=e[1].toLowerCase();return P8({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function S7e(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return P8(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function z8(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 C7e(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 w7e(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 T7e(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[j8(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(S8`Octal encoded byte above 177 unsupported "${n}"`)}else r=b8(t);a.push(M8(r,(e===0?`\\`:``)+t))}return a}function E7e(e){let t=[],n=new RegExp(E8,`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(R8(e.slice(0,-1)));continue}}}t.push(R8(e))}return t}function B8(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 D7e(e){return O7e.has(e.type)}var O7e=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function V8(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=i7e(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 H8();case`Assertion`:return k7e(n);case`Backreference`:return A7e(n,a);case`Character`:return K8(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return j7e(n,a,t);case`CharacterClassOpen`:return M7e(n,a,t);case`CharacterSet`:return N7e(n,a);case`Directive`:return z7e(n.kind,{flags:n.flags});case`GroupOpen`:return P7e(n,a,t);case`NamedCallout`:return V7e(n.kind,n.tag,n.arguments);case`Quantifier`:return F7e(n,a);case`Subroutine`:return I7e(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=U7e(B7e(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(S8`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(S8`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function k7e({kind:e}){return U8(C8({"^":`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===S8`\B`||e===S8`\Y`})}function A7e({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,W8(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 W8(r)}return i(+r)}function j7e(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(),R7e(o,e);throw Error(`Invalid character class range`)}return K8(b8(`-`))}function M7e({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[q8()],s=a5(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(q8()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=a5(r[t.nextIndex],a)}let c=q8({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 N7e({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=i5(n);if(x8.has(r)&&!o?.has(r))e=`posix`,n=r;else return $8(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?H7e(n,{negate:t}):J8(e,{negate:t})}function P7e(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=W7e(e),l=c.type===`AbsenceFunction`,u=r5(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&r7e(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=o5(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(H8()),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(n5(t)||t.type===`CapturingGroup`)throw Error(e)}else if(n5(t)||r5(t)&&t.negate)throw Error(e)}}f=o5(r[t.nextIndex])}return t.nextIndex++,c}function F7e({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!D7e(a))throw Error(`Quantifier requires a repeatable token`);let o=Z8(e,t,n,a);return i.body.pop(),o}function I7e({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=Q8(i);return r.push(o),o}function L7e(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:e5(t?.body)}}function H8(e){return{type:`Alternative`,body:t5(e?.body)}}function U8(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function W8(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function G8(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!G7e(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:e5(t?.body)}}function K8(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 q8(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:t5(e?.body)}}function R7e(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function J8(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 z7e(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:C8(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function B7e(e){return{type:`Flags`,...e}}function Y8(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:e5(e?.body)}}function X8(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:e5(e?.body)}}function V7e(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function H7e(e,t){let n=!!t?.negate;if(!x8.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function Z8(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 U7e(e,t){return{type:`Regex`,body:e5(t?.body),flags:e}}function Q8(e){return{type:`Subroutine`,ref:e}}function $8(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(i5(e));if(!r){if(n.normalizeUnknownPropertyNames)r=K7e(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(S8`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function W7e({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return L7e(`repeater`);case`atomic`:return Y8({atomic:!0});case`capturing`:return G8(i,{name:n});case`group`:return Y8({flags:e});case`lookahead`:case`lookbehind`:return X8({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function e5(e){if(e===void 0)e=[H8()];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 t5(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 n5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function r5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function G7e(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function K7e(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 i5(e){return e.replace(/[- _]+/g,``).toLowerCase()}function a5(e,t){return C8(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function o5(e){return C8(e,`Unclosed group`)}function s5(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(){c5(c).splice(Math.max(0,l5(s)+l),1),l--,u=!0},removeAllNextSiblings(){return c5(c).splice(l5(s)+1)},removeAllPrevSiblings(){let e=l5(s)+l;return l-=e,c5(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,l5(s)+l)]=e:C8(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(c5(c).splice(Math.max(0,l5(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,l5(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 c5(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function l5(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var q7e=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function J7e(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Y7e(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var u5=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===u5.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?u5.CHAR_CLASS:u5.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 f5(e,t,n,r){d5(e,t,n,r)}function X7e(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===u5.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function p5(e,t,n){return!!X7e(e,t,0,n)}function Z7e(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 m5=new RegExp(String.raw`(?<noncapturingStart>${q7e})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function Q7e(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(m5.lastIndex=Number.isNaN(c)?0:c+7;f=m5.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),J7e(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}`},u5.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var h5=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,g5=new RegExp(String.raw`
1073
+ `.replace(/\s+/g,``),`gsu`);function s7e(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=E7e(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(D8.lastIndex=0;s=D8.exec(e);){let t=c7e(a,e,s[0],D8.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(D8.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`?O7e(e,u):e).flat(),flags:r}}function c7e(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=l7e(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:A8(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:y7e(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:j8(n)}}if(a===`K`)return{token:F8(`keep`,n)};if(a===`N`||a===`R`)return{token:P8(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:P8(`any`,n)};if(a===`X`)return{token:P8(`text_segment`,n)};let e=k8(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:C7e(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:S7e(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:I8(`group`,n)};if(n===`(?>`)return{token:I8(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:I8(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:I8(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:I8(`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:g7e(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
1074
+ `,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:P8(`dot`,n)}:n===`^`||n===`$`?{token:A8(e.singleline?{"^":S8`\A`,$:S8`\Z`}[n]:n,n)}:n===`|`?{token:d7e(n)}:E8.test(n)?{tokens:k7e(n)}:{token:M8(b8(n),n)}}function l7e(e,t,n){let r=[N8(t[1]===`^`,t)],i=1,a;for(O8.lastIndex=n;a=O8.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(N8(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(M8(93,e));else if(i--,r.push(f7e(e)),!i)break}else{let t=u7e(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:O8.lastIndex||e.length}}function u7e(e){if(e[0]===`\\`)return k8(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!x8.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return P8(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?p7e(e):e===`&&`?m7e(e):M8(b8(e),e)}function k8(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return x7e(e);if(`dDhHsSwW`.includes(n))return w7e(e);if(e.startsWith(S8`\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 T7e(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 M8(b8(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return M8(D7e(e),e);if(L8.has(n))return M8(L8.get(n),e);if(/\d/.test(n))return h7e(t,e);if(e===`\\`)throw Error(S8`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return M8(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function d7e(e){return{type:`Alternator`,raw:e}}function A8(e,t){return{type:`Assertion`,kind:e,raw:t}}function j8(e){return{type:`Backreference`,raw:e}}function M8(e,t){return{type:`Character`,value:e,raw:t}}function f7e(e){return{type:`CharacterClassClose`,raw:e}}function p7e(e){return{type:`CharacterClassHyphen`,raw:e}}function m7e(e){return{type:`CharacterClassIntersector`,raw:e}}function N8(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function P8(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function F8(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:C8(n.flags),raw:t}}function h7e(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function g7e(e){return{type:`GroupClose`,raw:e}}function I8(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function _7e(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function v7e(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function y7e(e){return{type:`Subroutine`,raw:e}}var b7e=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),L8=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function x7e(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return M8(b8(t.toUpperCase())-64,e)}function S7e(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=z8(n),o=z8(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),F8(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,I8(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function C7e(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=b7e.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 _7e(l,r??null,i?.split(`,`)??null,e)}function R8(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 v7e(t,n,r,e)}function w7e(e){let t=e[1].toLowerCase();return P8({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function T7e(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return P8(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function z8(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 E7e(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 D7e(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 O7e(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[j8(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(S8`Octal encoded byte above 177 unsupported "${n}"`)}else r=b8(t);a.push(M8(r,(e===0?`\\`:``)+t))}return a}function k7e(e){let t=[],n=new RegExp(E8,`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(R8(e.slice(0,-1)));continue}}}t.push(R8(e))}return t}function B8(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 A7e(e){return j7e.has(e.type)}var j7e=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function V8(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=s7e(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 H8();case`Assertion`:return M7e(n);case`Backreference`:return N7e(n,a);case`Character`:return K8(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return P7e(n,a,t);case`CharacterClassOpen`:return F7e(n,a,t);case`CharacterSet`:return I7e(n,a);case`Directive`:return H7e(n.kind,{flags:n.flags});case`GroupOpen`:return L7e(n,a,t);case`NamedCallout`:return W7e(n.kind,n.tag,n.arguments);case`Quantifier`:return R7e(n,a);case`Subroutine`:return z7e(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=K7e(U7e(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(S8`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(S8`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function M7e({kind:e}){return U8(C8({"^":`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===S8`\B`||e===S8`\Y`})}function N7e({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,W8(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 W8(r)}return i(+r)}function P7e(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(),V7e(o,e);throw Error(`Invalid character class range`)}return K8(b8(`-`))}function F7e({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[q8()],s=a5(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(q8()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=a5(r[t.nextIndex],a)}let c=q8({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 I7e({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=i5(n);if(x8.has(r)&&!o?.has(r))e=`posix`,n=r;else return $8(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?G7e(n,{negate:t}):J8(e,{negate:t})}function L7e(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=q7e(e),l=c.type===`AbsenceFunction`,u=r5(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&o7e(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=o5(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(H8()),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(n5(t)||t.type===`CapturingGroup`)throw Error(e)}else if(n5(t)||r5(t)&&t.negate)throw Error(e)}}f=o5(r[t.nextIndex])}return t.nextIndex++,c}function R7e({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!A7e(a))throw Error(`Quantifier requires a repeatable token`);let o=Z8(e,t,n,a);return i.body.pop(),o}function z7e({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=Q8(i);return r.push(o),o}function B7e(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:e5(t?.body)}}function H8(e){return{type:`Alternative`,body:t5(e?.body)}}function U8(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function W8(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function G8(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!J7e(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:e5(t?.body)}}function K8(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 q8(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:t5(e?.body)}}function V7e(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function J8(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 H7e(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:C8(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function U7e(e){return{type:`Flags`,...e}}function Y8(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:e5(e?.body)}}function X8(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:e5(e?.body)}}function W7e(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function G7e(e,t){let n=!!t?.negate;if(!x8.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function Z8(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 K7e(e,t){return{type:`Regex`,body:e5(t?.body),flags:e}}function Q8(e){return{type:`Subroutine`,ref:e}}function $8(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(i5(e));if(!r){if(n.normalizeUnknownPropertyNames)r=Y7e(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(S8`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function q7e({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return B7e(`repeater`);case`atomic`:return Y8({atomic:!0});case`capturing`:return G8(i,{name:n});case`group`:return Y8({flags:e});case`lookahead`:case`lookbehind`:return X8({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function e5(e){if(e===void 0)e=[H8()];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 t5(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 n5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function r5(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function J7e(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function Y7e(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 i5(e){return e.replace(/[- _]+/g,``).toLowerCase()}function a5(e,t){return C8(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function o5(e){return C8(e,`Unclosed group`)}function s5(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(){c5(c).splice(Math.max(0,l5(s)+l),1),l--,u=!0},removeAllNextSiblings(){return c5(c).splice(l5(s)+1)},removeAllPrevSiblings(){let e=l5(s)+l;return l-=e,c5(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,l5(s)+l)]=e:C8(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(c5(c).splice(Math.max(0,l5(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,l5(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 c5(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function l5(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var X7e=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function Z7e(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Q7e(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var u5=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===u5.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?u5.CHAR_CLASS:u5.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 f5(e,t,n,r){d5(e,t,n,r)}function $7e(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===u5.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function p5(e,t,n){return!!$7e(e,t,0,n)}function e9e(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 m5=new RegExp(String.raw`(?<noncapturingStart>${X7e})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function t9e(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(m5.lastIndex=Number.isNaN(c)?0:c+7;f=m5.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),Z7e(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}`},u5.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var h5=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,g5=new RegExp(String.raw`
1075
1075
  \\(?: \d+
1076
1076
  | c[A-Za-z]
1077
1077
  | [gk]<[^>]+>
@@ -1086,7 +1086,7 @@ If init has been called in the preload and contextIsolation is disabled, is not
1086
1086
  ))?
1087
1087
  | (?<qBase>${h5})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
1088
1088
  | \\?.
1089
- `.replace(/\s+/g,``),`gsu`);function $7e(e){if(!RegExp(`${h5}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(g5.lastIndex=0;o=g5.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=Y7e(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}g5.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null);i=s}return{pattern:e}}var _5=String.raw,v5=_5`\(\?R=(?<rDepth>[^\)]+)\)|${_5`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,y5=_5`\(\?<(?![=!])(?<captureName>[^>]+)>`,b5=_5`${y5}|(?<unnamed>\()(?!\?)`,x5=new RegExp(_5`${y5}|${v5}|\(\?|\\?.`,`gsu`),S5=`Cannot use multiple overlapping recursions`;function e9e(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(v5,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&p5(e,_5`\(\?\(DEFINE\)`,u5.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=p5(e,_5`\\[1-9]`,u5.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(x5.lastIndex=0;f=x5.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(C5(m),l)throw Error(S5);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(x5.lastIndex);if(p5(s,v5,u5.DEFAULT))throw Error(S5);let c=m-1;e=w5(t,s,c,!1,n,a,d),i=E5(i,t,c,a.length,0,d);break}if(h){C5(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(S5);break}if(!u)throw Error(_5`Recursive \g cannot be used outside the referenced group "${r===`external`?h:_5`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Z7e(e,p);if(o&&p5(m,_5`${y5}|\((?!\?)`,u5.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=w5(_,v,b,!0,n,a,d);i=E5(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,x5.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),x5.lastIndex),s.set(p,x5.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),x5.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function C5(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 w5(e,t,n,r,i,a,o){let s=new Set;r&&f5(e+t,y5,({groups:{captureName:e}})=>{s.add(e)},u5.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${T5(`(?:${e}`,`forward`,...c)}(?:)${T5(`${t})`,`backward`,...c)}${t}`}function T5(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,_5`${b5}|\\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),t9e(i,n),s?e:`(?<${t}${l}>`}return _5`\k<${c}${l}>`},u5.DEFAULT)}return c}function t9e(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function E5(e,t,n,r,i,a){if(e.size&&r){let o=0;f5(t,b5,()=>o++,u5.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 D5=String.fromCodePoint,O5=String.raw,k5={},A5=globalThis.RegExp;k5.flagGroups=(()=>{try{new A5(`(?i:)`)}catch{return!1}return!0})(),k5.unicodeSets=(()=>{try{new A5(`[[]]`,`v`)}catch{return!1}return!0})(),k5.bugFlagVLiteralHyphenIsRange=k5.unicodeSets?(()=>{try{new A5(O5`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,k5.bugNestedClassIgnoresNegation=k5.unicodeSets&&new A5(`[[^a]]`,`v`).test(`a`);function j5(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function M5(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function N5(e,t){return P5[e]>=P5[t]}function n9e(e,t){if(e==null)throw Error(t??`Value expected`);return e}var P5={ES2025:2025,ES2024:2024,ES2018:2018},r9e={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function F5(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!r9e[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=k5.flagGroups?`ES2025`:k5.unicodeSets?`ES2024`:`ES2018`),t}var i9e=`[ -\r ]`,a9e=new Set([D5(304),D5(305)]),I5=O5`[\p{L}\p{M}\p{N}\p{Pc}]`;function L5(e){if(a9e.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=c9e.get(n),a=o9e.get(n),o=s9e.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 R5=new Map(`C Other
1089
+ `.replace(/\s+/g,``),`gsu`);function n9e(e){if(!RegExp(`${h5}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(g5.lastIndex=0;o=g5.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=Q7e(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}g5.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null);i=s}return{pattern:e}}var _5=String.raw,v5=_5`\(\?R=(?<rDepth>[^\)]+)\)|${_5`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,y5=_5`\(\?<(?![=!])(?<captureName>[^>]+)>`,b5=_5`${y5}|(?<unnamed>\()(?!\?)`,x5=new RegExp(_5`${y5}|${v5}|\(\?|\\?.`,`gsu`),S5=`Cannot use multiple overlapping recursions`;function r9e(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(v5,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&p5(e,_5`\(\?\(DEFINE\)`,u5.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=p5(e,_5`\\[1-9]`,u5.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(x5.lastIndex=0;f=x5.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(C5(m),l)throw Error(S5);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(x5.lastIndex);if(p5(s,v5,u5.DEFAULT))throw Error(S5);let c=m-1;e=w5(t,s,c,!1,n,a,d),i=E5(i,t,c,a.length,0,d);break}if(h){C5(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(S5);break}if(!u)throw Error(_5`Recursive \g cannot be used outside the referenced group "${r===`external`?h:_5`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=e9e(e,p);if(o&&p5(m,_5`${y5}|\((?!\?)`,u5.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=w5(_,v,b,!0,n,a,d);i=E5(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,x5.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),x5.lastIndex),s.set(p,x5.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),x5.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function C5(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 w5(e,t,n,r,i,a,o){let s=new Set;r&&f5(e+t,y5,({groups:{captureName:e}})=>{s.add(e)},u5.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${T5(`(?:${e}`,`forward`,...c)}(?:)${T5(`${t})`,`backward`,...c)}${t}`}function T5(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,_5`${b5}|\\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),i9e(i,n),s?e:`(?<${t}${l}>`}return _5`\k<${c}${l}>`},u5.DEFAULT)}return c}function i9e(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function E5(e,t,n,r,i,a){if(e.size&&r){let o=0;f5(t,b5,()=>o++,u5.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 D5=String.fromCodePoint,O5=String.raw,k5={},A5=globalThis.RegExp;k5.flagGroups=(()=>{try{new A5(`(?i:)`)}catch{return!1}return!0})(),k5.unicodeSets=(()=>{try{new A5(`[[]]`,`v`)}catch{return!1}return!0})(),k5.bugFlagVLiteralHyphenIsRange=k5.unicodeSets?(()=>{try{new A5(O5`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,k5.bugNestedClassIgnoresNegation=k5.unicodeSets&&new A5(`[[^a]]`,`v`).test(`a`);function j5(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function M5(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function N5(e,t){return P5[e]>=P5[t]}function a9e(e,t){if(e==null)throw Error(t??`Value expected`);return e}var P5={ES2025:2025,ES2024:2024,ES2018:2018},o9e={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function F5(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!o9e[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=k5.flagGroups?`ES2025`:k5.unicodeSets?`ES2024`:`ES2018`),t}var s9e=`[ -\r ]`,c9e=new Set([D5(304),D5(305)]),I5=O5`[\p{L}\p{M}\p{N}\p{Pc}]`;function L5(e){if(c9e.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=d9e.get(n),a=l9e.get(n),o=u9e.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 R5=new Map(`C Other
1090
1090
  Cc Control cntrl
1091
1091
  Cf Format
1092
1092
  Cn Unassigned
@@ -1176,18 +1176,18 @@ Uppercase Upper
1176
1176
  Variation_Selector VS
1177
1177
  White_Space space
1178
1178
  XID_Continue XIDC
1179
- XID_Start XIDS`.split(/\s/).map(e=>[i5(e),e])),o9e=new Map([[`s`,D5(383)],[D5(383),`s`]]),s9e=new Map([[D5(223),D5(7838)],[D5(107),D5(8490)],[D5(229),D5(8491)],[D5(969),D5(8486)]]),c9e=new Map([z5(453),z5(456),z5(459),z5(498),...B5(8072,8079),...B5(8088,8095),...B5(8104,8111),z5(8124),z5(8140),z5(8188)]),l9e=new Map([[`alnum`,O5`[\p{Alpha}\p{Nd}]`],[`alpha`,O5`\p{Alpha}`],[`ascii`,O5`\p{ASCII}`],[`blank`,O5`[\p{Zs}\t]`],[`cntrl`,O5`\p{Cc}`],[`digit`,O5`\p{Nd}`],[`graph`,O5`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,O5`\p{Lower}`],[`print`,O5`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,O5`[\p{P}\p{S}]`],[`space`,O5`\p{space}`],[`upper`,O5`\p{Upper}`],[`word`,O5`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,O5`\p{AHex}`]]);function u9e(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function z5(e){let t=D5(e);return[t.toLowerCase(),t]}function B5(e,t){return u9e(e,t).map(e=>z5(e))}var V5=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function d9e(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};H5(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:N5(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};s5(e,f9e,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 s5(e,p9e,a),s5(e,m9e,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var f9e={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=Y8();e.body[0].body.push(X8({negate:!0,body:r}),$8(`Any`));let i=Y8();i.body[0].body.push(Z8(`greedy`,0,1/0,e)),n(e7(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];M5(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=K5(t.get(e));if(n){let t=Y8({flags:n});t.body[0].body=e.body,e.body=[e7(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(e7(X8({body:[H8({body:[U8(`string_end`)]}),H8({body:[K8(10)]})]}),t));else if(c===`line_start`)o(e7(Z5(O5`(?<=\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&&b9e(e))o(e7(X8({negate:!0}),t));else if(d)throw Error(O5`Uses "\G" in a way that requires a subclass`);else o($5(U8(`string_start`),t)),s.strategy=`clip_search`}else if(c!==`string_end`&&c!==`string_start`)if(c===`string_end_newline`)o(e7(Z5(O5`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${I5})(?!${I5})|(?<!${I5})(?=${I5}))`,n=`(?:(?<=${I5})(?=${I5})|(?<!${I5})(?!${I5}))`;o(e7(Z5(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!X5(n)&&(n=G5(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!X5(r)&&(r=G5(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(e7(q8({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($5(J8(`digit`,{negate:l}),t));return}if(o&&(c===`space`||u===`space`)){n(e7(Q5(Z5(i9e),l),t));return}if(s&&(c===`word`||u===`word`)){n($5(J8(`word`,{negate:l}),t));return}if(c===`any`)n($5($8(`Any`),t));else if(c===`digit`)n($5($8(`Nd`,{negate:l}),t));else if(c!==`dot`)if(c===`text_segment`){if(r===`strict`)throw Error(O5`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=O5`\p{RI}{2}|${e}(?:\u200D${e})*`;n(e7(Z5(O5`(?>\r\n|${i?O5`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n($5($8(`AHex`,{negate:l}),t));else if(c===`newline`)n(e7(Z5(l?`[^
1179
+ XID_Start XIDS`.split(/\s/).map(e=>[i5(e),e])),l9e=new Map([[`s`,D5(383)],[D5(383),`s`]]),u9e=new Map([[D5(223),D5(7838)],[D5(107),D5(8490)],[D5(229),D5(8491)],[D5(969),D5(8486)]]),d9e=new Map([z5(453),z5(456),z5(459),z5(498),...B5(8072,8079),...B5(8088,8095),...B5(8104,8111),z5(8124),z5(8140),z5(8188)]),f9e=new Map([[`alnum`,O5`[\p{Alpha}\p{Nd}]`],[`alpha`,O5`\p{Alpha}`],[`ascii`,O5`\p{ASCII}`],[`blank`,O5`[\p{Zs}\t]`],[`cntrl`,O5`\p{Cc}`],[`digit`,O5`\p{Nd}`],[`graph`,O5`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,O5`\p{Lower}`],[`print`,O5`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,O5`[\p{P}\p{S}]`],[`space`,O5`\p{space}`],[`upper`,O5`\p{Upper}`],[`word`,O5`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,O5`\p{AHex}`]]);function p9e(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function z5(e){let t=D5(e);return[t.toLowerCase(),t]}function B5(e,t){return p9e(e,t).map(e=>z5(e))}var V5=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function m9e(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};H5(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:N5(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};s5(e,h9e,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 s5(e,g9e,a),s5(e,_9e,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var h9e={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=Y8();e.body[0].body.push(X8({negate:!0,body:r}),$8(`Any`));let i=Y8();i.body[0].body.push(Z8(`greedy`,0,1/0,e)),n(e7(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];M5(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=K5(t.get(e));if(n){let t=Y8({flags:n});t.body[0].body=e.body,e.body=[e7(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(e7(X8({body:[H8({body:[U8(`string_end`)]}),H8({body:[K8(10)]})]}),t));else if(c===`line_start`)o(e7(Z5(O5`(?<=\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&&C9e(e))o(e7(X8({negate:!0}),t));else if(d)throw Error(O5`Uses "\G" in a way that requires a subclass`);else o($5(U8(`string_start`),t)),s.strategy=`clip_search`}else if(c!==`string_end`&&c!==`string_start`)if(c===`string_end_newline`)o(e7(Z5(O5`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${I5})(?!${I5})|(?<!${I5})(?=${I5}))`,n=`(?:(?<=${I5})(?=${I5})|(?<!${I5})(?!${I5}))`;o(e7(Z5(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!X5(n)&&(n=G5(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!X5(r)&&(r=G5(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(e7(q8({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($5(J8(`digit`,{negate:l}),t));return}if(o&&(c===`space`||u===`space`)){n(e7(Q5(Z5(s9e),l),t));return}if(s&&(c===`word`||u===`word`)){n($5(J8(`word`,{negate:l}),t));return}if(c===`any`)n($5($8(`Any`),t));else if(c===`digit`)n($5($8(`Nd`,{negate:l}),t));else if(c!==`dot`)if(c===`text_segment`){if(r===`strict`)throw Error(O5`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=O5`\p{RI}{2}|${e}(?:\u200D${e})*`;n(e7(Z5(O5`(?>\r\n|${i?O5`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n($5($8(`AHex`,{negate:l}),t));else if(c===`newline`)n(e7(Z5(l?`[^
1180
1180
  ]`:`(?>\r
1181
1181
  ?|[
1182
- \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-${D5(e.codePointAt(0)-1)}${D5(e.codePointAt(2)+1)}-\u{10FFFF}`),n(e7(Z5(`[${e}]`),t))}else n(e7(Q5(Z5(l9e.get(u)),l),t));else if(c===`property`)R5.has(i5(u))||(e.key=`sc`);else if(c===`space`)n($5($8(`space`,{negate:l}),t));else if(c===`word`)n(e7(Q5(Z5(I5),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=Y8({flags:c});e.body[0].body=o(),i(e7(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&B8(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(O5`Uses "\K" in a way that's unsupported`);let o=X8({behind:!0});o.body[0].body=a(),i(e7(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(e7(X8({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=Y8();t.body[0].body.push(e.body),e.body=e7(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=J5(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(O5`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!X5(n)&&(n=G5(n,t),e.ref=n)}},p9e={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=$5(W5(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&M5(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=M5(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=j5(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?W5(0):U5(o,r.groupOriginByCopy,null),l=c;if(!s){let e=K5(_9e(o,e=>e.type===`Group`&&!!e.flags)),t=e?j5(r.globalFlags,e):r.globalFlags;h9e(t,r.currentFlags)||(l=Y8({flags:v9e(t)}),l.body[0].body.push(c))}n(e7(l,t),{traverse:!s})}},m9e={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=>g9e(t,e));i.length?i.length>1?n(e7(Y8({atomic:!0,body:i.reverse().map(e=>H8({body:[W8(e.number)]}))}),t)):e.ref=i[0].number:n(e7(X8({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=G8();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function H5(e){s5(e,{"*"({node:e,parent:t}){e.parent=t}})}function h9e(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function g9e(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=q5(n.parent);for(let r of t){if(r===n)break;if(r===e||Y5(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function U5(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]=U5(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function W5(e){let t=Q8(e);return t.isRecursive=!0,t}function _9e(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function G5(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 K5(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 v9e({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 q5(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function J5(e){let t=e.find(e=>e.kind===`search_start`||x9e(e,{negate:!1})||!y9e(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=J5(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function Y5(e,t){let n=q5(e)??[];for(let e of n)if(e===t||Y5(e,t))return!0;return!1}function y9e({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function b9e(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function x9e(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&B8(e.body[0],{type:`Assertion`,kind:`search_start`})}function X5(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function Z5(e,t){let n=V8(e,{...t,unicodePropertyMap:R5}).body;return n.length>1||n[0].body.length>1?Y8({body:n}):n[0].body[0]}function Q5(e,t){return e.negate=t,e}function $5(e,t){return e.parent=t,e}function e7(e,t){return H5(e),e.parent=t,e}function S9e(e,t){let n=F5(t),r=N5(n.target,`ES2024`),i=N5(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];s5(e,C9e,{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,n9e(w9e[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&&M5(f._captureTransfers,e.transferTo,[]).push(t)}),f}var C9e={"*":{enter({node:e},t){if(a7(e)){let n=t.getCurrentModI();t.pushModI(e.flags?j5({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){a7(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){n7(D5(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),r7(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&V5.has(e.value)&&t.setHasCasedChar()}},w9e={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?O5`\B`:O5`\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=D5(e),r=i7(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&n7(n)){let e=L5(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`);k5.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(o7)&&(o=[K8(45),...o.filter(e=>!o7(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||k5.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=Y8(),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=H8({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`&&!(k5.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=i7(n,i),o=i7(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&k9e(r7(e)).forEach(e=>{s.add(Array.isArray(e)?`${i7(e[0],i)}-${i7(e[1],i)}`:i7(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?`.`:`[^]`:O5`[^\n]`;if(e===`digit`)return t?O5`\D`:O5`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&V5.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?O5`\P`:O5`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?O5`\W`:O5`\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=j5(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${A9e(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)+j9e(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})`:O5`\g<${t}&R=${r}>`}},T9e=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),E9e=new Set([`-`,`\\`,`]`,`^`,`[`]),D9e=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),t7=new Map([[9,O5`\t`],[10,O5`\n`],[11,O5`\v`],[12,O5`\f`],[13,O5`\r`],[8232,O5`\u2028`],[8233,O5`\u2029`],[65279,O5`\uFEFF`]]),O9e=/^\p{Cased}$/u;function n7(e){return O9e.test(e)}function r7(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=D5(e);if(!n7(t))continue;let o=L5(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function i7(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(t7.has(e))return t7.get(e);if(e<32||e>126&&e<160||e>262143||t&&M9e(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?D9e:E9e:T9e,a=D5(e);return(i.has(a)?`\\`:``)+a}function k9e(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 A9e(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 j9e({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 a7({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function M9e(e){return e>47&&e<58}function o7({type:e,value:t}){return e===`Character`&&t===45}var N9e=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=F9e(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&&(P9e(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||=I9e(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 P9e(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 F9e(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)M5(n,t,{}).transferTo=e;return n}function I9e(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 L9e(e,t){let n=R9e(e,t);return n.options?new N9e(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function R9e(e,t){let n=F5(t),r=d9e(V8(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:R5}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=S9e(r,n),a=e9e(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Q7e($7e(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 z9e(e,t){return L9e(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function B9e(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>z9e(e,{target:t.target}),{createScanner(e){return new n7e(e,t)},createString(e){return{content:e}}}}async function s7(e){if(w3())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=x3.get(e);if(t!=null)return t;try{let t=G6e.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(O3,e)&&(t=O3[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 b3.has(e)||b3.set(e,n),n});return x3.set(e,n),await n}finally{x3.delete(e)}}function c7(e){return b3.get(e)??s7(e)}var l7=new Set;function u7(e){let t=[],n=new Set;for(let r of V9e(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 u7({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 u7({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function V9e(e){return H9e(e)?[e]:e}function H9e(e){return d7(e)||U9e(e)}function U9e(e){return typeof e.name==`string`&&typeof e.load==`function`}function d7(e){return typeof e.getThemes==`function`}function f7(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var W9e=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},G9e=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},K9e=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function q9e(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new W9e(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 G9e(i));let c=r,l=s().then(e=>{let a=f7(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 K9e(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 p7=q9e();function m7(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=p7.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,p7.getResolvedTheme(n)??p7.seedResolvedTheme(n,e);l7.has(n)||(l7.add(n),t.loadThemeSync(e))}}function h7({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:J9e(t)}}function J9e(e){return async()=>K6(f7(await e()))}var Y9e=`pierre`,X9e=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],g7=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],Z9e=[...g7,...X9e],Q9e=new Set(g7);function $9e(e){return Q9e.has(e)?`light`:`dark`}var eet={"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`},tet={"pierre-dark":()=>N(()=>import(`./pierre-dark-BE1q-b3U.js`),[]),"pierre-dark-soft":()=>N(()=>import(`./pierre-dark-soft-LwbHiy7Y.js`),[]),"pierre-dark-vibrant":()=>N(()=>import(`./pierre-dark-vibrant-C0LpAZKq.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>N(()=>import(`./pierre-dark-protanopia-deuteranopia-CmoiA9-7.js`),[]),"pierre-dark-tritanopia":()=>N(()=>import(`./pierre-dark-tritanopia-hSN4g2lI.js`),[]),"pierre-light":()=>N(()=>import(`./pierre-light-CowcJ50V.js`),[]),"pierre-light-soft":()=>N(()=>import(`./pierre-light-soft-DZJewTTo.js`),[]),"pierre-light-vibrant":()=>N(()=>import(`./pierre-light-vibrant-BYyM1ug_.js`),[]),"pierre-light-protanopia-deuteranopia":()=>N(()=>import(`./pierre-light-protanopia-deuteranopia-DAcnjrIl.js`),[]),"pierre-light-tritanopia":()=>N(()=>import(`./pierre-light-tritanopia-CPzP-LuK.js`),[])};function net(e){return h7({name:e,collection:Y9e,colorScheme:$9e(e),displayName:eet[e],load:tet[e]})}var ret=u7({themes:Z9e.map(e=>net(e))}),iet=`shiki`,_7=[`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`],aet=`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(`.`),oet=new Set(_7);function set(e){return oet.has(e)?`light`:`dark`}var cet={andromeeda:()=>N(()=>import(`./andromeeda-BNeYCHXk.js`),[]),"aurora-x":()=>N(()=>import(`./aurora-x-CH7IPTqK.js`),[]),"ayu-dark":()=>N(()=>import(`./ayu-dark-Gwa7IGEl.js`),[]),"ayu-light":()=>N(()=>import(`./ayu-light-CfQsU1za.js`),[]),"ayu-mirage":()=>N(()=>import(`./ayu-mirage-Czr4we6a.js`),[]),"catppuccin-frappe":()=>N(()=>import(`./catppuccin-frappe-C0QsWMj9.js`),[]),"catppuccin-latte":()=>N(()=>import(`./catppuccin-latte-CBqMKpD-.js`),[]),"catppuccin-macchiato":()=>N(()=>import(`./catppuccin-macchiato-Ba-LmgkD.js`),[]),"catppuccin-mocha":()=>N(()=>import(`./catppuccin-mocha-UdiwJY8k.js`),[]),"dark-plus":()=>N(()=>import(`./dark-plus-fEh1utf2.js`),[]),dracula:()=>N(()=>import(`./dracula-BteNSxBe.js`),[]),"dracula-soft":()=>N(()=>import(`./dracula-soft-kIJVe7gs.js`),[]),"everforest-dark":()=>N(()=>import(`./everforest-dark-BNfvFKFy.js`),[]),"everforest-light":()=>N(()=>import(`./everforest-light-BNyMwptp.js`),[]),"github-dark":()=>N(()=>import(`./github-dark-OZxO9CaM.js`),[]),"github-dark-default":()=>N(()=>import(`./github-dark-default-WMF7_Ep7.js`),[]),"github-dark-dimmed":()=>N(()=>import(`./github-dark-dimmed-DuB6izjU.js`),[]),"github-dark-high-contrast":()=>N(()=>import(`./github-dark-high-contrast-hcAb8j0M.js`),[]),"github-light":()=>N(()=>import(`./github-light-B7kcaBRI.js`),[]),"github-light-default":()=>N(()=>import(`./github-light-default-Bn7rOI3v.js`),[]),"github-light-high-contrast":()=>N(()=>import(`./github-light-high-contrast-ViJZ_fOo.js`),[]),"gruvbox-dark-hard":()=>N(()=>import(`./gruvbox-dark-hard-Cgl2mPuM.js`),[]),"gruvbox-dark-medium":()=>N(()=>import(`./gruvbox-dark-medium-DCX_afxc.js`),[]),"gruvbox-dark-soft":()=>N(()=>import(`./gruvbox-dark-soft-xSy3_D_R.js`),[]),"gruvbox-light-hard":()=>N(()=>import(`./gruvbox-light-hard-DyUjYTwb.js`),[]),"gruvbox-light-medium":()=>N(()=>import(`./gruvbox-light-medium-t9u9yTZC.js`),[]),"gruvbox-light-soft":()=>N(()=>import(`./gruvbox-light-soft-BwkRZulu.js`),[]),horizon:()=>N(()=>import(`./horizon-D9esxdtu.js`),[]),"horizon-bright":()=>N(()=>import(`./horizon-bright-CNAa2YaN.js`),[]),houston:()=>N(()=>import(`./houston-BWd77f8g.js`),[]),"kanagawa-dragon":()=>N(()=>import(`./kanagawa-dragon-BltL5Npt.js`),[]),"kanagawa-lotus":()=>N(()=>import(`./kanagawa-lotus-x5UUlq9Q.js`),[]),"kanagawa-wave":()=>N(()=>import(`./kanagawa-wave-CzXbKbXM.js`),[]),laserwave:()=>N(()=>import(`./laserwave-DKVcugnw.js`),[]),"light-plus":()=>N(()=>import(`./light-plus-DKgBJq08.js`),[]),"material-theme":()=>N(()=>import(`./material-theme-BadEBfe3.js`),[]),"material-theme-darker":()=>N(()=>import(`./material-theme-darker-CgX1d1NS.js`),[]),"material-theme-lighter":()=>N(()=>import(`./material-theme-lighter-wo_41JUX.js`),[]),"material-theme-ocean":()=>N(()=>import(`./material-theme-ocean-DbMwCxHP.js`),[]),"material-theme-palenight":()=>N(()=>import(`./material-theme-palenight-Db-YB2zW.js`),[]),"min-dark":()=>N(()=>import(`./min-dark-yqE0z6kx.js`),[]),"min-light":()=>N(()=>import(`./min-light-DPcLduMD.js`),[]),monokai:()=>N(()=>import(`./monokai-2u_Hse38.js`),[]),"night-owl":()=>N(()=>import(`./night-owl-CjKjAoQw.js`),[]),"night-owl-light":()=>N(()=>import(`./night-owl-light-PrK6APct.js`),[]),nord:()=>N(()=>import(`./nord-CTEC6wiS.js`),[]),"one-dark-pro":()=>N(()=>import(`./one-dark-pro-Bf5_ZHAs.js`),[]),"one-light":()=>N(()=>import(`./one-light-BbB92BMl.js`),[]),plastic:()=>N(()=>import(`./plastic-Dra6mGgc.js`),[]),poimandres:()=>N(()=>import(`./poimandres-5IL5df4X.js`),[]),red:()=>N(()=>import(`./red-ffKIm2h1.js`),[]),"rose-pine":()=>N(()=>import(`./rose-pine-BRBOTc14.js`),[]),"rose-pine-dawn":()=>N(()=>import(`./rose-pine-dawn-DqkM9du5.js`),[]),"rose-pine-moon":()=>N(()=>import(`./rose-pine-moon-qBEmDSsj.js`),[]),"slack-dark":()=>N(()=>import(`./slack-dark-DsT1PKI3.js`),[]),"slack-ochin":()=>N(()=>import(`./slack-ochin-BOYRpxv-.js`),[]),"snazzy-light":()=>N(()=>import(`./snazzy-light---Imn7h4.js`),[]),"solarized-dark":()=>N(()=>import(`./solarized-dark-CJeV_sol.js`),[]),"solarized-light":()=>N(()=>import(`./solarized-light-DgM7ubU-.js`),[]),"synthwave-84":()=>N(()=>import(`./synthwave-84-DrJ3lewE.js`),[]),"tokyo-night":()=>N(()=>import(`./tokyo-night-BLIujs_G.js`),[]),vesper:()=>N(()=>import(`./vesper-DqGzMUWf.js`),[]),"vitesse-black":()=>N(()=>import(`./vitesse-black-NKVZiefY.js`),[]),"vitesse-dark":()=>N(()=>import(`./vitesse-dark-BzOZR3Cg.js`),[]),"vitesse-light":()=>N(()=>import(`./vitesse-light-D_cKxtOE.js`),[])};function v7(e){return h7({name:e,collection:iet,colorScheme:set(e),load:cet[e]})}var uet=u7({themes:Object.freeze([..._7.map(e=>v7(e)),...aet.map(e=>v7(e))])});function y7(e){if(w3())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(p7.hasRegisteredTheme(e))return;let t=uet.getTheme(e);if(t!=null){p7.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function b7(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function det(e){y7(e);let t=await p7.resolveTheme(e);return b7(e,t),t}function fet(e){return p7.getResolvedTheme(e)??det(e)}var x7;async function S7({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){x7??=v8({themes:[],langs:[`text`],engine:n===`shiki-wasm`?z3(N(()=>import(`./wasm-BSSg2JG2.js`),[])):B9e()});let r=met(x7)?await x7:x7;x7=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=c7(e);`then`in t?i.push(t):C3(t,r)}let a=[];for(let t of e){let e=fet(t);`then`in e?a.push(e):m7(e,x7)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{C3(e,r)}),Promise.all(a).then(e=>{m7(e,r)})]),r}function pet(){if(x7!=null&&!(`then`in x7))return x7}function met(e=x7){return e!=null&&`then`in e}for(let e of ret.getThemes())p7.registerThemeIfAbsent(e.name,e.load);function C7(e=w2){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function het(e){for(let t of C7(e))if(!l7.has(t))return!1;return!0}function w7(e){return p7.hasResolvedThemes(e)}function T7(e,t){return N2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function get(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 _et(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 vet(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 yet({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:C2}}):bet({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[xet(r)]],properties:i})}function bet({name:e,prevName:t,iconType:n}){let r=[c4({tagName:`slot`,properties:{name:b2}}),l4({name:vet(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(l4({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:x2}})),c4({tagName:`div`,children:r,properties:{"data-header-content":``}})}function xet(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:S2}})),c4({tagName:`div`,children:t,properties:{"data-metadata":``}})}function Cet(e){return c4({tagName:`pre`,properties:wet(e)})}function wet({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 E7=new Map,Tet=0,D7={"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 O7(e){if(E7.has(e))return E7.get(e)??`text`;if(D7[e]!=null)return D7[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(E7.has(t[1]))return E7.get(t[1])??`text`;if(D7[t[1]]!=null)return D7[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return E7.has(n)?E7.get(n)??`text`:D7[n]??`text`}function k7(){return Tet}function A7(){return Object.fromEntries(E7)}function Eet(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:C7(t),preferredHighlighter:n}}function Det(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function Oet(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(`
1183
- `)),e}var j7=Symbol(`no-token`),M7=Symbol(`multiple-tokens`);function N7(e){let t=ket(e);if(t!=null)return t;let n=j7,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`){Aet(e,a);for(let t of e.children)P7(t)}else P7(e);r.push(e),i=[],a=void 0;return}for(let e of i)P7(e);r.push(c4({tagName:`span`,properties:{"data-char":a},children:i})),i=[],a=void 0},s=e=>{if(e!==j7){if(e===M7){n=M7;return}if(n===j7){n=e;return}n!==e&&(n=M7)}};for(let t of e.children){let e=t.type===`element`?N7(t):j7;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 ket(e){let t=e.properties[`data-char`];if(typeof t==`number`)return t}function P7(e){if(e.type===`element`){e.properties[`data-char`]=void 0;for(let t of e.children)P7(t)}}function Aet(e,t){e.properties[`data-char`]=t}function jet(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+Met(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 Met(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 F7(e=!1,t=!1){let n={lineInfo:[]},r=[{line(e){return delete e.properties.class,e},pre(t){let r=f3e(t),i=[];if(r!=null){let t=1;for(let a of r.children)a.type===`element`&&(e&&N7(a),i.push(Oet(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(Net,I7),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:I7}}var I7=jet({classPrefix:`hl-`}),Net={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 L7(e){return`--${e===`token`?`diffs-token`:`diffs`}-`}var Pet=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,Fet=/^0(?:\.0+)?%?$/;function Iet(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 Let(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 R7(e){if(e==null)return null;let t=Let(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 z7(e){if(e==null)return!1;let t=e.trim().toLowerCase();if(t===`transparent`||Pet.test(t))return!0;let n=Iet(t);return n!=null&&Fet.test(n)}function Ret(e,t,n){if(t==null||n==null)return!1;let r=R7(e),i=R7(t),a=R7(n);return r==null||i==null||a==null?!1:Math.abs(r-a)<Math.abs(r-i)}var B7=new WeakMap;function V7(e){let t=B7.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;H7(r,`editor.background`,i),H7(r,`editor.foreground`,a),H7(r,`sideBar.background`,o),H7(r,`sideBar.foreground`,s),H7(r,`input.background`,n[`input.background`]??o),H7(r,`sideBarSectionHeader.foreground`,n[`sideBarSectionHeader.foreground`]??s),H7(r,`list.activeSelectionForeground`,n[`list.activeSelectionForeground`]??s),H7(r,`gitDecoration.addedResourceForeground`,U7(n[`gitDecoration.addedResourceForeground`],n[`terminal.ansiGreen`],n[`editorGutter.addedBackground`])),H7(r,`gitDecoration.modifiedResourceForeground`,U7(n[`gitDecoration.modifiedResourceForeground`],n[`terminal.ansiBlue`],n[`editorGutter.modifiedBackground`])),H7(r,`gitDecoration.deletedResourceForeground`,U7(n[`gitDecoration.deletedResourceForeground`],n[`terminal.ansiRed`],n[`editorGutter.deletedBackground`]));let c=(z7(n[`list.focusOutline`])?void 0:n[`list.focusOutline`])??(z7(n.focusBorder)?void 0:n.focusBorder);c==null?delete r[`list.focusOutline`]:r[`list.focusOutline`]=c;let l=n[`list.hoverBackground`];l!=null&&(zet(l,o)||Ret(l,o,s))&&delete r[`list.hoverBackground`];let u=Object.freeze({...e,colors:Object.freeze(r)});return B7.set(e,u),u}function H7(e,t,n){n!=null&&n!==``&&(e[t]=n)}function U7(...e){for(let t of e)if(t!=null&&t!==``)return t}function zet(e,t){return t!=null&&e.toLowerCase()===t.toLowerCase()}function W7({theme:e=w2,highlighter:t,prefix:n}){let r=``;if(typeof e==`string`){let i=t.getTheme(e),a=V7(i);r+=`color:${a.fg};`,r+=`background-color:${a.bg};`,r+=`${L7(`global`)}fg:${a.fg};`,r+=`${L7(`global`)}bg:${a.bg};`,r+=G7(i,n)}else{let n=t.getTheme(e.dark),i=V7(n);r+=`${L7(`global`)}dark:${i.fg};`,r+=`${L7(`global`)}dark-bg:${i.bg};`,r+=G7(n,`dark`),n=t.getTheme(e.light),i=V7(n),r+=`${L7(`global`)}light:${i.fg};`,r+=`${L7(`global`)}light-bg:${i.bg};`,r+=G7(n,`light`)}return r}function G7(e,t){t=t==null?``:`${t}-`;let n=``,r=e.colors?.[`gitDecoration.addedResourceForeground`]??e.colors?.[`terminal.ansiGreen`];r!=null&&(n+=`${L7(`global`)}${t}addition-color:${r};`);let i=e.colors?.[`gitDecoration.deletedResourceForeground`]??e.colors?.[`terminal.ansiRed`];i!=null&&(n+=`${L7(`global`)}${t}deletion-color:${i};`);let a=e.colors?.[`gitDecoration.modifiedResourceForeground`]??e.colors?.[`terminal.ansiBlue`];return a!=null&&(n+=`${L7(`global`)}${t}modified-color:${a};`),n}function K7(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 q7=10,J7=13,Bet=4,Vet=40;function Het(e){let t=[0],n=e.indexOf(`\r`),r=e.indexOf(`
1182
+ \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-${D5(e.codePointAt(0)-1)}${D5(e.codePointAt(2)+1)}-\u{10FFFF}`),n(e7(Z5(`[${e}]`),t))}else n(e7(Q5(Z5(f9e.get(u)),l),t));else if(c===`property`)R5.has(i5(u))||(e.key=`sc`);else if(c===`space`)n($5($8(`space`,{negate:l}),t));else if(c===`word`)n(e7(Q5(Z5(I5),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=Y8({flags:c});e.body[0].body=o(),i(e7(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&B8(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(O5`Uses "\K" in a way that's unsupported`);let o=X8({behind:!0});o.body[0].body=a(),i(e7(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(e7(X8({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=Y8();t.body[0].body.push(e.body),e.body=e7(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=J5(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(O5`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!X5(n)&&(n=G5(n,t),e.ref=n)}},g9e={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=$5(W5(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&M5(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=M5(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=j5(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?W5(0):U5(o,r.groupOriginByCopy,null),l=c;if(!s){let e=K5(b9e(o,e=>e.type===`Group`&&!!e.flags)),t=e?j5(r.globalFlags,e):r.globalFlags;v9e(t,r.currentFlags)||(l=Y8({flags:x9e(t)}),l.body[0].body.push(c))}n(e7(l,t),{traverse:!s})}},_9e={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=>y9e(t,e));i.length?i.length>1?n(e7(Y8({atomic:!0,body:i.reverse().map(e=>H8({body:[W8(e.number)]}))}),t)):e.ref=i[0].number:n(e7(X8({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=G8();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function H5(e){s5(e,{"*"({node:e,parent:t}){e.parent=t}})}function v9e(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function y9e(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=q5(n.parent);for(let r of t){if(r===n)break;if(r===e||Y5(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function U5(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]=U5(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function W5(e){let t=Q8(e);return t.isRecursive=!0,t}function b9e(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function G5(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 K5(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 x9e({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 q5(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function J5(e){let t=e.find(e=>e.kind===`search_start`||w9e(e,{negate:!1})||!S9e(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=J5(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function Y5(e,t){let n=q5(e)??[];for(let e of n)if(e===t||Y5(e,t))return!0;return!1}function S9e({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function C9e(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function w9e(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&B8(e.body[0],{type:`Assertion`,kind:`search_start`})}function X5(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function Z5(e,t){let n=V8(e,{...t,unicodePropertyMap:R5}).body;return n.length>1||n[0].body.length>1?Y8({body:n}):n[0].body[0]}function Q5(e,t){return e.negate=t,e}function $5(e,t){return e.parent=t,e}function e7(e,t){return H5(e),e.parent=t,e}function T9e(e,t){let n=F5(t),r=N5(n.target,`ES2024`),i=N5(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];s5(e,E9e,{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,a9e(D9e[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&&M5(f._captureTransfers,e.transferTo,[]).push(t)}),f}var E9e={"*":{enter({node:e},t){if(a7(e)){let n=t.getCurrentModI();t.pushModI(e.flags?j5({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){a7(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){n7(D5(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),r7(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&V5.has(e.value)&&t.setHasCasedChar()}},D9e={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?O5`\B`:O5`\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=D5(e),r=i7(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&n7(n)){let e=L5(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`);k5.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(o7)&&(o=[K8(45),...o.filter(e=>!o7(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||k5.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=Y8(),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=H8({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`&&!(k5.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=i7(n,i),o=i7(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&M9e(r7(e)).forEach(e=>{s.add(Array.isArray(e)?`${i7(e[0],i)}-${i7(e[1],i)}`:i7(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?`.`:`[^]`:O5`[^\n]`;if(e===`digit`)return t?O5`\D`:O5`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&V5.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?O5`\P`:O5`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?O5`\W`:O5`\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=j5(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${N9e(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)+P9e(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})`:O5`\g<${t}&R=${r}>`}},O9e=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),k9e=new Set([`-`,`\\`,`]`,`^`,`[`]),A9e=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),t7=new Map([[9,O5`\t`],[10,O5`\n`],[11,O5`\v`],[12,O5`\f`],[13,O5`\r`],[8232,O5`\u2028`],[8233,O5`\u2029`],[65279,O5`\uFEFF`]]),j9e=/^\p{Cased}$/u;function n7(e){return j9e.test(e)}function r7(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=D5(e);if(!n7(t))continue;let o=L5(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function i7(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(t7.has(e))return t7.get(e);if(e<32||e>126&&e<160||e>262143||t&&F9e(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?A9e:k9e:O9e,a=D5(e);return(i.has(a)?`\\`:``)+a}function M9e(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 N9e(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 P9e({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 a7({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function F9e(e){return e>47&&e<58}function o7({type:e,value:t}){return e===`Character`&&t===45}var I9e=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=R9e(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&&(L9e(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||=z9e(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 L9e(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 R9e(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)M5(n,t,{}).transferTo=e;return n}function z9e(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 B9e(e,t){let n=V9e(e,t);return n.options?new I9e(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function V9e(e,t){let n=F5(t),r=m9e(V8(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:R5}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=T9e(r,n),a=r9e(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=t9e(n9e(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 H9e(e,t){return B9e(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function U9e(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>H9e(e,{target:t.target}),{createScanner(e){return new a7e(e,t)},createString(e){return{content:e}}}}async function s7(e){if(w3())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=x3.get(e);if(t!=null)return t;try{let t=J6e.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(O3,e)&&(t=O3[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 b3.has(e)||b3.set(e,n),n});return x3.set(e,n),await n}finally{x3.delete(e)}}function c7(e){return b3.get(e)??s7(e)}var l7=new Set;function u7(e){let t=[],n=new Set;for(let r of W9e(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 u7({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 u7({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function W9e(e){return G9e(e)?[e]:e}function G9e(e){return d7(e)||K9e(e)}function K9e(e){return typeof e.name==`string`&&typeof e.load==`function`}function d7(e){return typeof e.getThemes==`function`}function f7(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var q9e=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},J9e=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},Y9e=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function X9e(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new q9e(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 J9e(i));let c=r,l=s().then(e=>{let a=f7(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 Y9e(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 p7=X9e();function m7(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=p7.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,p7.getResolvedTheme(n)??p7.seedResolvedTheme(n,e);l7.has(n)||(l7.add(n),t.loadThemeSync(e))}}function h7({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:Z9e(t)}}function Z9e(e){return async()=>K6(f7(await e()))}var Q9e=`pierre`,$9e=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],g7=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],eet=[...g7,...$9e],tet=new Set(g7);function net(e){return tet.has(e)?`light`:`dark`}var ret={"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`},iet={"pierre-dark":()=>N(()=>import(`./pierre-dark-BE1q-b3U.js`),[]),"pierre-dark-soft":()=>N(()=>import(`./pierre-dark-soft-LwbHiy7Y.js`),[]),"pierre-dark-vibrant":()=>N(()=>import(`./pierre-dark-vibrant-C0LpAZKq.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>N(()=>import(`./pierre-dark-protanopia-deuteranopia-CmoiA9-7.js`),[]),"pierre-dark-tritanopia":()=>N(()=>import(`./pierre-dark-tritanopia-hSN4g2lI.js`),[]),"pierre-light":()=>N(()=>import(`./pierre-light-CowcJ50V.js`),[]),"pierre-light-soft":()=>N(()=>import(`./pierre-light-soft-DZJewTTo.js`),[]),"pierre-light-vibrant":()=>N(()=>import(`./pierre-light-vibrant-BYyM1ug_.js`),[]),"pierre-light-protanopia-deuteranopia":()=>N(()=>import(`./pierre-light-protanopia-deuteranopia-DAcnjrIl.js`),[]),"pierre-light-tritanopia":()=>N(()=>import(`./pierre-light-tritanopia-CPzP-LuK.js`),[])};function aet(e){return h7({name:e,collection:Q9e,colorScheme:net(e),displayName:ret[e],load:iet[e]})}var oet=u7({themes:eet.map(e=>aet(e))}),set=`shiki`,_7=[`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`],cet=`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(`.`),uet=new Set(_7);function det(e){return uet.has(e)?`light`:`dark`}var fet={andromeeda:()=>N(()=>import(`./andromeeda-BNeYCHXk.js`),[]),"aurora-x":()=>N(()=>import(`./aurora-x-CH7IPTqK.js`),[]),"ayu-dark":()=>N(()=>import(`./ayu-dark-Gwa7IGEl.js`),[]),"ayu-light":()=>N(()=>import(`./ayu-light-CfQsU1za.js`),[]),"ayu-mirage":()=>N(()=>import(`./ayu-mirage-Czr4we6a.js`),[]),"catppuccin-frappe":()=>N(()=>import(`./catppuccin-frappe-C0QsWMj9.js`),[]),"catppuccin-latte":()=>N(()=>import(`./catppuccin-latte-CBqMKpD-.js`),[]),"catppuccin-macchiato":()=>N(()=>import(`./catppuccin-macchiato-Ba-LmgkD.js`),[]),"catppuccin-mocha":()=>N(()=>import(`./catppuccin-mocha-UdiwJY8k.js`),[]),"dark-plus":()=>N(()=>import(`./dark-plus-fEh1utf2.js`),[]),dracula:()=>N(()=>import(`./dracula-BteNSxBe.js`),[]),"dracula-soft":()=>N(()=>import(`./dracula-soft-kIJVe7gs.js`),[]),"everforest-dark":()=>N(()=>import(`./everforest-dark-BNfvFKFy.js`),[]),"everforest-light":()=>N(()=>import(`./everforest-light-BNyMwptp.js`),[]),"github-dark":()=>N(()=>import(`./github-dark-OZxO9CaM.js`),[]),"github-dark-default":()=>N(()=>import(`./github-dark-default-WMF7_Ep7.js`),[]),"github-dark-dimmed":()=>N(()=>import(`./github-dark-dimmed-DuB6izjU.js`),[]),"github-dark-high-contrast":()=>N(()=>import(`./github-dark-high-contrast-hcAb8j0M.js`),[]),"github-light":()=>N(()=>import(`./github-light-B7kcaBRI.js`),[]),"github-light-default":()=>N(()=>import(`./github-light-default-Bn7rOI3v.js`),[]),"github-light-high-contrast":()=>N(()=>import(`./github-light-high-contrast-ViJZ_fOo.js`),[]),"gruvbox-dark-hard":()=>N(()=>import(`./gruvbox-dark-hard-Cgl2mPuM.js`),[]),"gruvbox-dark-medium":()=>N(()=>import(`./gruvbox-dark-medium-DCX_afxc.js`),[]),"gruvbox-dark-soft":()=>N(()=>import(`./gruvbox-dark-soft-xSy3_D_R.js`),[]),"gruvbox-light-hard":()=>N(()=>import(`./gruvbox-light-hard-DyUjYTwb.js`),[]),"gruvbox-light-medium":()=>N(()=>import(`./gruvbox-light-medium-t9u9yTZC.js`),[]),"gruvbox-light-soft":()=>N(()=>import(`./gruvbox-light-soft-BwkRZulu.js`),[]),horizon:()=>N(()=>import(`./horizon-D9esxdtu.js`),[]),"horizon-bright":()=>N(()=>import(`./horizon-bright-CNAa2YaN.js`),[]),houston:()=>N(()=>import(`./houston-BWd77f8g.js`),[]),"kanagawa-dragon":()=>N(()=>import(`./kanagawa-dragon-BltL5Npt.js`),[]),"kanagawa-lotus":()=>N(()=>import(`./kanagawa-lotus-x5UUlq9Q.js`),[]),"kanagawa-wave":()=>N(()=>import(`./kanagawa-wave-CzXbKbXM.js`),[]),laserwave:()=>N(()=>import(`./laserwave-DKVcugnw.js`),[]),"light-plus":()=>N(()=>import(`./light-plus-DKgBJq08.js`),[]),"material-theme":()=>N(()=>import(`./material-theme-BadEBfe3.js`),[]),"material-theme-darker":()=>N(()=>import(`./material-theme-darker-CgX1d1NS.js`),[]),"material-theme-lighter":()=>N(()=>import(`./material-theme-lighter-wo_41JUX.js`),[]),"material-theme-ocean":()=>N(()=>import(`./material-theme-ocean-DbMwCxHP.js`),[]),"material-theme-palenight":()=>N(()=>import(`./material-theme-palenight-Db-YB2zW.js`),[]),"min-dark":()=>N(()=>import(`./min-dark-yqE0z6kx.js`),[]),"min-light":()=>N(()=>import(`./min-light-DPcLduMD.js`),[]),monokai:()=>N(()=>import(`./monokai-2u_Hse38.js`),[]),"night-owl":()=>N(()=>import(`./night-owl-CjKjAoQw.js`),[]),"night-owl-light":()=>N(()=>import(`./night-owl-light-PrK6APct.js`),[]),nord:()=>N(()=>import(`./nord-CTEC6wiS.js`),[]),"one-dark-pro":()=>N(()=>import(`./one-dark-pro-Bf5_ZHAs.js`),[]),"one-light":()=>N(()=>import(`./one-light-BbB92BMl.js`),[]),plastic:()=>N(()=>import(`./plastic-Dra6mGgc.js`),[]),poimandres:()=>N(()=>import(`./poimandres-5IL5df4X.js`),[]),red:()=>N(()=>import(`./red-ffKIm2h1.js`),[]),"rose-pine":()=>N(()=>import(`./rose-pine-BRBOTc14.js`),[]),"rose-pine-dawn":()=>N(()=>import(`./rose-pine-dawn-DqkM9du5.js`),[]),"rose-pine-moon":()=>N(()=>import(`./rose-pine-moon-qBEmDSsj.js`),[]),"slack-dark":()=>N(()=>import(`./slack-dark-DsT1PKI3.js`),[]),"slack-ochin":()=>N(()=>import(`./slack-ochin-BOYRpxv-.js`),[]),"snazzy-light":()=>N(()=>import(`./snazzy-light---Imn7h4.js`),[]),"solarized-dark":()=>N(()=>import(`./solarized-dark-CJeV_sol.js`),[]),"solarized-light":()=>N(()=>import(`./solarized-light-DgM7ubU-.js`),[]),"synthwave-84":()=>N(()=>import(`./synthwave-84-DrJ3lewE.js`),[]),"tokyo-night":()=>N(()=>import(`./tokyo-night-BLIujs_G.js`),[]),vesper:()=>N(()=>import(`./vesper-DqGzMUWf.js`),[]),"vitesse-black":()=>N(()=>import(`./vitesse-black-NKVZiefY.js`),[]),"vitesse-dark":()=>N(()=>import(`./vitesse-dark-BzOZR3Cg.js`),[]),"vitesse-light":()=>N(()=>import(`./vitesse-light-D_cKxtOE.js`),[])};function v7(e){return h7({name:e,collection:set,colorScheme:det(e),load:fet[e]})}var pet=u7({themes:Object.freeze([..._7.map(e=>v7(e)),...cet.map(e=>v7(e))])});function y7(e){if(w3())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(p7.hasRegisteredTheme(e))return;let t=pet.getTheme(e);if(t!=null){p7.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function b7(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function met(e){y7(e);let t=await p7.resolveTheme(e);return b7(e,t),t}function het(e){return p7.getResolvedTheme(e)??met(e)}var x7;async function S7({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){x7??=v8({themes:[],langs:[`text`],engine:n===`shiki-wasm`?z3(N(()=>import(`./wasm-BSSg2JG2.js`),[])):U9e()});let r=_et(x7)?await x7:x7;x7=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=c7(e);`then`in t?i.push(t):C3(t,r)}let a=[];for(let t of e){let e=het(t);`then`in e?a.push(e):m7(e,x7)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{C3(e,r)}),Promise.all(a).then(e=>{m7(e,r)})]),r}function get(){if(x7!=null&&!(`then`in x7))return x7}function _et(e=x7){return e!=null&&`then`in e}for(let e of oet.getThemes())p7.registerThemeIfAbsent(e.name,e.load);function C7(e=w2){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function vet(e){for(let t of C7(e))if(!l7.has(t))return!1;return!0}function w7(e){return p7.hasResolvedThemes(e)}function T7(e,t){return N2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function yet(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 bet(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 xet(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 Cet({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:C2}}):wet({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[Tet(r)]],properties:i})}function wet({name:e,prevName:t,iconType:n}){let r=[c4({tagName:`slot`,properties:{name:b2}}),l4({name:xet(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(l4({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:x2}})),c4({tagName:`div`,children:r,properties:{"data-header-content":``}})}function Tet(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:S2}})),c4({tagName:`div`,children:t,properties:{"data-metadata":``}})}function Eet(e){return c4({tagName:`pre`,properties:Det(e)})}function Det({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 E7=new Map,Oet=0,D7={"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 O7(e){if(E7.has(e))return E7.get(e)??`text`;if(D7[e]!=null)return D7[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(E7.has(t[1]))return E7.get(t[1])??`text`;if(D7[t[1]]!=null)return D7[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return E7.has(n)?E7.get(n)??`text`:D7[n]??`text`}function k7(){return Oet}function A7(){return Object.fromEntries(E7)}function ket(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:C7(t),preferredHighlighter:n}}function Aet(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function jet(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(`
1183
+ `)),e}var j7=Symbol(`no-token`),M7=Symbol(`multiple-tokens`);function N7(e){let t=Met(e);if(t!=null)return t;let n=j7,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`){Net(e,a);for(let t of e.children)P7(t)}else P7(e);r.push(e),i=[],a=void 0;return}for(let e of i)P7(e);r.push(c4({tagName:`span`,properties:{"data-char":a},children:i})),i=[],a=void 0},s=e=>{if(e!==j7){if(e===M7){n=M7;return}if(n===j7){n=e;return}n!==e&&(n=M7)}};for(let t of e.children){let e=t.type===`element`?N7(t):j7;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 Met(e){let t=e.properties[`data-char`];if(typeof t==`number`)return t}function P7(e){if(e.type===`element`){e.properties[`data-char`]=void 0;for(let t of e.children)P7(t)}}function Net(e,t){e.properties[`data-char`]=t}function Pet(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+Fet(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 Fet(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 F7(e=!1,t=!1){let n={lineInfo:[]},r=[{line(e){return delete e.properties.class,e},pre(t){let r=h3e(t),i=[];if(r!=null){let t=1;for(let a of r.children)a.type===`element`&&(e&&N7(a),i.push(jet(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(Iet,I7),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:I7}}var I7=Pet({classPrefix:`hl-`}),Iet={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 L7(e){return`--${e===`token`?`diffs-token`:`diffs`}-`}var Let=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,Ret=/^0(?:\.0+)?%?$/;function zet(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 Bet(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 R7(e){if(e==null)return null;let t=Bet(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 z7(e){if(e==null)return!1;let t=e.trim().toLowerCase();if(t===`transparent`||Let.test(t))return!0;let n=zet(t);return n!=null&&Ret.test(n)}function Vet(e,t,n){if(t==null||n==null)return!1;let r=R7(e),i=R7(t),a=R7(n);return r==null||i==null||a==null?!1:Math.abs(r-a)<Math.abs(r-i)}var B7=new WeakMap;function V7(e){let t=B7.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;H7(r,`editor.background`,i),H7(r,`editor.foreground`,a),H7(r,`sideBar.background`,o),H7(r,`sideBar.foreground`,s),H7(r,`input.background`,n[`input.background`]??o),H7(r,`sideBarSectionHeader.foreground`,n[`sideBarSectionHeader.foreground`]??s),H7(r,`list.activeSelectionForeground`,n[`list.activeSelectionForeground`]??s),H7(r,`gitDecoration.addedResourceForeground`,U7(n[`gitDecoration.addedResourceForeground`],n[`terminal.ansiGreen`],n[`editorGutter.addedBackground`])),H7(r,`gitDecoration.modifiedResourceForeground`,U7(n[`gitDecoration.modifiedResourceForeground`],n[`terminal.ansiBlue`],n[`editorGutter.modifiedBackground`])),H7(r,`gitDecoration.deletedResourceForeground`,U7(n[`gitDecoration.deletedResourceForeground`],n[`terminal.ansiRed`],n[`editorGutter.deletedBackground`]));let c=(z7(n[`list.focusOutline`])?void 0:n[`list.focusOutline`])??(z7(n.focusBorder)?void 0:n.focusBorder);c==null?delete r[`list.focusOutline`]:r[`list.focusOutline`]=c;let l=n[`list.hoverBackground`];l!=null&&(Het(l,o)||Vet(l,o,s))&&delete r[`list.hoverBackground`];let u=Object.freeze({...e,colors:Object.freeze(r)});return B7.set(e,u),u}function H7(e,t,n){n!=null&&n!==``&&(e[t]=n)}function U7(...e){for(let t of e)if(t!=null&&t!==``)return t}function Het(e,t){return t!=null&&e.toLowerCase()===t.toLowerCase()}function W7({theme:e=w2,highlighter:t,prefix:n}){let r=``;if(typeof e==`string`){let i=t.getTheme(e),a=V7(i);r+=`color:${a.fg};`,r+=`background-color:${a.bg};`,r+=`${L7(`global`)}fg:${a.fg};`,r+=`${L7(`global`)}bg:${a.bg};`,r+=G7(i,n)}else{let n=t.getTheme(e.dark),i=V7(n);r+=`${L7(`global`)}dark:${i.fg};`,r+=`${L7(`global`)}dark-bg:${i.bg};`,r+=G7(n,`dark`),n=t.getTheme(e.light),i=V7(n),r+=`${L7(`global`)}light:${i.fg};`,r+=`${L7(`global`)}light-bg:${i.bg};`,r+=G7(n,`light`)}return r}function G7(e,t){t=t==null?``:`${t}-`;let n=``,r=e.colors?.[`gitDecoration.addedResourceForeground`]??e.colors?.[`terminal.ansiGreen`];r!=null&&(n+=`${L7(`global`)}${t}addition-color:${r};`);let i=e.colors?.[`gitDecoration.deletedResourceForeground`]??e.colors?.[`terminal.ansiRed`];i!=null&&(n+=`${L7(`global`)}${t}deletion-color:${i};`);let a=e.colors?.[`gitDecoration.modifiedResourceForeground`]??e.colors?.[`terminal.ansiBlue`];return a!=null&&(n+=`${L7(`global`)}${t}modified-color:${a};`),n}function K7(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 q7=10,J7=13,Uet=4,Wet=40;function Get(e){let t=[0],n=e.indexOf(`\r`),r=e.indexOf(`
1184
1184
  `),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(`
1185
1185
  `,o)):(o=n+1,n=e.indexOf(`\r`,o)):(o=r+1,r=e.indexOf(`
1186
- `,o)),t.push(o),++a===Bet){if(o-i<=Vet){for(let n=o;n<e.length;n++){let r=e.charCodeAt(n);(r===q7||r===J7)&&(r===J7&&n+1<e.length&&e.charCodeAt(n+1)===q7&&n++,t.push(n+1))}return t}i=o,a=0}}return t}function Y7(e){let t=Het(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 Uet={forcePlainText:!1};function X7(e,t,{theme:n=w2,tokenizeMaxLineLength:r,useTokenTransformer:i},{forcePlainText:a,startingLine:o,totalLines:s,lines:c}=Uet){a?(o??=0,s??=1/0):(o=0,s=1/0);let l=o>0||s<1/0,{state:u,transformers:d}=F7(i),f=a?`text`:e.lang??O7(e.name),p=typeof n==`string`?t.getTheme(n).type:void 0,m=W7({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:L7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0}:{lang:f,themes:n,transformers:d,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0},g=K7(t.codeToHast(l?Wet(c??Y7(e.contents),o,s):e.contents,h)),_=l?Array(o):g;return l&&_.push(...g),{code:_,themeStyles:m,baseThemeType:p}}function Wet(e,t,n){if(e.length===0)return``;let r=Math.min(t+n,e.length);return e.slice(t,r).join(``)}var Get=`-1,-1`;function Ket(e){return e?.some(e=>e.lineNumber===0)??!1}function qet(e){let t=e[0];return t!=null&&t.length>0?t:void 0}function Jet(e){return e.startingLine===0&&e.totalLines>0}function Yet(e,t){return e.endsWith(`\r
1186
+ `,o)),t.push(o),++a===Uet){if(o-i<=Wet){for(let n=o;n<e.length;n++){let r=e.charCodeAt(n);(r===q7||r===J7)&&(r===J7&&n+1<e.length&&e.charCodeAt(n+1)===q7&&n++,t.push(n+1))}return t}i=o,a=0}}return t}function Y7(e){let t=Get(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 Ket={forcePlainText:!1};function X7(e,t,{theme:n=w2,tokenizeMaxLineLength:r,useTokenTransformer:i},{forcePlainText:a,startingLine:o,totalLines:s,lines:c}=Ket){a?(o??=0,s??=1/0):(o=0,s=1/0);let l=o>0||s<1/0,{state:u,transformers:d}=F7(i),f=a?`text`:e.lang??O7(e.name),p=typeof n==`string`?t.getTheme(n).type:void 0,m=W7({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:L7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0}:{lang:f,themes:n,transformers:d,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0},g=K7(t.codeToHast(l?qet(c??Y7(e.contents),o,s):e.contents,h)),_=l?Array(o):g;return l&&_.push(...g),{code:_,themeStyles:m,baseThemeType:p}}function qet(e,t,n){if(e.length===0)return``;let r=Math.min(t+n,e.length);return e.slice(t,r).join(``)}var Jet=`-1,-1`;function Yet(e){return e?.some(e=>e.lineNumber===0)??!1}function Xet(e){let t=e[0];return t!=null&&t.length>0?t:void 0}function Zet(e){return e.startingLine===0&&e.totalLines>0}function Qet(e,t){return e.endsWith(`\r
1187
1187
  `)?t+`\r
1188
1188
  `:e.endsWith(`\r`)?t+`\r`:e.endsWith(`
1189
1189
  `)?t+`
1190
- `:t}function Xet(e,t){return c4({tagName:`div`,children:e,properties:{"data-content":``,style:`grid-row: span ${t}`}})}function Z7(e){return(e.lang??O7(e.name))===`text`}var Zet=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
1190
+ `:t}function $et(e,t){return c4({tagName:`div`,children:e,properties:{"data-content":``,style:`grid-row: span ${t}`}})}function Z7(e){return(e.lang??O7(e.name))===`text`}var ett=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
1191
1191
  <symbol id="diffs-icon-arrow-right-short" viewBox="0 0 16 16">
1192
1192
  <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"/>
1193
1193
  </symbol>
@@ -1239,7 +1239,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[i5(e),e])),o9e=new Map([[`s`,D5(383)],[D5(38
1239
1239
  <symbol id="diffs-icon-symbol-ref" viewBox="0 0 16 16">
1240
1240
  <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"/>
1241
1241
  </symbol>
1242
- </svg>`;function Qet(e,t){return e==null||t==null?e===t:$et(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 Q7={};function $et(e=Q7,t=Q7){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 ett(e){let t=document.createElement(`div`);return t.dataset.annotationSlot=``,t.slot=e,t.style.whiteSpace=`normal`,t}function ttt(){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 ntt(){let e=document.createElement(`style`);return e.setAttribute(H4e,``),e}var rtt=`@layer base {
1242
+ </svg>`;function ttt(e,t){return e==null||t==null?e===t:ntt(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 Q7={};function ntt(e=Q7,t=Q7){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 rtt(e){let t=document.createElement(`div`);return t.dataset.annotationSlot=``,t.slot=e,t.style.whiteSpace=`normal`,t}function itt(){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 att(){let e=document.createElement(`style`);return e.setAttribute(G4e,``),e}var ott=`@layer base {
1243
1243
  :host {
1244
1244
  --diffs-font-fallback: "SF Mono", Monaco, Consolas, "Ubuntu Mono", "Liberation Mono",
1245
1245
  "Courier New", monospace;
@@ -2517,15 +2517,15 @@ XID_Start XIDS`.split(/\s/).map(e=>[i5(e),e])),o9e=new Map([[`s`,D5(383)],[D5(38
2517
2517
  }
2518
2518
 
2519
2519
  @layer theme, rendered, unsafe;
2520
- `,$7;function e9(e){if($7!=null)return $7;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(U4e,`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),$7=Math.max(n.offsetHeight-n.clientHeight,0),n.remove(),$7}function t9(e){return`${T2}: ${e==null?`var(--diffs-scrollbar-gutter-fallback)`:`${e}px`};`}var n9=`@layer base, theme, rendered, unsafe;`,itt=RegExp(`${ctt(T2)}\\s*:\\s*[^;]+;`);function att(e){return`${n9}
2520
+ `,$7;function e9(e){if($7!=null)return $7;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(K4e,`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),$7=Math.max(n.offsetHeight-n.clientHeight,0),n.remove(),$7}function t9(e){return`${T2}: ${e==null?`var(--diffs-scrollbar-gutter-fallback)`:`${e}px`};`}var n9=`@layer base, theme, rendered, unsafe;`,stt=RegExp(`${dtt(T2)}\\s*:\\s*[^;]+;`);function ctt(e){return`${n9}
2521
2521
  @layer unsafe {
2522
2522
  ${e}
2523
- }`}function ott(e,t=`system`,n){return`${n9}
2523
+ }`}function ltt(e,t=`system`,n){return`${n9}
2524
2524
  @layer rendered {
2525
2525
  :host {${t===`system`?``:`
2526
2526
  color-scheme: ${t};`}
2527
2527
  ${t9(n)}
2528
2528
  ${e}
2529
2529
  }
2530
- }`}function stt(e,t){let n=t9(t);return e.replace(itt,n)}function ctt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ltt({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 utt(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function dtt(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 ftt(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function ptt(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function mtt(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 htt({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=gtt(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function gtt(){let e=document.createElement(`style`);return e.setAttribute(V4e,``),e}var _tt=void 0;function vtt(){return _tt??=`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(rtt)),t.adoptedStyleSheets=[e]}connectedCallback(){e9(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(y2,t)}function ytt(e){return{...E2,...e}}function btt(e,t){let n=xtt(e,t);return t?n:e.diffHeaderHeight+n}function xtt(e,t){return e.paddingTop??(t?e.spacing:0)}function Stt(e){return e.paddingBottom??e.spacing}function Ctt(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function r9(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function i9(e,t){return N2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function a9({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 o9({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 s9(e){return[L2(e.additionStart,e.additionCount)+1,R2(e.additionStart,e.additionCount)+1]}function c9({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 wtt(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-R2(t.additionStart,t.additionCount),r=e.deletionLines.length-R2(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function l9({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-R2(n.additionStart,n.additionCount),i=e.deletionLines.length-R2(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 u9({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=l9({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 Ttt({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]=s9(a);if(t<o){let s=c9({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=u9({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]=s9(a);return t<o+i.fromStart||t>=o+i.rangeSize}function Ett({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]=s9(n),l=c9({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=u9({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??Ctt(e)}function f9({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function Dtt({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 Ott(e){return e!==`simple`&&e!==`metadata`}function ktt({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!Dtt({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=d9({type:e,metrics:t}),a=f9({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function Att({type:e,metrics:t}){if(!Ott(e))return;let n=d9({type:e,metrics:t}),r=f9({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function p9({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=jtt({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=L2(r.deletionStart,r.deletionCount),s=L2(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=c9({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?u9({fileDiff:e,hunkIndex:n,expandedHunks:i,collapsedContextThreshold:a,errorPrefix:`iterateOverDiff`}):void 0,p=d.fromStart+d.fromEnd;function m(e,n){return f==null||f.collapsedLines<=0||f.fromStart+f.fromEnd>0?0:t===`unified`?e===r.unifiedLineStart+r.unifiedLineCount-1?f.collapsedLines:0:n===r.splitLineStart+r.splitLineCount-1?f.collapsedLines:0}let h=d.collapsedLines===0;function g(){return h?0:(h=!0,d.collapsedLines)}if(c.shouldSkip(p,p))c.incrementCounts(p,p),g();else{let e=r.unifiedLineStart-d.rangeSize,i=r.splitLineStart-d.rangeSize,a=l-d.rangeSize,f=u-d.rangeSize,p=o+1-d.rangeSize,m=s+1-d.rangeSize;if(m9(c,d.fromStart,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:0,collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}))||(e=r.unifiedLineStart-d.fromEnd,i=r.splitLineStart-d.fromEnd,a=l-d.fromEnd,f=u-d.fromEnd,p=o+1-d.fromEnd,m=s+1-d.fromEnd,m9(c,d.fromEnd,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}),()=>{g()})))break hunkIterator}let _=r.unifiedLineStart,v=r.splitLineStart,y=l,b=u,x=o+1,S=s+1,C=r.hunkContent.at(-1);for(let e of r.hunkContent){if(c.shouldBreak())break hunkIterator;let i=e===C;if(e.type===`context`){if(c.shouldSkip(e.lines,e.lines))c.incrementCounts(e.lines,e.lines),g();else if(m9(c,e.lines,t,t=>{let a=i&&t===e.lines-1,o=_+t,s=v+t;return c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:m(o,s),type:`context`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:a&&r.noEOFCRDeletions,unifiedLineIndex:o,splitLineIndex:s},additionLine:{unifiedLineIndex:o,splitLineIndex:s,lineIndex:b+t,lineNumber:S+t,noEOFCR:a&&r.noEOFCRAdditions}})},()=>{g()}))break hunkIterator;_+=e.lines,v+=e.lines,y+=e.lines,b+=e.lines,x+=e.lines,S+=e.lines}else{let a=Math.max(e.deletions,e.additions),o=e.deletions+e.additions;if(!c.shouldSkip(o,a)){let s=Ptt(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(Ftt({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:l,diffStyle:t,index:s,unifiedLineIndex:_,splitLineIndex:v,additionLineIndex:b,deletionLineIndex:y,additionLineNumber:S,deletionLineNumber:x,content:e,isLastContent:i,unifiedCount:o,splitCount:a}),!0))break hunkIterator}}g(),c.incrementCounts(o,a),_+=o,v+=a,y+=e.deletions,b+=e.additions,x+=e.deletions,S+=e.additions}}if(f!=null){let{collapsedLines:n,fromStart:r,fromEnd:i}=f,a=r+i;if(m9(c,a,t,t=>{let r=t===a-1;return c.emit({hunkIndex:e.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:r?n:0,type:`context-expanded`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:!1,unifiedLineIndex:_+t,splitLineIndex:v+t},additionLine:{unifiedLineIndex:_+t,splitLineIndex:v+t,lineIndex:b+t,lineNumber:S+t,noEOFCR:!1}})},void 0,()=>c.shouldBreak()))break hunkIterator}}}function jtt({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=Mtt({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 Mtt({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=c9({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?u9({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 Ntt(e,t,n){if(!e.isWindowedHighlight||t<=0)return[0,t];let r=[];function i(n){let i=Math.max(0,e.viewportStart-n),a=Math.min(t,e.viewportEnd-n);a>i&&r.push([i,a])}if(n!==`split`&&i(e.unifiedCount),n!==`unified`&&i(e.splitCount),r.length===0)return[0,0];let a=r[0][0],o=r[0][1];for(let e=1;e<r.length;e++){let t=r[e];a=Math.min(a,t[0]),o=Math.max(o,t[1])}return[a,o]}function m9(e,t,n,r,i,a){let[o,s]=Ntt(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 Ptt(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 Ftt({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 Itt={forcePlainText:!1};function h9(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=Itt){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=W7({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)??Rtt();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)}p9({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&&Ltt({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}=ztt({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 Ltt({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=I2(e),t=I2(t),e.length>s||t.length>s))return;let c=o===`char`?n3e(e,t):o3e(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?(o9({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),o9({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?o9({item:e,arr:l,enableJoin:d,isLastItem:t}):o9({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(a9({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(a9({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function Rtt(){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 ztt({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=w2,...l}}){let u=s??O7(e.name),d=s??O7(t.name),{state:f,transformers:p}=F7(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,K7(i.codeToHast(I2(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,K7(i.codeToHast(I2(t.contents),m)))}}function g9(e){let t=e.lang??O7(e.name),n=e.lang??(e.prevName==null?`text`:O7(e.prevName));return t===`text`&&n===`text`}function _9(e){let t=[];for(let n of e){let e=b3.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function v9(e){for(let t of Array.isArray(e)?e:[e])if(!b3.has(t))return!1;return!0}async function y9(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=c7(r)??s7(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 b9(e){return p7.getResolvedThemes(e)}async function x9(e){for(let t of e)y7(t);let t=await p7.resolveThemes(e);for(let n=0;n<e.length;n++)b7(e[n],t[n]);return t}var S9={light:`pierre-light`,dark:`pierre-dark`};function Btt(e){return e===`dark`?S9.dark:S9.light}var C9=2166136261,w9=16777619,Vtt=2654435769,Htt=2246822507;function T9(e,t=C9,n=w9){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 Utt(e,t=`diff-panel`){let n=e.trim(),r=T9(n,C9,w9).toString(36),i=T9(n,Vtt,Htt).toString(36);return`${t}:${n.length}:${r}:${i}`}var Wtt=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,Gtt=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function Ktt(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 qtt(e){let t=e.split(`,`).map(Ktt).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var E9={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 Jtt(e,t){let n=[[E9.fontSans,t.fontFamilySans,Wtt],[E9.fontMono,t.fontFamilyCode,Gtt],[E9.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[E9.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=qtt(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(E9.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(E9.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(E9.glassOpacity,`${String(t.glassOpacity)}%`),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}var D9=`themeId`,O9=`forge:theme-boot:v1`;function Ytt(e,t){try{window.localStorage.setItem(O9,JSON.stringify({appearance:t,background:e}))}catch{}}function Xtt(){try{window.localStorage.removeItem(O9)}catch{}}function k9(){return typeof document>`u`?null:document.documentElement}function A9(){let e=k9();if(e!==null){for(let t of bn)e.style.removeProperty(on[t]);delete e.dataset[D9],Xtt()}}function Ztt(e,t){let n=k9();if(n===null)return;let r=t===`dark`?e.dark:e.light;for(let e of bn){let t=r[e];if(t===void 0){n.style.removeProperty(on[e]);continue}n.style.setProperty(on[e],t)}n.dataset[D9]=e.id,r.background!==void 0&&Ytt(r.background,t)}function Qtt(e,t){if(e===`forge`){A9();return}let n=kte(e);if(n===void 0){A9();return}Ztt(n,t)}var $tt=`forge:theme`,j9=`theme-color`,ent=`meta[name="${j9}"][data-dynamic-theme-color="true"]`,M9=`(prefers-color-scheme: dark)`,tnt={dark:`#0a0a0a`,light:`#ffffff`};function nnt(){return typeof window<`u`&&typeof localStorage<`u`}function N9(e){return e===`system`||e===`light`||e===`dark`}function P9(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function rnt(){if(!nnt())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(GY);if(e){let t=JY(JSON.parse(e));return{theme:N9(t.theme)?t.theme:`system`,uiFontSize:P9(t.uiFontSize,16),codeFontSize:P9(t.codeFontSize,13)}}let t=window.localStorage.getItem($tt);return{theme:N9(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function int(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(M9).matches?`dark`:`light`}function F9(e){return e===`system`?int():e}function ant(){let e=document.querySelector(ent);return e||(e=document.createElement(`meta`),e.name=j9,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function I9(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 ont(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function snt(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function L9(e=snt()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=I9(getComputedStyle(ont()).backgroundColor),n=I9(getComputedStyle(document.body).backgroundColor),r=t??n??tnt[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,ant().setAttribute(`content`,r)}function cnt(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function R9(e,t=!1){let n=F9(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,L9(n),cnt(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function z9(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${P9(e,16)}px`)}function B9(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${P9(e,13)}px`)}function V9(e){z9(e.uiFontSize),B9(e.codeFontSize)}if(typeof document<`u`){let e=rnt();R9(e.theme),V9(e)}function lnt(){let e=(0,ul.c)(34),t=C0(pnt),n=C0(fnt),r=C0(dnt),i=C0(unt),{updateSettings:a}=w0(),o;e[0]===t?o=e[1]:(o=()=>F9(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(R9(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=P9(e,16);a({uiFontSize:t}),z9(t)},e[6]=a,e[7]=p);let m=p,h;e[8]===a?h=e[9]:(h=e=>{let t=P9(e,13);a({codeFontSize:t}),B9(t)},e[8]=a,e[9]=h);let g=h,_,v;e[10]===t?(_=e[11],v=e[12]):(_=()=>{c(R9(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=()=>{V9({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=()=>{Qtt(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(M9),n=()=>{c(R9(`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 unt(e){return e.codeFontSize}function dnt(e){return e.uiFontSize}function fnt(e){return e.themeId}function pnt(e){return e.theme}function mnt(){let e=(0,ul.c)(10),t=C0(Snt),n=C0(xnt),r=C0(bnt),i=C0(ynt),a=C0(vnt),o=C0(_nt),s=C0(gnt),c=C0(hnt),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`||Jtt(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 hnt(e){return e.glassOpacity}function gnt(e){return e.fontSmoothing}function _nt(e){return e.terminalFontSize}function vnt(e){return e.promptFontSize}function ynt(e){return e.fontFamilyTerminal}function bnt(e){return e.fontFamilyComposer}function xnt(e){return e.fontFamilyCode}function Snt(e){return e.fontFamilySans}function Cnt(e){let t=(0,F.useRef)(e);return(0,F.useInsertionEffect)(()=>void(t.current=e)),(0,F.useCallback)((...e)=>t.current(...e),[])}var wnt=(0,F.createContext)(void 0);function Tnt(){return(0,F.useContext)(wnt)}var Ent={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},Dnt={display:`contents`};function Ont(){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`)}},knt=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=w2,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??w2,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()||i9(a,this.renderOptions))return;let o=C7(e),c=[];if(N2(a.theme,this.renderOptions.theme)||(c=w7(o)?b9(o):await x9(o)),!s())return;if(this.highlighter!=null)m7(c,this.highlighter);else{let e=await S7({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=C7(this.renderOptions.theme),i=[];if(i=w7(r)?b9(r):await x9(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=v9(e)?_9(e):await y9(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([S7({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=k7(),i=r>0?A7():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);Z7(t)||n!=null&&T7(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||Z7(e)||t!=null&&T7(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 X7(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);g9(t)||n!=null&&i9(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||g9(e)||t!=null&&i9(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:h9(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&&(v9(r)?t.request.resolvedLanguages=_9(r):t.request.resolvedLanguages=await y9(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)||!T7(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)||!i9(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){Ant(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=k7();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=A7())}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)&&o4(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)&&r9(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 Ant(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??O7(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??O7(e.request.diff.name)),t.add(e.request.diff.lang??O7(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 jnt({poolOptions:e,highlighterOptions:t}){return X9??=new knt(e,t),X9}function Mnt(){X9!=null&&(X9.terminate(),X9=void 0)}var Z9=(0,F.createContext)(void 0),Q9=0;function Nnt({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,F.useState)(()=>{if(!(typeof window>`u`))return jnt({poolOptions:t,highlighterOptions:n})});return(0,F.useInsertionEffect)(()=>{if(r!=null)return Q9++,()=>{Q9--}},[r]),(0,F.useEffect)(()=>()=>{Q9===0&&Mnt()},[]),(0,Fr.jsx)(Z9.Provider,{value:r,children:e})}function Pnt(){return(0,F.useContext)(Z9)}function $9(e){return Qt(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,Ir&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function Fnt(e){let t=(0,ul.c)(10),n=Ir&&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=Qt(`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,Fr.jsx)(`div`,{className:$9(e.mode),children:e.header}):(0,Fr.jsx)(`div`,{className:`border-b border-border`,children:(0,Fr.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,Fr.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 Int(){let e=(0,ul.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Fr.jsx)(VY,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,Fr.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,Fr.jsx)(VY,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,Fr.jsx)(VY,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(Fr.Fragment,{children:[r,(0,Fr.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,Fr.jsx)(VY,{className:`size-7 rounded-md`}),(0,Fr.jsx)(VY,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function Lnt(e){let t=(0,ul.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Fr.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,Fr.jsx)(VY,{className:`h-4 w-32 rounded-full`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`space-y-2`,children:[(0,Fr.jsx)(VY,{className:`h-3 w-full rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-full rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-10/12 rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-11/12 rounded-full`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,Fr.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,Fr.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,Fr.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{Xet as $,mJ as $a,WYe as $i,L2e as $n,lq as $o,j1e as $r,rre as $s,A2 as $t,i9 as A,WJ as Aa,br as Ac,JXe as Ai,_2 as An,Gq as Ao,n0 as Ar,Mi as As,K4 as At,dtt as B,gqe as Ba,DZ as Bi,p4e as Bn,PGe as Bo,d0 as Br,Si as Bs,c4 as Bt,ktt as C,mJe as Ca,Kne as Cc,vZe as Ci,B4e as Cn,Wq as Co,w0 as Cr,Ro as Cs,A6e as Ct,Att as D,Pqe as Da,Wne as Dc,mQ as Di,j4e as Dn,Vq as Do,m0 as Dr,Lo as Ds,J4 as Dt,u9 as E,JJ as Ea,yr as Ec,ZXe as Ei,D4e as En,zq as Eo,C0e as Er,Uo as Es,q3e as Et,vtt as F,HJ as Fa,xXe as Fi,v4e as Fn,HGe as Fo,v0e as Fr,Oi as Fs,m4 as Ft,att as G,PKe as Ga,fZ as Gi,V2e as Gn,jGe as Go,R1e as Gr,ui as Gs,R2 as Gt,ltt as H,jJ as Ha,CZ as Hi,$0 as Hn,CGe as Ho,K1e as Hr,gre as Hs,s4 as Ht,htt as I,PJ as Ia,jZ as Ii,h4e as In,BGe as Io,p0e as Ir,Di as Is,d4 as It,ttt as J,zKe as Ja,yZ as Ji,R2e as Jn,MGe as Jo,B1e as Jr,ai as Js,e3e as Jt,e9 as K,IKe as Ka,UYe as Ki,B2e as Kn,tGe as Ko,M1e as Kr,li as Ks,L2 as Kt,mtt as L,Aqe as La,TXe as Li,g4e as Ln,RGe as Lo,h0e as Lr,Ti as Ls,h3e as Lt,ytt as M,zJ as Ma,dQ as Mi,y4e as Mn,tKe as Mo,l0e as Mr,ji as Ms,I4 as Mt,btt as N,Mqe as Na,pQ as Ni,f2 as Nn,Pq as No,m0e as Nr,Ai as Ns,L4 as Nt,wtt as O,KJ as Oa,Fne as Oc,GXe as Oi,M4e as On,Hq as Oo,i0 as Or,Cre as Os,K3e as Ot,Stt as P,UJ as Pa,PZ as Pi,m4e as Pn,qGe as Po,d0e as Pr,Ei as Ps,F4 as Pt,Z7 as Q,xJ as Qa,vZ as Qi,G0e as Qn,kGe as Qo,L1e as Qr,ore as Qs,M2 as Qt,ptt as R,cqe as Ra,NZ as Ri,_4e as Rn,WGe as Ro,g0e as Rr,wi as Rs,m3e as Rt,s9 as S,zY as Sa,Tr as Sc,gZe as Si,b2 as Sn,nKe as So,C0 as Sr,Ko as Ss,k6e as St,l9 as T,Nqe as Ta,Rne as Tc,bQ as Ti,O4e as Tn,Lq as To,E0e as Tr,Ho as Ts,Y4 as Tt,stt as U,kJ as Ua,SZ as Ui,t2 as Un,wGe as Uo,q1e as Ur,mre as Us,o4 as Ut,utt as V,QKe as Va,wZ as Vi,e2 as Vn,Tq as Vo,_0e as Vr,gi as Vs,l4 as Vt,ott as W,WKe as Wa,HYe as Wi,r2 as Wn,OGe as Wo,I1e as Wr,hre as Ws,u3e as Wt,Qet as X,EJ as Xa,_Z as Xi,r2e as Xn,bGe as Xo,N1 as Xr,Kr as Xs,$4e as Xt,ett as Y,DJ as Ya,BYe as Yi,R0e as Yn,vq as Yo,P1e as Yr,tre as Ys,F2 as Yt,Zet as Z,CJ as Za,VYe as Zi,i2e as Zn,kq as Zo,M1 as Zr,Gr as Zs,N2 as Zt,Btt as _,bJe as _a,Or as _c,gQe as _i,L4e as _n,$q as _o,n2e as _r,Nce as _s,C7 as _t,Nnt as a,CX as aa,Yr as ac,I$e as ai,C2 as an,cJ as ao,I2e as ar,AK as as,X7 as at,p9 as b,SJe as ba,qne as bc,WZe as bi,x2 as bn,Jq as bo,I0e as br,pl as bs,K6e as bt,Dnt as c,gX as ca,Rr as cc,w$e as ci,X4e as cn,dKe as co,j0 as cr,EK as cs,Eet as ct,Cnt as d,HY as da,Zne as dc,h$ as di,w2 as dn,CKe as do,I0 as dr,TK as ds,yet as dt,zYe as ea,nre as ec,l1e as ei,k2 as en,yJ as eo,K0e as er,oq as es,Yet as et,L9 as f,wJe as fa,Pr as fc,VQe as fi,K4e as fn,uKe as fo,J0e as fr,bWe as fs,_et as ft,T9 as g,CJe as ga,kr as gc,s$ as gi,Q4e as gn,Zq as go,R0 as gr,Mce as gs,het as gt,Utt as h,VY as ha,Ar as hc,WQe as hi,y2 as hn,Qq as ho,O0 as hr,Rce as hs,w7 as ht,Z9 as i,XJe as ia,Ur as ic,z$e as ii,P4e as in,oJ as io,W0e as ir,RK as is,Jet as it,r9 as j,BJ as ja,qXe as ji,A4e as jn,Uq as jo,o0e as jr,ki as js,z4 as jt,Ttt as k,GJ as ka,Bne as kc,KXe as ki,k4e as kn,Rq as ko,a0 as kr,Ni as ks,q4 as kt,Ont as l,dX as la,Lr as lc,_$ as li,Z4e as ln,rJ as lo,q0e as lr,wK as ls,O7 as lt,lnt as m,UY as ma,jr as mc,HQe as mi,N4e as mn,wKe as mo,F2e as mr,Ice as ms,T7 as mt,Lnt as n,bZ as na,qr as nc,j1 as ni,G4e as nn,bJ as no,P2e as nr,UWe as ns,qet as nt,Pnt as o,hX as oa,ni as oc,S$ as oi,q4e as on,_Ke as oo,O2e as or,OK as os,Y7 as ot,mnt as p,WY as pa,Nr as pc,XQe as pi,E2 as pn,TKe as po,D2e as pr,Lce as ps,get as pt,ntt as q,RKe as qa,pZ as qi,Z0 as qn,NGe as qo,z1e as qr,oi as qs,I2 as qt,Fnt as r,YJe as ra,Jr as rc,F$ as ri,W4e as rn,fJ as ro,H0e as rr,BK as rs,Ket as rt,Ent as s,vX as sa,ei as sc,T$ as si,J4e as sn,bKe as so,Y0e as sr,DK as ss,Det as st,Int as t,RYe as ta,Br as tc,V1e as ti,z4e as tn,jKe as to,V0e as tr,aq as ts,Get as tt,Tnt as u,xX as ua,Ir as uc,g$ as ui,Y4e as un,nJ as uo,B0e as ur,yWe as us,Cet as ut,g9 as v,yJe as va,Dr as vc,yQe as vi,R4e as vn,qq as vo,D0 as vr,Pce as vs,pet as vt,Ett as w,gJe as wa,Ine as wc,mZe as wi,I4e as wn,Bq as wo,p0 as wr,zo as ws,s3 as wt,c9 as x,vJe as xa,Gne as xc,FQ as xi,S2 as xn,sKe as xo,F0e as xr,ml as xs,z6e as xt,h9 as y,xJe as ya,Une as yc,uQe as yi,F4e as yn,Yq as yo,L0e as yr,Pl as ys,S7 as yt,ftt as z,aqe as za,AZ as zi,u4e as zn,Fq as zo,f0e as zr,yre as zs,p3e as zt};
2531
- //# sourceMappingURL=DiffPanelShell-R1Q66jTc.js.map
2530
+ }`}function utt(e,t){let n=t9(t);return e.replace(stt,n)}function dtt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ftt({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 ptt(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function mtt(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 htt(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function gtt(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function _tt(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 vtt({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=ytt(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function ytt(){let e=document.createElement(`style`);return e.setAttribute(W4e,``),e}var btt=void 0;function xtt(){return btt??=`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(ott)),t.adoptedStyleSheets=[e]}connectedCallback(){e9(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(y2,t)}function Stt(e){return{...E2,...e}}function Ctt(e,t){let n=wtt(e,t);return t?n:e.diffHeaderHeight+n}function wtt(e,t){return e.paddingTop??(t?e.spacing:0)}function Ttt(e){return e.paddingBottom??e.spacing}function Ett(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function r9(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function i9(e,t){return N2(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function a9({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 o9({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 s9(e){return[L2(e.additionStart,e.additionCount)+1,R2(e.additionStart,e.additionCount)+1]}function c9({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 Dtt(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-R2(t.additionStart,t.additionCount),r=e.deletionLines.length-R2(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function l9({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-R2(n.additionStart,n.additionCount),i=e.deletionLines.length-R2(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 u9({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=l9({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 Ott({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]=s9(a);if(t<o){let s=c9({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=u9({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]=s9(a);return t<o+i.fromStart||t>=o+i.rangeSize}function ktt({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]=s9(n),l=c9({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=u9({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??Ett(e)}function f9({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function Att({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 jtt(e){return e!==`simple`&&e!==`metadata`}function Mtt({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!Att({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=d9({type:e,metrics:t}),a=f9({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function Ntt({type:e,metrics:t}){if(!jtt(e))return;let n=d9({type:e,metrics:t}),r=f9({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function p9({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=Ptt({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=L2(r.deletionStart,r.deletionCount),s=L2(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=c9({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?u9({fileDiff:e,hunkIndex:n,expandedHunks:i,collapsedContextThreshold:a,errorPrefix:`iterateOverDiff`}):void 0,p=d.fromStart+d.fromEnd;function m(e,n){return f==null||f.collapsedLines<=0||f.fromStart+f.fromEnd>0?0:t===`unified`?e===r.unifiedLineStart+r.unifiedLineCount-1?f.collapsedLines:0:n===r.splitLineStart+r.splitLineCount-1?f.collapsedLines:0}let h=d.collapsedLines===0;function g(){return h?0:(h=!0,d.collapsedLines)}if(c.shouldSkip(p,p))c.incrementCounts(p,p),g();else{let e=r.unifiedLineStart-d.rangeSize,i=r.splitLineStart-d.rangeSize,a=l-d.rangeSize,f=u-d.rangeSize,p=o+1-d.rangeSize,m=s+1-d.rangeSize;if(m9(c,d.fromStart,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:0,collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}))||(e=r.unifiedLineStart-d.fromEnd,i=r.splitLineStart-d.fromEnd,a=l-d.fromEnd,f=u-d.fromEnd,p=o+1-d.fromEnd,m=s+1-d.fromEnd,m9(c,d.fromEnd,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}),()=>{g()})))break hunkIterator}let _=r.unifiedLineStart,v=r.splitLineStart,y=l,b=u,x=o+1,S=s+1,C=r.hunkContent.at(-1);for(let e of r.hunkContent){if(c.shouldBreak())break hunkIterator;let i=e===C;if(e.type===`context`){if(c.shouldSkip(e.lines,e.lines))c.incrementCounts(e.lines,e.lines),g();else if(m9(c,e.lines,t,t=>{let a=i&&t===e.lines-1,o=_+t,s=v+t;return c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:m(o,s),type:`context`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:a&&r.noEOFCRDeletions,unifiedLineIndex:o,splitLineIndex:s},additionLine:{unifiedLineIndex:o,splitLineIndex:s,lineIndex:b+t,lineNumber:S+t,noEOFCR:a&&r.noEOFCRAdditions}})},()=>{g()}))break hunkIterator;_+=e.lines,v+=e.lines,y+=e.lines,b+=e.lines,x+=e.lines,S+=e.lines}else{let a=Math.max(e.deletions,e.additions),o=e.deletions+e.additions;if(!c.shouldSkip(o,a)){let s=Ltt(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(Rtt({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:l,diffStyle:t,index:s,unifiedLineIndex:_,splitLineIndex:v,additionLineIndex:b,deletionLineIndex:y,additionLineNumber:S,deletionLineNumber:x,content:e,isLastContent:i,unifiedCount:o,splitCount:a}),!0))break hunkIterator}}g(),c.incrementCounts(o,a),_+=o,v+=a,y+=e.deletions,b+=e.additions,x+=e.deletions,S+=e.additions}}if(f!=null){let{collapsedLines:n,fromStart:r,fromEnd:i}=f,a=r+i;if(m9(c,a,t,t=>{let r=t===a-1;return c.emit({hunkIndex:e.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:r?n:0,type:`context-expanded`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:!1,unifiedLineIndex:_+t,splitLineIndex:v+t},additionLine:{unifiedLineIndex:_+t,splitLineIndex:v+t,lineIndex:b+t,lineNumber:S+t,noEOFCR:!1}})},void 0,()=>c.shouldBreak()))break hunkIterator}}}function Ptt({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=Ftt({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 Ftt({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=c9({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?u9({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 Itt(e,t,n){if(!e.isWindowedHighlight||t<=0)return[0,t];let r=[];function i(n){let i=Math.max(0,e.viewportStart-n),a=Math.min(t,e.viewportEnd-n);a>i&&r.push([i,a])}if(n!==`split`&&i(e.unifiedCount),n!==`unified`&&i(e.splitCount),r.length===0)return[0,0];let a=r[0][0],o=r[0][1];for(let e=1;e<r.length;e++){let t=r[e];a=Math.min(a,t[0]),o=Math.max(o,t[1])}return[a,o]}function m9(e,t,n,r,i,a){let[o,s]=Itt(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 Ltt(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 Rtt({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 ztt={forcePlainText:!1};function h9(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=ztt){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=W7({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)??Vtt();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)}p9({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&&Btt({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}=Htt({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 Btt({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=I2(e),t=I2(t),e.length>s||t.length>s))return;let c=o===`char`?a3e(e,t):l3e(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?(o9({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),o9({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?o9({item:e,arr:l,enableJoin:d,isLastItem:t}):o9({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(a9({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(a9({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function Vtt(){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 Htt({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=w2,...l}}){let u=s??O7(e.name),d=s??O7(t.name),{state:f,transformers:p}=F7(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:L7(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,K7(i.codeToHast(I2(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,K7(i.codeToHast(I2(t.contents),m)))}}function g9(e){let t=e.lang??O7(e.name),n=e.lang??(e.prevName==null?`text`:O7(e.prevName));return t===`text`&&n===`text`}function _9(e){let t=[];for(let n of e){let e=b3.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function v9(e){for(let t of Array.isArray(e)?e:[e])if(!b3.has(t))return!1;return!0}async function y9(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=c7(r)??s7(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 b9(e){return p7.getResolvedThemes(e)}async function x9(e){for(let t of e)y7(t);let t=await p7.resolveThemes(e);for(let n=0;n<e.length;n++)b7(e[n],t[n]);return t}var S9={light:`pierre-light`,dark:`pierre-dark`};function Utt(e){return e===`dark`?S9.dark:S9.light}var C9=2166136261,w9=16777619,Wtt=2654435769,Gtt=2246822507;function T9(e,t=C9,n=w9){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 Ktt(e,t=`diff-panel`){let n=e.trim(),r=T9(n,C9,w9).toString(36),i=T9(n,Wtt,Gtt).toString(36);return`${t}:${n.length}:${r}:${i}`}var qtt=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,Jtt=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function Ytt(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 Xtt(e){let t=e.split(`,`).map(Ytt).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var E9={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 Ztt(e,t){let n=[[E9.fontSans,t.fontFamilySans,qtt],[E9.fontMono,t.fontFamilyCode,Jtt],[E9.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[E9.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=Xtt(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(E9.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(E9.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(E9.glassOpacity,`${String(t.glassOpacity)}%`),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}var D9=`themeId`,O9=`forge:theme-boot:v1`;function Qtt(e,t){try{window.localStorage.setItem(O9,JSON.stringify({appearance:t,background:e}))}catch{}}function $tt(){try{window.localStorage.removeItem(O9)}catch{}}function k9(){return typeof document>`u`?null:document.documentElement}function A9(){let e=k9();if(e!==null){for(let t of bn)e.style.removeProperty(on[t]);delete e.dataset[D9],$tt()}}function ent(e,t){let n=k9();if(n===null)return;let r=t===`dark`?e.dark:e.light;for(let e of bn){let t=r[e];if(t===void 0){n.style.removeProperty(on[e]);continue}n.style.setProperty(on[e],t)}n.dataset[D9]=e.id,r.background!==void 0&&Qtt(r.background,t)}function tnt(e,t){if(e===`forge`){A9();return}let n=kte(e);if(n===void 0){A9();return}ent(n,t)}var nnt=`forge:theme`,j9=`theme-color`,rnt=`meta[name="${j9}"][data-dynamic-theme-color="true"]`,M9=`(prefers-color-scheme: dark)`,int={dark:`#0a0a0a`,light:`#ffffff`};function ant(){return typeof window<`u`&&typeof localStorage<`u`}function N9(e){return e===`system`||e===`light`||e===`dark`}function P9(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function ont(){if(!ant())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(GY);if(e){let t=JY(JSON.parse(e));return{theme:N9(t.theme)?t.theme:`system`,uiFontSize:P9(t.uiFontSize,16),codeFontSize:P9(t.codeFontSize,13)}}let t=window.localStorage.getItem(nnt);return{theme:N9(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function snt(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(M9).matches?`dark`:`light`}function F9(e){return e===`system`?snt():e}function cnt(){let e=document.querySelector(rnt);return e||(e=document.createElement(`meta`),e.name=j9,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function I9(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 lnt(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function unt(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function L9(e=unt()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=I9(getComputedStyle(lnt()).backgroundColor),n=I9(getComputedStyle(document.body).backgroundColor),r=t??n??int[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,cnt().setAttribute(`content`,r)}function dnt(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function R9(e,t=!1){let n=F9(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,L9(n),dnt(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function z9(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${P9(e,16)}px`)}function B9(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${P9(e,13)}px`)}function V9(e){z9(e.uiFontSize),B9(e.codeFontSize)}if(typeof document<`u`){let e=ont();R9(e.theme),V9(e)}function fnt(){let e=(0,ul.c)(34),t=C0(gnt),n=C0(hnt),r=C0(mnt),i=C0(pnt),{updateSettings:a}=w0(),o;e[0]===t?o=e[1]:(o=()=>F9(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(R9(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=P9(e,16);a({uiFontSize:t}),z9(t)},e[6]=a,e[7]=p);let m=p,h;e[8]===a?h=e[9]:(h=e=>{let t=P9(e,13);a({codeFontSize:t}),B9(t)},e[8]=a,e[9]=h);let g=h,_,v;e[10]===t?(_=e[11],v=e[12]):(_=()=>{c(R9(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=()=>{V9({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=()=>{tnt(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(M9),n=()=>{c(R9(`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 pnt(e){return e.codeFontSize}function mnt(e){return e.uiFontSize}function hnt(e){return e.themeId}function gnt(e){return e.theme}function _nt(){let e=(0,ul.c)(10),t=C0(Tnt),n=C0(wnt),r=C0(Cnt),i=C0(Snt),a=C0(xnt),o=C0(bnt),s=C0(ynt),c=C0(vnt),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`||Ztt(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 vnt(e){return e.glassOpacity}function ynt(e){return e.fontSmoothing}function bnt(e){return e.terminalFontSize}function xnt(e){return e.promptFontSize}function Snt(e){return e.fontFamilyTerminal}function Cnt(e){return e.fontFamilyComposer}function wnt(e){return e.fontFamilyCode}function Tnt(e){return e.fontFamilySans}function Ent(e){let t=(0,F.useRef)(e);return(0,F.useInsertionEffect)(()=>void(t.current=e)),(0,F.useCallback)((...e)=>t.current(...e),[])}var Dnt=(0,F.createContext)(void 0);function Ont(){return(0,F.useContext)(Dnt)}var knt={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},Ant={display:`contents`};function jnt(){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`)}},Mnt=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=w2,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??w2,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()||i9(a,this.renderOptions))return;let o=C7(e),c=[];if(N2(a.theme,this.renderOptions.theme)||(c=w7(o)?b9(o):await x9(o)),!s())return;if(this.highlighter!=null)m7(c,this.highlighter);else{let e=await S7({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=C7(this.renderOptions.theme),i=[];if(i=w7(r)?b9(r):await x9(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=v9(e)?_9(e):await y9(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([S7({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=k7(),i=r>0?A7():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);Z7(t)||n!=null&&T7(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||Z7(e)||t!=null&&T7(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 X7(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);g9(t)||n!=null&&i9(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||g9(e)||t!=null&&i9(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:h9(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&&(v9(r)?t.request.resolvedLanguages=_9(r):t.request.resolvedLanguages=await y9(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)||!T7(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)||!i9(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){Nnt(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=k7();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=A7())}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)&&o4(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)&&r9(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 Nnt(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??O7(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??O7(e.request.diff.name)),t.add(e.request.diff.lang??O7(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 Pnt({poolOptions:e,highlighterOptions:t}){return X9??=new Mnt(e,t),X9}function Fnt(){X9!=null&&(X9.terminate(),X9=void 0)}var Z9=(0,F.createContext)(void 0),Q9=0;function Int({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,F.useState)(()=>{if(!(typeof window>`u`))return Pnt({poolOptions:t,highlighterOptions:n})});return(0,F.useInsertionEffect)(()=>{if(r!=null)return Q9++,()=>{Q9--}},[r]),(0,F.useEffect)(()=>()=>{Q9===0&&Fnt()},[]),(0,Fr.jsx)(Z9.Provider,{value:r,children:e})}function Lnt(){return(0,F.useContext)(Z9)}function $9(e){return Qt(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,Ir&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function Rnt(e){let t=(0,ul.c)(10),n=Ir&&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=Qt(`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,Fr.jsx)(`div`,{className:$9(e.mode),children:e.header}):(0,Fr.jsx)(`div`,{className:`border-b border-border`,children:(0,Fr.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,Fr.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 znt(){let e=(0,ul.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Fr.jsx)(VY,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,Fr.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,Fr.jsx)(VY,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,Fr.jsx)(VY,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(Fr.Fragment,{children:[r,(0,Fr.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,Fr.jsx)(VY,{className:`size-7 rounded-md`}),(0,Fr.jsx)(VY,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function Bnt(e){let t=(0,ul.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Fr.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,Fr.jsx)(VY,{className:`h-4 w-32 rounded-full`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`space-y-2`,children:[(0,Fr.jsx)(VY,{className:`h-3 w-full rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-full rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-10/12 rounded-full`}),(0,Fr.jsx)(VY,{className:`h-3 w-11/12 rounded-full`}),(0,Fr.jsx)(VY,{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,Fr.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,Fr.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,Fr.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,Fr.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{$et as $,mJ as $a,qYe as $i,B2e as $n,lq as $o,P1e as $r,rre as $s,A2 as $t,i9 as A,WJ as Aa,br as Ac,ZXe as Ai,_2 as An,Gq as Ao,n0 as Ar,Mi as As,K4 as At,mtt as B,yqe as Ba,DZ as Bi,g4e as Bn,LGe as Bo,d0 as Br,Si as Bs,c4 as Bt,Mtt as C,_Je as Ca,Kne as Cc,xZe as Ci,U4e as Cn,Wq as Co,w0 as Cr,Ro as Cs,N6e as Ct,Ntt as D,Lqe as Da,Wne as Dc,mQ as Di,P4e as Dn,Vq as Do,m0 as Dr,Lo as Ds,J4 as Dt,u9 as E,JJ as Ea,yr as Ec,eZe as Ei,A4e as En,zq as Eo,E0e as Er,Uo as Es,X3e as Et,xtt as F,HJ as Fa,wXe as Fi,x4e as Fn,GGe as Fo,x0e as Fr,Oi as Fs,m4 as Ft,ctt as G,LKe as Ga,fZ as Gi,W2e as Gn,PGe as Go,V1e as Gr,ui as Gs,R2 as Gt,ftt as H,jJ as Ha,CZ as Hi,$0 as Hn,EGe as Ho,Y1e as Hr,gre as Hs,s4 as Ht,vtt as I,PJ as Ia,jZ as Ii,v4e as In,UGe as Io,g0e as Ir,Di as Is,d4 as It,itt as J,HKe as Ja,yZ as Ji,V2e as Jn,FGe as Jo,U1e as Jr,ai as Js,r3e as Jt,e9 as K,zKe as Ka,KYe as Ki,U2e as Kn,iGe as Ko,F1e as Kr,li as Ks,L2 as Kt,_tt as L,Nqe as La,OXe as Li,y4e as Ln,VGe as Lo,v0e as Lr,Ti as Ls,v3e as Lt,Stt as M,zJ as Ma,dQ as Mi,S4e as Mn,iKe as Mo,f0e as Mr,ji as Ms,I4 as Mt,Ctt as N,Fqe as Na,pQ as Ni,f2 as Nn,Pq as No,_0e as Nr,Ai as Ns,L4 as Nt,Dtt as O,KJ as Oa,Fne as Oc,JXe as Oi,F4e as On,Hq as Oo,i0 as Or,Cre as Os,Y3e as Ot,Ttt as P,UJ as Pa,PZ as Pi,_4e as Pn,XGe as Po,m0e as Pr,Ei as Ps,F4 as Pt,Z7 as Q,xJ as Qa,vZ as Qi,J0e as Qn,MGe as Qo,B1e as Qr,ore as Qs,M2 as Qt,gtt as R,dqe as Ra,NZ as Ri,b4e as Rn,qGe as Ro,y0e as Rr,wi as Rs,_3e as Rt,s9 as S,zY as Sa,Tr as Sc,yZe as Si,b2 as Sn,aKe as So,C0 as Sr,Ko as Ss,M6e as St,l9 as T,Iqe as Ta,Rne as Tc,bQ as Ti,j4e as Tn,Lq as To,k0e as Tr,Ho as Ts,Y4 as Tt,utt as U,kJ as Ua,SZ as Ui,t2 as Un,DGe as Uo,X1e as Ur,mre as Us,o4 as Ut,ptt as V,tqe as Va,wZ as Vi,e2 as Vn,Tq as Vo,b0e as Vr,gi as Vs,l4 as Vt,ltt as W,qKe as Wa,GYe as Wi,r2 as Wn,jGe as Wo,z1e as Wr,hre as Ws,p3e as Wt,ttt as X,EJ as Xa,_Z as Xi,o2e as Xn,CGe as Xo,N1 as Xr,Kr as Xs,n3e as Xt,rtt as Y,DJ as Ya,UYe as Yi,V0e as Yn,vq as Yo,L1e as Yr,tre as Ys,F2 as Yt,ett as Z,CJ as Za,WYe as Zi,s2e as Zn,kq as Zo,M1 as Zr,Gr as Zs,N2 as Zt,Utt as _,CJe as _a,Or as _c,yQe as _i,B4e as _n,$q as _o,a2e as _r,Nce as _s,C7 as _t,Int as a,CX as aa,Yr as ac,z$e as ai,C2 as an,cJ as ao,z2e as ar,AK as as,X7 as at,p9 as b,TJe as ba,qne as bc,qZe as bi,x2 as bn,Jq as bo,z0e as br,pl as bs,Y6e as bt,Ant as c,gX as ca,Rr as cc,D$e as ci,$4e as cn,mKe as co,j0 as cr,EK as cs,ket as ct,Ent as d,HY as da,Zne as dc,h$ as di,w2 as dn,EKe as do,I0 as dr,TK as ds,Cet as dt,HYe as ea,nre as ec,f1e as ei,k2 as en,yJ as eo,Y0e as er,oq as es,Qet as et,L9 as f,DJe as fa,Pr as fc,WQe as fi,Y4e as fn,pKe as fo,Z0e as fr,bWe as fs,bet as ft,T9 as g,EJe as ga,kr as gc,s$ as gi,t3e as gn,Zq as go,R0 as gr,Mce as gs,vet as gt,Ktt as h,VY as ha,Ar as hc,qQe as hi,y2 as hn,Qq as ho,O0 as hr,Rce as hs,w7 as ht,Z9 as i,$Je as ia,Ur as ic,H$e as ii,L4e as in,oJ as io,q0e as ir,RK as is,Zet as it,r9 as j,BJ as ja,XXe as ji,N4e as jn,Uq as jo,l0e as jr,ki as js,z4 as jt,Ott as k,GJ as ka,Bne as kc,YXe as ki,M4e as kn,Rq as ko,a0 as kr,Ni as ks,q4 as kt,jnt as l,dX as la,Lr as lc,_$ as li,e3e as ln,rJ as lo,X0e as lr,wK as ls,O7 as lt,fnt as m,UY as ma,jr as mc,GQe as mi,I4e as mn,DKe as mo,R2e as mr,Ice as ms,T7 as mt,Bnt as n,bZ as na,qr as nc,j1 as ni,J4e as nn,bJ as no,L2e as nr,UWe as ns,Xet as nt,Lnt as o,hX as oa,ni as oc,S$ as oi,X4e as on,bKe as oo,j2e as or,OK as os,Y7 as ot,_nt as p,WY as pa,Nr as pc,$Qe as pi,E2 as pn,OKe as po,A2e as pr,Lce as ps,yet as pt,att as q,VKe as qa,pZ as qi,Z0 as qn,IGe as qo,H1e as qr,oi as qs,I2 as qt,Rnt as r,QJe as ra,Jr as rc,F$ as ri,q4e as rn,fJ as ro,G0e as rr,BK as rs,Yet as rt,knt as s,vX as sa,ei as sc,T$ as si,Z4e as sn,CKe as so,Q0e as sr,DK as ss,Aet as st,znt as t,VYe as ta,Br as tc,W1e as ti,H4e as tn,PKe as to,W0e as tr,aq as ts,Jet as tt,Ont as u,xX as ua,Ir as uc,g$ as ui,Q4e as un,nJ as uo,U0e as ur,yWe as us,Eet as ut,g9 as v,SJe as va,Dr as vc,SQe as vi,V4e as vn,qq as vo,D0 as vr,Pce as vs,get as vt,ktt as w,yJe as wa,Ine as wc,_Ze as wi,z4e as wn,Bq as wo,p0 as wr,zo as ws,s3 as wt,c9 as x,xJe as xa,Gne as xc,FQ as xi,S2 as xn,uKe as xo,R0e as xr,ml as xs,H6e as xt,h9 as y,wJe as ya,Une as yc,pQe as yi,R4e as yn,Yq as yo,B0e as yr,Pl as ys,S7 as yt,htt as z,cqe as za,AZ as zi,p4e as zn,Fq as zo,h0e as zr,yre as zs,g3e as zt};
2531
+ //# sourceMappingURL=DiffPanelShell-B8YmcyIS.js.map