1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CHJK_WGo.js","assets/index-BSuLgOgM.js","assets/index-BqNoTY0z.js","assets/amplify_outputs-ByhBuvRU.js","assets/index-BWG24D4D.js","assets/jsx-runtime-C2UBfbyc.js","assets/index-Ctn5E0jf.js","assets/contract-C8_2XbhZ.js","assets/logger-AqfA_hXV.js","assets/chat-YAQO4n_L.js","assets/index-CHoi3jgE.js","assets/index-DgoachrA.js","assets/artifactTitle-DNRdmHz0.js","assets/authenticated-chat-Yvg3yA_B.js","assets/resume-DQ2pc8eQ.js","assets/aiWorkspace-DNQ8NOJn.js","assets/auth-BYwTrny6.js","assets/API-DAFHaofH.js","assets/sync-DtNvzS6k.js","assets/HostedSignInButtons-BY3xXxUD.js","assets/index-qtUc8lsi.js","assets/HostedSignInButtons-HSKQt6gX.css","assets/react-toastify.esm-DcR-pTER.js","assets/clsx-B-dksMZM.js","assets/workbench-DVZ8UPcc.js","assets/preload-helper-CLcXU_4U.js","assets/chatMode-nkbEUJmy.js","assets/chatMedia-Bm3yTEDP.js","assets/networkQuality-MoaFJ23-.js","assets/clientImageAssets-BwBgCWfG.js","assets/index-D-j07sr6.js","assets/router-CdSor0Tc.js","assets/index-DG0jpFbZ.js","assets/index-SgDwteQq.js","assets/usePromptEnhancer-5VnOEynm.js","assets/pendingDashboardPromptAttachments-BmaqZ4u2.js","assets/index-CAsT1rfk.js","assets/index-DTbehiYO.js","assets/Dropdown-Dgl1XgmV.js","assets/index-D2RkbEbt.js","assets/index-CdmNQeNf.js","assets/classNames-D4DIdros.js","assets/supportLinks-D1aYQK4l.js","assets/proxy-gn4uqtVm.js","assets/BillingExperience-D-K1LAVQ.js","assets/service-D1r3_DgS.js","assets/createLucideIcon-C_AYRPVT.js","assets/video-CFxngqn5.js","assets/mic-vocal-20U2l1KN.js","assets/pricingData-DrQtaPwh.js","assets/platformPricing-tZHuNO2h.js","assets/useBillingSummary-BO9ufWot.js","assets/refresh-cw-BgmVbcS1.js","assets/gauge-DejO41ze.js","assets/credit-card-C6H2etZq.js","assets/file-text-Bq8boU8U.js","assets/circle-alert-BPTJID5T.js","assets/components-DKMMHsO5.js","assets/single-fetch-Bfr4o6AV.js","assets/shield-check-BYYH1pJ6.js","assets/search-ZlL_h0-r.js","assets/download-BNQ6jJBj.js","assets/Button-B5kdVOtM.js","assets/Dialog-DaMOFeJE.js","assets/check-6fU0F-bx.js","assets/ImageStudio-Bk7F7h1y.js","assets/imageStudio-BZ6yVwsW.js","assets/Input-DTMX85Mn.js","assets/Tabs-DNJS30xw.js","assets/imagePricing-Y4dpxEcZ.js","assets/useImagePricingPlan-Ddd2NPJk.js","assets/stripIndent-OpH14_i6.js","assets/workspaceHistorySource-CW8zU1pv.js","assets/index-Bj4CZp8v.js","assets/workspacePromptLaunch-Cfzl8mao.js","assets/workspacePromptLaunch-CK3iMQik.css","assets/googleDrive-2-J1c5so.js","assets/runtimeUsage-CUnLOScq.js","assets/homePromptDraft-Br7wJnvm.js","assets/mutations-Dba0hfjS.js","assets/d1RuntimeProduct-DuY39u3D.js","assets/genieWebsiteRazorpay--S7PVtZf.js","assets/homeReset-ClYxhsPV.js","assets/index-CDg6de0u.js","assets/routing-5g8LK-Iv.js","assets/ReportIssueLink-2gue2bLN.js","assets/ChatClientFallback-DRLUUO3H.js","assets/AuthWrapper-BR8lelxY.js","assets/AuthWrapper-Cmd5PKjq.css","assets/index-ClVLQyOJ.js","assets/index-CdNT3kup.js","assets/index-MuJDxPXn.js","assets/index-uSfUUvZD.js","assets/index-Gg5lkPbv.js","assets/index-DdJCVIS5.js","assets/index-B19Skoh2.js","assets/DiffView-SIFVNEj3.js","assets/DiffView-OPuRUQ2u.css","assets/Preview-DiF-fRVO.js","assets/agenticDataBridge-BzBJ6muP.js","assets/AdminWorkspace-NbGkEJF3.js","assets/googleDriveClient-ePTryYPK.js","assets/AdminWorkspace-CBtSgKR4.css","assets/PublishDialog-BFD8pRoX.js","assets/sessionErrors-COH7wBoA.js","assets/SecurityAuditDialog-BcPV1jvR.js","assets/PricingDialog-TZK6K_5x.js","assets/PricingPage-PU_0uYQa.js","assets/BillingTermSelector-Dz7CeAUX.js","assets/termPricing-DN9DKseZ.js","assets/VideoPricingSection-Ds1NFjYi.js","assets/videoPricing-CGATsrch.js","assets/sparkles-BXyJ22Ln.js","assets/circle-check-CIda9hsj.js","assets/PricingPage-BtZF3T0e.css","assets/genieAIPaypalPayment-B-m3-NOX.js","assets/genieAIRazorpayPayment-CCSWBTPd.js","assets/CheckoutDialog-BNmVWL-k.js","assets/PaymentSuccessDialog-C-r3zina.js","assets/angular-html-LfdN0zeE.js","assets/html-C2L_23MC.js","assets/javascript-ySlJ1b_l.js","assets/css-BPhBrDlE.js","assets/angular-ts-CKsD7JZE.js","assets/scss-C31hgJw-.js","assets/apl-BBq3IX1j.js","assets/xml-e3z08dGr.js","assets/java-xI-RfyKK.js","assets/json-BQoSv7ci.js","assets/astro-CqkE3fuf.js","assets/typescript-Dj6nwHGl.js","assets/postcss-B3ZDOciz.js","assets/blade-a8OxSdnT.js","assets/sql-COK4E0Yg.js","assets/bsl-Dgyn0ogV.js","assets/sdbl-BLhTXw86.js","assets/cairo--RitsXJZ.js","assets/python-DhUJRlN_.js","assets/cobol-PTqiYgYu.js","assets/coffee-dyiR41kL.js","assets/cpp-BksuvNSY.js","assets/regexp-DWJ3fJO_.js","assets/glsl-DBO2IWDn.js","assets/c-C3t2pwGQ.js","assets/crystal-DtDmRg-F.js","assets/shellscript-atvbtKCR.js","assets/dotenv-D-NiToSL.js","assets/edge-D5gP-w-T.js","assets/html-derivative-CSfWNPLT.js","assets/elixir-CLiX3zqd.js","assets/elm-CmHSxxaM.js","assets/erb-BYTLMnw6.js","assets/ruby-DeZ3UC14.
1js","assets/haml-B2EZWmdv.js","assets/graphql-cDcHW_If.js","assets/jsx-BAng5TT0.js","assets/tsx-B6W0miNI.js","assets/lua-CvWAzNxB.js","assets/yaml-CVw76BM1.js","assets/fortran-fixed-form-TqA4NnZg.js","assets/fortran-free-form-DKXYxT9g.js","assets/fsharp-XplgxFYe.js","assets/markdown-UIAJJxZW.js","assets/gdresource-BHYsBjWJ.js","assets/gdshader-SKMF96pI.js","assets/gdscript-DfxzS6Rs.js","assets/git-commit-i4q6IMui.js","assets/diff-BgYniUM_.js","assets/git-rebase-B-v9cOL2.js","assets/glimmer-js-D-cwc0-E.js","assets/glimmer-ts-pgjy16dm.js","assets/hack-D1yCygmZ.js","assets/handlebars-BQGss363.js","assets/http-FRrOvY1W.js","assets/hxml-TIA70rKU.js","assets/haxe-C5wWYbrZ.js","assets/imba-bv_oIlVt.js","assets/jinja-DGy0s7-h.js","assets/jison-BqZprYcd.js","assets/julia-BBuGR-5E.js","assets/r-CwjWoCRV.js","assets/latex-C-cWTeAZ.js","assets/tex-rYs2v40G.js","assets/liquid-D3W5UaiH.js","assets/marko-z0MBrx5-.js","assets/less-BfCpw3nA.js","assets/mdc-DB_EDNY_.js","assets/nginx-D_VnBJ67.js","assets/nim-ZlGxZxc3.js","assets/perl-CHQXSrWU.js","assets/php-B5ebYQev.js","assets/pug-CM9l7STV.js","assets/qml-D8XfuvdV.js","assets/razor-CNLDkMZG.js","assets/csharp-D9R-vmeu.js","assets/rst-4NLicBqY.js","assets/cmake-DbXoA79R.js","assets/sas-BmTFh92c.js","assets/shaderlab-B7qAK45m.js","assets/hlsl-ifBTmRxC.js","assets/shellsession-C_rIy8kc.js","assets/soy-C-lX7w71.js","assets/sparql-bYkjHRlG.js","assets/turtle-BMR_PYu6.js","assets/stata-DorPZHa4.js","assets/svelte-MSaWC3Je.js","assets/templ-dwX3ZSMB.js","assets/go-B1SYOhNW.js","assets/ts-tags-CipyTH0X.js","assets/twig-NC5TFiHP.js","assets/vue-BuYVFjOK.js","assets/vue-html-xdeiXROB.js","assets/xsl-Dd0NUgwM.js","assets/VideoStudio-_hTpIzKt.js","assets/clientMediaHandoff-CytaYzWa.js","assets/videoStudio-CdEWC50a.js","assets/wand-sparkles-QKDEs8if.js","assets/loader-circle-CBROZvKn.js","assets/audio-lines-Cg3ad4Du.js","assets/x-BYC35FMQ.js","assets/copy-Dlxo72d0.js","assets/eye-DsOtfLk0.js","assets/AudioStudio-Cco9byUX.js","assets/AudioVoiceButtons-CXJ_FmRO.js","assets/audioPricing-Bjhi6w3A.js"])))=>i.map(i=>d[i]); 2import{r as x,a as _t,g as nD,j as f,R as rp,c as Ka}from"./jsx-runtime-C2UBfbyc.js";import{u as We}from"./index-Ctn5E0jf.js";import{g as Zb,h as dg,j as sD,k as iD,s as oD,m as rx,o as aD,u as lD,q as cD,r as uD,b as Za,i as j1,l as Wa,T as jh,t as dD,v as hD,w as fD,A as np,B as uo,S as Mf,x as pD,y as $1,z as sm,C as Nc,D as B1,E as ea,F as mD,G as ju,c as gD}from"./contract-C8_2XbhZ.js";import{s as nx}from"./HostedSignInButtons-BY3xXxUD.js";import{B as Se,Q as bD,g as vD}from"./react-toastify.esm-DcR-pTER.js";import{c as ya,r as gu,l as yD}from"./logger-AqfA_hXV.js";import{p as _D,w as j,c as F1,d as sp,q as ad,u as W1,a as ip,r as Zy,s as e_,b as H1,t as ta,k as ev,v as xD,g as sx,x as U1,l as wD,m as SD,y as CD,z as AD,A as ED,B as kD,P as ix,C as PD,D as TD,E as RD,F as hs,G as ID,H as ND,I as LD,J as DD,K as MD,L as OD}from"./workbench-DVZ8UPcc.js";import{i as jD,u as $D}from"./usePromptEnhancer-5VnOEynm.js";import{h as BD,s as FD,i as ox,P as t_,R as z1,T as V1,j as G1,A as q1,k as WD,t as ai,l as el,m as im,n as ax,o as HD,p as K1,q as UD,r as om,u as sh,v as Y1,d as zD,w as lx,z as VD,x as GD,y as qD,D as KD,E as YD,g as XD,G as JD,H as QD}from"./pendingDashboardPromptAttachments-BmaqZ4u2.js";import{c as Ve}from"./chat-YAQO4n_L.js";import{D as Lc,a as Dc,b as Cd,c as op,d as Ds,_ as X1,I as tu}from"./Dialog-DaMOFeJE.js";import{r as tv,b as ZD,a as eM}from"./networkQuality-MoaFJ23-.js";import{a as tM,d as $h,W as hg,e as rM,v as nM,i as _c,b as J1,g as cx,f as sM,h as Q1,c as iM,j as oM}from"./ImageStudio-Bk7F7h1y.js";import{_ as H}from"./preload-helper-CLcXU_4U.js";import{R as Bl,P as aM,O as lM,C as cM,T as uM,D as dM,a as hM}from"./index-CAsT1rfk.js";import{B as En}from"./Button-B5kdVOtM.js";import{c as ue}from"./classNames-D4DIdros.js";import{aC as Z1,o as Of,ay as fM,aq as pM,aD as ux,c as Bh,aE as xc,aF as dx,aG as mM,av as hx,am as gM,u as bM,aH as vM,ao as yM,r as Kt,aI as _M,aJ as xM,aK as eE,y as fn,a3 as wM,G as SM,a4 as CM,a5 as AM,v as fx,aL as EM,aM as kM,aN as PM,x as hn,K as Fh,ac as TM,F as fg,N as RM,R as IM,L as NM,J as LM,E as px,D as mx,S as DM,I as gx,w as bx,a6 as vx,a7 as yx,aO as _x,aP as pg,O as _l,Q as xl,af as MM,P as OM,as as
2jM,aQ as $M,aR as BM,aS as FM,a8 as xx,aT as WM,aU as HM,aV as UM,aW as zM,aX as VM}from"./artifactTitle-DNRdmHz0.js";import{a as On,l as tE,t as GM,u as qM,v as KM,c as rv,f as wx}from"./auth-BYwTrny6.js";import{a as ap,r as am,b as ih,c as r_}from"./chatMode-nkbEUJmy.js";import{b as Ad,e as lm,g as lp,i as YM,j as XM,k as Sx,u as nv,m as JM,n as QM,v as ZM,p as e2,h as t2,r as r2,N as n2,o as s2,q as i2}from"./clientImageAssets-BwBgCWfG.js";import{b as rE,c as nE}from"./index-D-j07sr6.js";import{l as sE,b as iE,a as o2,W as a2,s as l2,d as c2,z as oE,C as u2,D as d2,E as h2,A as f2}from"./workspaceHistorySource-CW8zU1pv.js";import{a as Cx,c as p2,d as Ax,e as m2,f as Ex,h as kx}from"./googleDrive-2-J1c5so.js";import{buildImageStudioRoute as g2,consumePendingImageStudioAssetUse as b2}from"./imageStudio-BZ6yVwsW.js";import{f as Yl,a as aE,c as n_,u as lE,b as s_,s as v2,d as y2,i as Px,g as Tx,e as Rx}from"./runtimeUsage-CUnLOScq.js";import{u as Ix,m as ar,c as _2}from"./proxy-gn4uqtVm.js";import{R as x2,L as w2,d as Wh,C as Hh}from"./Tabs-DNJS30xw.js";import{t as Ed,a as S2}from"./stripIndent-OpH14_i6.js";import{u as C2,i as Uh,g as A2,o as cE,h as mg,m as gg,r as E2,j as k2,s as P2,k as T2,l as R2,n as I2,p as uE,q as N2,t as L2,v as D2,w as M2,G as O2,x as j2,L as $2,y as B2,z as F2,B as W2,E as H2,S as U2,F as z2,H as V2,J as G2,e as q2,T as K2,P as Y2,f as X2,K as J2,c as dE,R as Q2,A as hE,d as Z2,C as eO,D as bg,b as oo,a as tO}from"./Dropdown-Dgl1XgmV.js";import{l as rO,c as fE,P as i_,b as Lo,u as nO,a as sO,g as pE,d as mE,e as iO,h as oO,R as aO,f as lO,i as cO,F as uO,D as dO}from"./index-DTbehiYO.js";import{A as Si}from"./index-Bj4CZp8v.js";import{p as cp,D as o_,c as a_,e as Nx,a as wc}from"./amplify_outputs-ByhBuvRU.js";import{u as l_,c as hO}from"./homePromptDraft-Br7wJnvm.js";import{j as Zl,c as vg,a as fO}from"./aiWorkspace-DNQ8NOJn.js";import{a as oh}from"./index-DgoachrA.js";import{h as pO,i as mO}from"./mutations-Dba0hfjS.js";import{a as c_,i as gO}from"./d1RuntimeProduct-DuY39u3D.js";import{g as u_}from"./API-DAFHaofH.js";import{g as bO}from"./genieWebsiteRazorpay--S7PVtZf.js";import{navigateHomeWithHardReset as vO}from"./homeReset-ClYxhsPV.js";import{g as jf,f as yO}from"./sync-DtNvzS6k.js";import{r as up}from"./index-SgDwteQq.js";import{w as d_,M as _O}from"./index-CDg6de0u.js";import{e as gE,M as ld,g as Lx,a as xO,b as wO,s as SO,i as CO,W as AO,c as EO}from"./chatMedia-Bm3yTEDP.js";import{w as sv,l as yg,n as kO,r as PO,a as _g,o as Dx,m as Mx,p as TO}from"./resume-DQ2pc8eQ.js";import{b as RO}from"./routing-5g8LK-Iv.js";import{R as h_}from"./ReportIssueLink-2gue2bLN.js";import{I as xg}from"./Input-DTMX85Mn.js";import{u as IO}from"./useBillingSummary-BO9ufWot.js";import{a as NO,C as LO}from"./supportLinks-D1aYQK4l.js";import{a as Fl}from"./authenticated-chat-Yvg3yA_B.js";import{C as DO}from"./ChatClientFallback-DRLUUO3H.js";import{AuthWrapper as MO}from"./AuthWrapper-BR8lelxY.js";import{a as OO,W as Ox}from"./workspacePromptLaunch-Cfzl8mao.js";import{u as jO}from"./index-DG0jpFbZ.js";function $O(t){return x.useEffect(()=>()=>t(),[])}function BO(){const t=Ix(()=>({current:null,animations:[]})),e=Ix(()=>BD(t));return $O(()=>{t.animations.forEach(r=>r.stop())}),[t,e]}function FO(){return()=>{}}function WO(){return x.useSyncExternalStore(FO,()=>!0,()=>!1)}function Ml({children:t,fallback:e=null}){return WO()?x.createElement(x.Fragment,null,t()):x.createElement(x.Fragment,null,e)}const bE=0,vE=1,yE=2,jx=3;var $x=Object.prototype.hasOwnProperty;function iv(t,e){var r,n;if(t===e)return!0;if(t&&e&&(r=t.constructor)===e.constructor){if(r===Date)return t.getTime()===e.getTime();if(r===RegExp)return t.toString()===e.toString();if(r===Array){if((n=t.length)===e.length)for(;n--&&iv(t[n],e[n]););return n===-1}if(!r||typeof t=="object"){n=0;for(r in t)if($x.call(t,r)&&++n&&!$x.call(e,r)||!(r in e)||!iv(t[r],e[r]))return!1;return Object.keys(e).length===n}}return t!==t&&e!==e}const ra=new WeakMap,oa=()=>{},Ws=oa(),ov=Object,Er=t=>t===Ws,Do=t=>typeof t=="function",tl=(t,e)=>({...t,...e}),_E=t=>Do(t.then),wg={},zh={},f_="undefined",ah=typeof window!=f_,av=typeof document!=f_,HO=ah&&"Deno"in window,UO=()=>ah&&typeof window.requestAnimationFrame!=f_,xE=(t,e)=>{const r=ra.get(t);return[()=>!Er(e)&&t.get(e)||wg,n=>{if(!Er(e)){const s=t.get(e);e in zh||(zh[e]=s),r[5](e,tl(s,n),s||wg)}},r[6],()=>!Er(e)&&e in zh?zh[e]:!Er(e)&&t.get(e)||wg]};let lv=!0;const zO=()=>lv,[cv,uv]=ah&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[oa,oa],VO=()=>{const t=av&&document.visibilityState;return Er(t)||t!=="hidden"},GO=t=>(av&&document.addEventListener("visibilitychange",t),cv("focus",t),()=>{av&&document.removeEventListener("visibilitychange",t),uv("focus",t)}),qO=t=>{const e=()=>{lv=!0,t()},r=()=>{lv=!1};
2return cv("online",e),cv("offline",r),()=>{uv("online",e),uv("offline",r)}},KO={isOnline:zO,isVisible:VO},YO={initFocus:GO,initReconnect:qO},Bx=!_t.useId,Hc=!ah||HO,XO=t=>UO()?window.requestAnimationFrame(t):setTimeout(t,1),Sg=Hc?x.useEffect:x.useLayoutEffect,Cg=typeof navigator<"u"&&navigator.connection,Fx=!Hc&&Cg&&(["slow-2g","2g"].includes(Cg.effectiveType)||Cg.saveData),Vh=new WeakMap,JO=t=>ov.prototype.toString.call(t),Ag=(t,e)=>t===`[object ${e}]`;let QO=0;const dv=t=>{const e=typeof t,r=JO(t),n=Ag(r,"Date"),s=Ag(r,"RegExp"),i=Ag(r,"Object");let a,o;if(ov(t)===t&&!n&&!s){if(a=Vh.get(t),a)return a;if(a=++QO+"~",Vh.set(t,a),Array.isArray(t)){for(a="@",o=0;o<t.length;o++)a+=dv(t[o])+",";Vh.set(t,a)}if(i){a="#";const l=ov.keys(t).sort();for(;!Er(o=l.pop());)Er(t[o])||(a+=o+":"+dv(t[o])+",");Vh.set(t,a)}}else a=n?t.toJSON():e=="symbol"?t.toString():e=="string"?JSON.stringify(t):""+t;return a},p_=t=>{if(Do(t))try{t=t()}catch{t=""}const e=t;return t=typeof t=="string"?t:(Array.isArray(t)?t.length:t)?dv(t):"",[t,e]};let ZO=0;const hv=()=>++ZO;async function wE(...t){const[e,r,n,s]=t,i=tl({populateCache:!0,throwOnError:!0},typeof s=="boolean"?{revalidate:s}:s||{});let a=i.populateCache;const o=i.rollbackOnError;let l=i.optimisticData;const c=h=>
2typeof o=="function"?o(h):o!==!1,u=i.throwOnError;if(Do(r)){const h=r,m=[],b=e.keys();for(const g of b)!/^\$(inf|sub)\$/.test(g)&&h(e.get(g)._k)&&m.push(g);return Promise.all(m.map(d))}return d(r);async function d(h){const[m]=p_(h);if(!m)return;const[b,g]=xE(e,m),[p,y,v,_]=ra.get(e),w=()=>{const M=p[m];return(Do(i.revalidate)?i.revalidate(b().data,h):i.revalidate!==!1)&&(delete v[m],delete _[m],M&&M[0])?M[0](yE).then(()=>b().data):b().data};if(t.length<3)return w();let C=n,A,E=!1;const S=hv();y[m]=[S,0];const k=!Er(l),O=b(),T=O.data,R=O._c,N=Er(R)?T:R;if(k&&(l=Do(l)?l(N,T):l,g({data:l,_c:N})),Do(C))try{C=C(N)}catch(M){A=M,E=!0}if(C&&_E(C))if(C=await C.catch(M=>{A=M,E=!0}),S!==y[m][0]){if(E)throw A;return C}else E&&k&&c(A)&&(a=!0,g({data:N,_c:Ws}));if(a&&!E)if(Do(a)){const M=a(C,N);g({data:M,error:Ws,_c:Ws})}else g({data:C,error:Ws,_c:Ws});if(y[m][1]=hv(),Promise.resolve(w()).then(()=>{g({_c:Ws})}),E){if(u)throw A;return}return C}}const Wx=(t,e)=>{for(const r in t)t[r][0]&&t[r][0](e)},ej=(t,e)=>{if(!ra.has(t)){const r=tl(YO,e),n=Object.create(null),s=wE.bind(Ws,t);let i=oa;const a=Object.create(null),o=(u,d)=>{const h=a[u]||[];return a[u]=h,h.push(d),()=>h.splice(h.indexOf(d),1)},l=(u,d,h)=>{t.set(u,d);const m=a[u];if(m)for(const b of m)b(d,h)},c=()=>{if(!ra.has(t)&&(ra.set(t,[n,Object.create(null),Object.create(null),Object.create(null),s,l,o]),!Hc)){const u=r.initFocus(setTimeout.bind(Ws,Wx.bind(Ws,n,bE))),d=r.initReconnect(setTimeout.bind(Ws,Wx.bind(Ws,n,vE)));i=()=>{u&&u(),d&&d(),ra.delete(t)}}};return c(),[t,s,c,i]}return[t,ra.get(t)[4]]},tj=(t,e,r,n,s)=>{const i=r.errorRetryCount,a=s.retryCount,o=~~((Math.random()+.5)*(1<<(a<8?a:8)))*r.errorRetryInterval;!Er(i)&&a>i||setTimeout(n,o,s)},rj=iv,[SE,nj]=ej(new Map),sj=tl({onLoadingSlow:oa,onSuccess:oa,onError:oa,onErrorRetry:tj,onDiscarded:oa,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Fx?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Fx?5e3:3e3,compare:rj,isPaused:()=>!1,cache:SE,mutate:nj,fallback:{}},KO),ij=(t,e)=>{const r=tl(t,e);if(e){const{use:n,fallback:s}=t,{use:i,fallback:a}=e;n&&i&&(r.use=n.concat(i)),s&&a&&(r.fallback=tl(s,a))}return r},oj=x.createContext({}),aj="$inf$",CE=ah&&window.__SWR_DEVTOOLS_USE__,lj=CE?window.__SWR_DEVTOOLS_USE__:[],cj=()=>{CE&&(window.__SWR_DEVTOOLS_REACT__=_t)},uj=t=>Do(t[1])?[t[0],t[1],t[2]||{}]:[t[0],null,(t[1]===null?t[2]:t[1])||{}],dj=()=>{const t=x.useContext(oj);return x.useMemo(()=>tl(sj,t),[t])},hj=t=>(e,r,n)=>t(e,r&&((...i)=>{const[a]=p_(e),[,,,o]=ra.get(SE);if(a.startsWith(aj))return r(...i);const l=o[a];return Er(l)?r(...i):(delete o[a],l)}),n),fj=lj.concat(hj),pj=t=>function(...r){const n=dj(),[s,i,a]=uj(r),o=ij(n,a);let l=t;const{use:c}=o,u=(c||[]).concat(fj);for(let d=u.length;d--;)l=u[d](l);return l(s,i||o.fetcher||null,o)},mj=(t,e,r)=>{const n=e[t]||(e[t]=[]);return n.push(r),()=>{const s=n.indexOf(r);s>=0&&(n[s]=n[n.length-1],n.pop())}};cj();const Eg=_t.use||(t=>{switch(t.status){case"pending":throw t;case"fulfilled":return t.value;case"rejected":throw t.reason;default:throw t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}),t}}),kg={dedupe:!0},Hx=Promise.resolve(Ws),gj=(t,e,r)=>{const{cache:n,compare:s,suspense:i,fallbackData:a,revalidateOnMount:o,revalidateIfStale:l,refreshInterval:c,refreshWhenHidden:u,refreshWhenOffline:d,keepPreviousData:h,strictServerPrefetchWarning:m}=r,[b,g,p,y]=ra.get(n),[v,_]=p_(t),w=x.useRef(!1),C=x.useRef(!1),A=x.useRef(v),E=x.useRef(e),S=x.useRef(r),k=()=>S.current,O=()=>k().isVisible()&&k().isOnline(),[T,R,N,M]=xE(n,v),B=x.useRef({}).current,U=Er(a)?Er(r.fallback)?Ws:r.fallback[v]:a,X=(Ae,we)=>{for(const pe in B){const Ye=pe;if(Ye==="data"){if(!s(Ae[Ye],we[Ye])&&(!Er(Ae[Ye])||!s(fe,we[Ye])))return!1}else if(we[Ye]!==Ae[Ye])return!1}return!0},oe=x.useMemo(()=>{const Ae=!v||!e?!1:Er(o)?k().isPaused()||i?!1:l!==!1:o,we=nt=>{const xt=tl(nt);return delete xt._k,Ae?{isValidating:!0,isLoading:!0,...xt}:xt},pe=T(),Ye=M(),ft=we(pe),pt=pe===Ye?ft:we(Ye);let Lt=ft;return[()=>{const nt=we(T());return X(nt,Lt)?(Lt.data=nt.data,Lt.isLoading=nt.isLoading,Lt.isValidating=nt.isValidating,Lt.error=nt.error,Lt):(Lt=nt,nt)},()=>pt]}
2,[n,v]),L=nx.useSyncExternalStore(x.useCallback(Ae=>N(v,(we,pe)=>{X(pe,we)||Ae()}),[n,v]),oe[0],oe[1]),F=!w.current,V=b[v]&&b[v].length>0,Z=L.data,K=Er(Z)?U&&_E(U)?Eg(U):U:Z,ie=L.error,se=x.useRef(K),fe=h?Er(Z)?Er(se.current)?K:se.current:Z:K,Y=v&&Er(K),I=!Hc&&nx.useSyncExternalStore(()=>oa,()=>!1,()=>!0);m&&I&&!i&&Y&&console.warn(`Missing pre-initiated data for serialized key "${v}" during server-side rendering. Data fethcing should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);const z=V&&!Er(ie)?!1:F&&!Er(o)?o:k().isPaused()?!1:i?Er(K)?!1:l:Er(K)||l,q=!!(v&&e&&F&&z),ae=Er(L.isValidating)?q:L.isValidating,ee=Er(L.isLoading)?q:L.isLoading,le=x.useCallback(async Ae=>{const we=E.current;if(!v||!we||C.current||k().isPaused())return!1;let pe,Ye,ft=!0;const pt=Ae||{},Lt=!p[v]||!pt.dedupe,nt=()=>Bx?!C.current&&v===A.current&&w.current:v===A.current,xt={isValidating:!1,isLoading:!1},ct=()=>{R(xt)},_r=()=>{const Pe=p[v];Pe&&Pe[1]===Ye&&delete p[v]},ht={isValidating:!0};Er(T().data)&&(ht.isLoading=!0);try{if(Lt&&(R(ht),r.loadingTimeout&&Er(T().data)&&setTimeout(()=>{ft&&nt()&&k().onLoadingSlow(v,r)},r.loadingTimeout),p[v]=[we(_),hv()]),[pe,Ye]=p[v],pe=await pe,Lt&&setTimeout(_r,r.dedupingInterval),!p[v]||p[v][1]!==Ye)return Lt&&nt()&&k().onDiscarded(v),!1;xt.error=Ws;const Pe=g[v];if(!Er(Pe)&&(Ye<=Pe[0]||Ye<=Pe[1]||Pe[1]===0))return ct(),Lt&&nt()&&k().onDiscarded(v),!1;const be=T().data;xt.data=s(be,pe)?be:pe,Lt&&nt()&&k().onSuccess(pe,v,r)}catch(Pe){_r();const be=k(),{shouldRetryOnError:Te}=be;be.isPaused()||(xt.error=Pe,Lt&&nt()&&(be.onError(Pe,v,be),(Te===!0||Do(Te)&&Te(Pe))&&(!k().revalidateOnFocus||!k().revalidateOnReconnect||O())&&be.onErrorRetry(Pe,v,be,Ne=>{const Fe=b[v];Fe&&Fe[0]&&Fe[0](jx,Ne)},{retryCount:(pt.retryCount||0)+1,dedupe:!0})))}return ft=!1,ct(),!0},[v,n]),ve=x.useCallback((...Ae)=>wE(n,A.current,...Ae),[]);if(Sg(()=>{E.current=e,S.current=r,Er(Z)||(se.current=Z)}),Sg(()=>{if(!v)return;const Ae=le.bind(Ws,kg);let we=0;k().revalidateOnFocus&&(we=Date.now()+k().focusThrottleInterval);const Ye=mj(v,b,(ft,pt={})=>{if(ft==bE){const Lt=Date.now();k().revalidateOnFocus&&Lt>we&&O()&&(we=Lt+k().focusThrottleInterval,Ae())}else if(ft==vE)k().revalidateOnReconnect&&O()&&Ae();else{if(ft==yE)return le();if(ft==jx)return le(pt)}});return C.current=!1,A.current=v,w.current=!0,R({_k:_}),z&&(p[v]||(Er(K)||Hc?Ae():XO(Ae))),()=>{C.current=!0,Ye()}},[v]),Sg(()=>{let Ae;function we(){const Ye=Do(c)?c(T().data):c;Ye&&Ae!==-1&&(Ae=setTimeout(pe,Ye))}function pe(){!T().error&&(u||k().isVisible())&&(d||k().isOnline())?le(kg).then(we):we()}return we(),()=>{Ae&&(clearTimeout(Ae),Ae=-1)}},[c,u,d,v]),x.useDebugValue(fe),i){if(!Bx&&Hc&&Y)throw new Error("Fallback data is required when using Suspense in SSR.");Y&&(E.current=e,S.current=r,C.current=!1);const Ae=y[v],we=!Er(Ae)&&Y?ve(Ae):Hx;if(Eg(we),!Er(ie)&&Y)throw ie;const pe=Y?le(kg):Hx;!Er(fe)&&Y&&(pe.status="fulfilled",pe.value=!0),Eg(pe)}return{mutate:ve,get data(){return B.data=!0,fe},get error(){return B.error=!0,ie},get isValidating(){return B.isValidating=!0,ae},get isLoading(){return B.isLoading=!0,ee}}},Gh=pj(gj);function bj(t,e){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let r,n=0;return function(...i){clearTimeout(r);const a=Date.now(),o=a-n,l=e-o;l<=0?(n=a,t.apply(this,i)):r=setTimeout(()=>{n=Date.now(),t.apply(this,i)},l)}}var vj=bj;const yj=nD(vj);function Ux(t,e){return e!=null?yj(t,e):t}function _j(t){const[e,r]=x.useState(t);return x.useEffect(()=>{uD(t,e)||r(t)},[t,e]),e}function xj({api:t="/api/chat",id:e,initialMessages:r,initialInput:n="",sendExtraMessageFields:s,onToolCall:i,experimental_prepareRequestBody:a,maxSteps:o=1,streamProtocol:l="data",onResponse:c,onFinish:u,onError:d,credentials:h,headers:m,body:b,generateId:g=Zb,fetch:p,keepLastMessageOnError:y=!0,experimental_throttle:v}={}){const[_]=x.useState(g),w=e??_,C=typeof t=="string"?[t,w]:w,A=_j(r??[]),E=x.useMemo(()=>dg(A),[A]),{data:S,mutate:k}=Gh([C,"messages"],null,{fallbackData:E}),O=x.useRef(S||[]);x.useEffect(()=>{O.current=S||[]},[S]);const{data:T,mutate:R}=Gh([C,"streamData"],null),N=x.useRef(T);x.useEffect(()=>{N.current=T},[T]);const{data:M="ready",mutate:B}=Gh([C,"status"],null),{data:U=void 0,mutate:X}=Gh([C,"error"],null),oe=x.useRef(null),L=x.useRef({credentials:h,headers:m,body:b});x.useEffect(()=>{L.current={credentials:h,headers:m,body:b}},[h,m,b]);const F=x.useCallback(async(ee,le="generate")=>{var ve,ye;B("submitted"),X(void 0);const Ae=dg(ee.messages),we=Ae.length,pe=sD((ve=Ae[Ae.length-1])==null?void 0:ve.toolInvocations);
2try{const ft=new AbortController;oe.current=ft;const pt=Ux(k,v),Lt=Ux(R,v),nt=O.current;pt(Ae,!1);const xt=s?Ae:Ae.map(({role:_r,content:ht,experimental_attachments:Pe,data:be,annotations:Te,toolInvocations:Ne,parts:Fe})=>({role:_r,content:ht,...Pe!==void 0&&{experimental_attachments:Pe},...be!==void 0&&{data:be},...Te!==void 0&&{annotations:Te},...Ne!==void 0&&{toolInvocations:Ne},...Fe!==void 0&&{parts:Fe}})),ct=N.current;await iD({api:t,body:(ye=a?.({id:w,messages:Ae,requestData:ee.data,requestBody:ee.body}))!=null?ye:{id:w,messages:xt,data:ee.data,...L.current.body,...ee.body},streamProtocol:l,credentials:L.current.credentials,headers:{...L.current.headers,...ee.headers},abortController:()=>oe.current,restoreMessagesOnFailure(){y||pt(nt,!1)},onResponse:c,onUpdate({message:_r,data:ht,replaceLastMessage:Pe}){B("streaming"),pt([...Pe?Ae.slice(0,Ae.length-1):Ae,_r],!1),ht?.length&&Lt([...ct??[],...ht],!1)},onToolCall:i,onFinish:u,generateId:g,fetch:p,lastMessage:Ae[Ae.length-1],requestType:le}),oe.current=null,B("ready")}catch(ft){if(ft.name==="AbortError")return oe.current=null,B("ready"),null;d&&ft instanceof Error&&d(ft),X(ft),B("error")}const Ye=O.current;oD({originalMaxToolInvocationStep:pe,originalMessageCount:we,maxSteps:o,messages:Ye})&&await F({messages:Ye})},[k,B,t,L,c,u,d,X,R,N,l,s,a,i,o,O,oe,g,p,y,v,w]),V=x.useCallback(async(ee,{data:le,headers:ve,body:ye,experimental_attachments:Ae=ee.experimental_attachments}={})=>{var we,pe;const Ye=await rx(Ae),ft=O.current.concat({...ee,id:(we=ee.id)!=null?we:g(),createdAt:(pe=ee.createdAt)!=null?pe:new Date,experimental_attachments:Ye.length>0?Ye:void 0,parts:aD(ee)});return F({messages:ft,headers:ve,body:ye,data:le})},[F,g]),Z=x.useCallback(async({data:ee,headers:le,body:ve}={})=>{const ye=O.current;if(ye.length===0)return null;const Ae=ye[ye.length-1];return F({messages:Ae.role==="assistant"?ye.slice(0,-1):ye,headers:le,body:ve,data:ee})},[F]),K=x.useCallback(()=>{oe.current&&(oe.current.abort(),oe.current=null)},[]),ie=x.useCallback(async()=>{const ee=O.current;F({messages:ee},"resume")},[F]),se=x.useCallback(ee=>{typeof ee=="function"&&(ee=ee(O.current));const le=dg(ee);k(le,!1),O.current=le},[k]),fe=x.useCallback(ee=>{typeof ee=="function"&&(ee=ee(N.current)),R(ee,!1),N.current=ee},[R]),[Y,I]=x.useState(n),z=x.useCallback(async(ee,le={},ve)=>{var ye;if((ye=ee?.preventDefault)==null||ye.call(ee),!Y&&!le.allowEmptySubmit)return;ve&&(L.current={...L.current,...ve});const Ae=await rx(le.experimental_attachments),pe={messages:O.current.concat({id:g(),createdAt:new Date,role:"user",content:Y,experimental_attachments:Ae.length>0?Ae:void 0,parts:[{type:"text",text:Y}]}),headers:le.headers,body:le.body,data:le.data};F(pe),I("")},[Y,g,F]),q=ee=>{I(ee.target.value)},ae=x.useCallback(({toolCallId:ee,result:le})=>{const ve=O.current;if(lD({messages:ve,toolCallId:ee,toolResult:le}),k([...ve.slice(0,ve.length-1),{...ve[ve.length-1]}],!1),M==="submitted"||M==="streaming")return;const ye=ve[ve.length-1];cD(ye)&&F({messages:ve})},[k,M,F]);return{messages:S??[],id:w,setMessages:se,data:T,setData:fe,error:U,append:V,reload:Z,stop:K,experimental_resume:ie,input:Y,setInput:I,handleInputChange:q,handleSubmit:z,isLoading:M==="submitted"||M==="streaming",status:M,addToolResult:ae}}const qh="<boltArtifact",zx="</boltArtifact>",wj="<boltAction",Kh="</boltAction>",Vx="<bolt-quick-actions>",Gx="</bolt-quick-actions>",wl=ya("MessageParser");function qx(t){const e=/^\s*```\w*\n([\s\S]*?)\n\s*```\s*$/,r=t.match(e);return r?r[1]:t}function Kx(t){return t.replace(/</g,"<").replace(/>/g,">")}class Sj{constructor(e={}){this._options=e}#e=new Map;parse(e,r){let n=this.#e.get(e);n||(n={position:0,insideAction:!1,insideArtifact:!1,skipCurrentActionCallbacks:!1,currentAction:{content:""},actionId:0},this.#e.set(e,n));let s="",i=n.position,a=!1;for(;i<r.length;){if(r.startsWith(Vx,i)){console.log("input:",r.slice(i));const o=r.indexOf(Gx,i);if(o!==-1){const l=r.slice(i+Vx.length,o),c=/<bolt-quick-action([^>]*)>([\s\S]*?)<\/bolt-quick-action>/g;let u;const d=[];for(;(u=c.exec(l))!==null;){const h=u[1],m=u[2],b=this.#t(h,"type"),g=this.#t(h,"message"),p=this.#t(h,"path"),y=this.#t(h,"href");d.push(Aj({type:b||"",message:g||"",path:p||"",href:y||""},m))}s+=Ej(d),i=o+Gx.length;continue}}if(n.insideArtifact){const o=n.currentArtifact;if(o===void 0&&_D("Artifact not initialized"),n.insideAction){const l=r.indexOf(Kh,i),c=n.currentAction,u=this.#n(c),d=String(n.actionId-1);if(l!==-1){if(c.content+=r.slice(i,l),u||n.skipCurrentActionCallbacks){n.insideAction=!1,n.skipCurrentActionCallbacks=!1,n.currentAction={content:""},i=l+Kh.length;continue}let h=c.content.trim();if("type"in c&&c.type==="file"){const m=this.#r(c),b=c.encoding==="base64";if(!m){wl.warn("Skipping malformed file action close because filePath is missing"),n.insideAction=!1,n.currentAction={content:""},i=l+Kh.length;continue}!b&&!m.endsWith(".md")&&(h=qx(h),h=Kx(h)),b||(h+=` 3`)}c.content=h,this._options.callbacks?.onActionClose?.({artifactId:o.id,messageId:e,actionId:d,action:c}),n.insideAction=!1,n.skipCurrentActionCallbacks=!1,n.currentAction={content:""},i=l+Kh.length}else{if(u||n.skipCurrentActionCallbacks)break;if("type"in c&&c.type==="file"){let h=r.slice(i);const m=this.#r(c),b=c.encoding==="base64";if(!m){wl.warn("Skipping malformed file action stream because filePath is missing");break}!b&&!m.endsWith(".md")&&(h=qx(h),h=Kx(h)),this._options.callbacks?.onActionStream?.({artifactId:o.id,messageId:e,actionId:d,action:{...c,content:h,filePath:m}})}break}}else{const l=r.indexOf(wj,i),c=r.indexOf(zx,i);if(l!==-1&&(c===-1||l<c)){const u=r.indexOf(">",l);if(u!==-1){if(n.insideAction=!0,n.currentAction=this.#i(r,l,u),n.skipCurrentActionCallbacks=this.#n(n.currentAction),n.skipCurrentActionCallbacks){wl.warn("Skipping malformed file action because filePath is missing"),i=u+1;continue}this._options.callbacks?.onActionOpen?.({artifactId:o.id,messageId:e,actionId:String(n.actionId++),action:n.currentAction}),i=u+1}else break}else if(c!==-1)this._options.callbacks?.onArtifactClose?.({messageId:e,...o}),n.insideArtifact=!1,n.currentArtifact=void 0,i=c+zx.length;else break}}else if(r[i]==="<"&&r[i+1]!=="/"){let o=i,l="";for(;o<r.length&&l.length<qh.length;){if(l+=r[o],l===qh){const c=r[o+1];if(c&&c!==">"&&c!==" "){s+=r.slice(i,o+1),i=o+1;break}const u=r.indexOf(">",o);if(u!==-1){const d=r.slice(i,u+1),h=this.#t(d,"title"),m=this.#t(d,"type"),b=this.#t(d,"id");h||wl.warn("Artifact title missing"),b||wl.warn("Artifact id missing");const g=b||`missing-artifact-id-${e}-${n.position}`,p=h||"Untitled Artifact";n.insideArtifact=!0;const y={id:g,title:p,type:m};n.currentArtifact=y,this._options.callbacks?.onArtifactOpen?.({messageId:e,...y});const v=this._options.artifactElement??Cj;s+=v({messageId:e}),i=u+1}else a=!0;break}else if(!qh.startsWith(l)){s+=r.slice(i,o+1),i=o+1;break}o++}if(o===r.length&&qh.startsWith(l))break}else s+=r[i],i++;if(a)break}return n.position=i,s}reset(){this.#e.clear()}#i(e,r,n){const s=e.slice(r,n+1),i=this.#t(s,"type"),a={type:i,content:""};if(i==="file"){const o=this.#t(s,"filePath"),l=this.#t(s,"encoding")?.toLowerCase();o||wl.debug("File path not specified");const c=a;c.filePath=o,l==="base64"&&(c.encoding="base64")}else["shell","start"].includes(i)||wl.warn(`Unknown action type '${i}'`);return a}#t(e,r){const n=e.match(new RegExp(`${r}="([^"]*)"`,"i"));
3return n?n[1]:void 0}#n(e){return"type"in e&&e.type==="file"&&!this.#r(e)}#r(e){if(!("type"in e)||e.type!=="file"||!("filePath"in e))return;const{filePath:r}=e;if(!(typeof r!="string"||r.trim().length===0))return r}}const Cj=t=>`<div ${['class="__boltArtifact__"',...Object.entries(t).map(([r,n])=>`data-${AE(r)}=${JSON.stringify(n)}`)].join(" ")}></div>`;function AE(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Aj(t,e){const r=['class="__boltQuickAction__"','data-bolt-quick-action="true"',...Object.entries(t).map(([n,s])=>`data-${AE(n)}=${JSON.stringify(s)}`)];return console.log("elementProps",`<button ${r.join(" ")}>${e}</button>`),`<button ${r.join(" ")}>${e}</button>`}function Ej(t){return`<div class="__boltQuickAction__" data-bolt-quick-action="true">${t.join("")}</div>`}const yi=ya("useMessageParser"),Uc=new Map,Yh=new Map,zc=new Map,dp=new Map,Mc=new Map,ru=new Map;function $u(t){return Uc.has(t)||Uc.set(t,{artifactOpenCount:0,artifactCloseCount:0,actionOpenCount:0,actionCloseCount:0,actionStreamCount:0}),Uc.get(t)}function Yx(t){return zc.has(t)||zc.set(t,new Set),zc.get(t)}function Xx(t){return t.map(e=>!e||typeof e!="object"||!("type"in e)||e.type!=="text"||!("text"in e)?"":typeof e.text=="string"?e.text??"":"").join("")}function kj(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?Xx(t.content):Array.isArray(t.parts)?Xx(t.parts):""}function Pj(t){const e=t||"",r=(e.match(/<boltArtifact\b/gi)||[]).length,n=(e.match(/<boltAction\b/gi)||[]).length,s=(e.match(/^\s*(?:[-*]\s*)?(?:Create|Update|Delete|Run command|Start Application|Install Dependencies|Install project dependencies)\b/gim)||[]).length;return{contentLength:e.length,boltArtifactCount:r,boltActionCount:n,actionLikeLineCount:s}}function Pg(t,e,r){return`${t}:${e}:${r}`}function EE(t,e){return`${t}:${e}`}function Tj(t){const e=EE(t.messageId,t.artifactId),r=ru.get(e)??[];r.push(t),ru.set(e,r)}function Rj(t,e){const r=EE(t,e),n=ru.get(r);if(!n||n.length===0)return;if(ru.delete(r),e==="template-bootstrap"){(async()=>{try{await j.waitForPendingActions();for(const i of n)j.runAction(i)}catch(i){yi.warn("deferred_template_bootstrap_failed",{messageId:t,artifactId:e,error:i instanceof Error?i.message:String(i)})}})();return}for(const i of n)j.runAction(i)}function Ij(t){return t?`${t.length}:${t.slice(-128)}`:"0:"}const Tg=new Sj({callbacks:{onArtifactOpen:t=>{const e=$u(t.messageId);e.artifactOpenCount+=1,yi.trace("onArtifactOpen",t),yi.info("parser_artifact_open",{messageId:t.messageId,artifactId:t.id,title:t.title,type:t.type,artifactOpenCount:e.artifactOpenCount}),j.showWorkbench.set(!0),j.addArtifact(t)},onArtifactClose:t=>{const e=$u(t.messageId);e.artifactCloseCount+=1,yi.trace("onArtifactClose");const r=Array.from(zc.get(t.messageId)??[]);if(yi.info("parser_artifact_close",{messageId:t.messageId,artifactId:t.id,artifactCloseCount:e.artifactCloseCount}),r.length>0){const n=r.sort().join(", "),s=dp.get(t.messageId);n!==s&&(dp.set(t.messageId,n),yi.info(`assistant_file_actions ${t.messageId}: ${n}`))}Rj(t.messageId,t.id),j.updateArtifact(t,{closed:!0})},onActionOpen:t=>{const e=$u(t.messageId);e.actionOpenCount+=1,yi.trace("onActionOpen",t.action),yi.info("parser_action_open",{messageId:t.messageId,artifactId:t.artifactId,actionId:t.actionId,actionType:t.action.type,filePath:t.action.type==="file"?t.action.filePath:void 0,actionOpenCount:e.actionOpenCount}),j.registerArtifactIdentity({messageId:t.messageId,artifactId:t.artifactId,type:t.action.type==="start"?"runtime":"bundled"}),t.action.type==="file"&&(Yx(t.messageId).add(t.action.filePath),yi.info(`parser_action_file_open ${t.action.filePath}`)),t.action.type==="file"&&j.addAction(t)},onActionClose:t=>{const e=$u(t.messageId);if(e.actionCloseCount+=1,yi.trace("onActionClose",t.action),yi.info("parser_action_close",{messageId:t.messageId,artifactId:t.artifactId,actionId:t.actionId,actionType:t.action.type,filePath:t.action.type==="file"?t.action.filePath:void 0,contentLength:t.action.content?.length??0,actionCloseCount:e.actionCloseCount}),t.action.type==="file"&&(Yx(t.messageId).add(t.action.filePath),yi.info(`parser_action_file_close ${t.action.filePath} (${t.action.content?.length??0} chars)`)),t.action.type!=="file"){j.addAction(t),Tj(t),Mc.delete(Pg(t.messageId,t.artifactId,t.actionId));return}j.runAction(t),Mc.delete(Pg(t.messageId,t.artifactId,t.actionId))},onActionStream:t=>{if(j.registerArtifactIdentity({messageId:t.messageId,artifactId:t.artifactId,type:t.action.type==="start"?"runtime":"bundled"}),t.action.type==="file"){const r=Pg(t.messageId,t.artifactId,t.actionId),n=typeof t.action.content=="string"?t.action.content:"",s=Ij(n);if(Mc.get(r)===s)return;Mc.set(r,s)}const e=$u(t.messageId);e.actionStreamCount+=1,yi.trace("onActionStream",t.action),(e.actionStreamCount===1||e.actionStreamCount%25===0)&&yi.info("parser_action_stream",{messageId:t.messageId,artifactId:t.artifactId,actionId:t.actionId,actionType:t.action.type,streamEventCount:e.actionStreamCount,contentLength:t.action.content?.length??0}),t.action.type==="file"&&j.runAction(t,!0)}}});function Nj(){const[t,e]=x.useState({}),r=x.useRef(new Map),n=x.useCallback(()=>
3{Tg.reset(),Uc.clear(),Yh.clear(),zc.clear(),dp.clear(),Mc.clear(),ru.clear(),r.current.clear(),e({})},[]),s=x.useCallback((i,a)=>{const o=[],l=r.current,c=new Set,u=m=>{const b=[];for(const[g,p]of i.entries()){if(p.role!=="assistant"&&p.role!=="user")continue;const y=kj(p);if(c.add(p.id),!m){const v=l.get(p.id);if(typeof v=="string"&&v===y)continue}b.push({index:g,messageId:p.id,textContent:y})}return b};let d=u(!1);const h=d.some(({messageId:m,textContent:b})=>{const g=l.get(m);return typeof g!="string"||g===b?!1:!b.startsWith(g)});h&&(Tg.reset(),Uc.clear(),Yh.clear(),zc.clear(),dp.clear(),Mc.clear(),ru.clear(),l.clear(),d=u(!0));for(const{index:m,messageId:b,textContent:g}of d){const p=i[m],y=Tg.parse(b,g);if(o.push({index:m,delta:y}),l.set(b,g),p.role==="assistant"){const v=Uc.get(b),_=Pj(g),w=[a?"loading":"idle",Math.floor(_.contentLength/5e3),_.boltArtifactCount,_.boltActionCount,_.actionLikeLineCount,v?.artifactOpenCount??0,v?.actionOpenCount??0,v?.actionCloseCount??0,v?.actionStreamCount??0].join(":"),C=Yh.get(b);w!==C&&Yh.set(b,w)}}for(const m of Array.from(l.keys()))c.has(m)||l.delete(m);e(m=>{let b=h?{}:m,g=!1;for(const{index:p,delta:y}of o){if(!y)continue;const v=b[p]||"",_=v+y;_!==v&&(g||(b={...b},g=!0),b[p]=_)}return g?b:m})},[]);return{parsedMessages:t,parseMessages:s,resetParsedMessages:n}}const Lj=["input","textarea"];class Dj{#e=new EventTarget;dispatch(e){this.#e.dispatchEvent(new Event(e))}on(e,r){return this.#e.addEventListener(e,r),()=>{this.#e.removeEventListener(e,r)}}}const kE=new Dj;function Mj(){const t=We(FD);x.useEffect(()=>{const e=r=>{const n=document.activeElement&&"tagName"in document.activeElement?String(document.activeElement.tagName||"").toLowerCase():"";if(!(n&&Lj.includes(n)&&!r.altKey&&!r.metaKey&&!r.ctrlKey))for(const[s,i]of Object.entries(t)){if(!i||typeof i.key!="string"||i.key.length===0)continue;const a=typeof r.key=="string"?r.key.toLowerCase():"",l=i.key.toLowerCase()===a||typeof r.code=="string"&&`Key${i.key.toUpperCase()}`===r.code,u=(i.ctrlOrMetaKey?ox&&r.metaKey||!ox&&r.ctrlKey:!0)&&(i.ctrlKey===void 0||i.ctrlKey===r.ctrlKey)&&(i.metaKey===void 0||i.metaKey===r.metaKey)&&(i.shiftKey===void 0||i.shiftKey===r.shiftKey)&&(i.altKey===void 0||i.altKey===r.altKey);if(l&&u){i.isPreventDefault&&(r.preventDefault(),r.stopPropagation()),kE.dispatch(s),i.action();break}}};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[t])}function Oj(t,e){let r;const n=()=>{r&&(clearTimeout(r),r=void 0)},s=async()=>{n(),await t()};return{schedule(){n(),r=setTimeout(()=>{s()},e)},cancel:n,flush:s}}class jj{appId;#e={state:null,isLoading:!1,isSynced:!0};#i=new Set;#t=null;#n=null;#r=null;#o=Oj(async()=>{await this.flushSync()},dx);constructor(e){this.appId=Z1(e)}get snapshot(){return this.#e}subscribe(e){return this.#i.add(e),e(this.#e),()=>{this.#i.delete(e)}}async load(){return this.#n?this.#n:(this.#e={...this.#e,isLoading:!0},this.#s(),this.#n=(async()=>{const e=await Of(),[r,n]=await Promise.all([e?fM(e,this.appId).then(a=>a??null):Promise.resolve(null),pM(this.appId)]),s=ux(r,n)>=0?r??n:n,i=!s||ux(s,n)===0;return s&&e&&await Bh(e,s),this.#e={state:s??null,isLoading:!1,isSynced:i},this.#t=n??null,this.#s(),s&&!i&&this.flushSync(),s??null})().finally(()=>{this.#n=null}),this.#n)}async stageContent(e){const r=!!this.#t,n=!!this.#e.state,s={appId:this.appId,content:e,version:this.#e.state?.ver
3sion??this.#t?.version??0,updatedAt:Date.now()},i=xc(this.#e.state),a=xc(s);if(i===a)return this.#e.state??s;this.#e={state:s,isLoading:!1,isSynced:!1},console.info("[builder.sync] Staged builder state locally",{appId:this.appId,version:s.version,updatedAt:s.updatedAt}),this.#s();const o=await Of();return o&&await Bh(o,s),!r&&!n?(console.info("[builder.sync] No prior synced builder state found. Flushing immediately.",{appId:this.appId}),this.flushSync()):(console.info("[builder.sync] Scheduling debounced builder sync",{appId:this.appId,debounceMs:dx}),this.#o.schedule()),s}async flushSync(){if(this.#r)return this.#r;const e=this.#e.state;if(!e)return null;const r=xc(e),n=xc(this.#t);if(this.#t&&r===n)return this.#e={...this.#e,isSynced:!0},this.#s(),e;const s={...e,version:Math.max(e.version,this.#t?.version??0)+1,updatedAt:Date.now()};return this.#r=(async()=>{try{const i=await Of();i&&await Bh(i,s);const a=await mM(this.appId,s),o=this.#e.state,l=!!o&&xc(o)!==xc(s);return this.#t=a,l?(this.#e={state:o,isLoading:!1,isSynced:!1},this.#o.schedule()):this.#e={state:a,isLoading:!1,isSynced:!0},console.info("[builder.sync] Builder state synced to IndexedDB and Cloudflare R2",{appId:this.appId,version:a.version,updatedAt:a.updatedAt,changedWhileSyncing:l}),this.#s(),i&&!l&&await Bh(i,a),a}catch(i){return console.error("[builder.sync] Builder-state sync failed",{appId:this.appId,error:i}),this.#e={...this.#e,isSynced:!1},this.#s(),e}finally{this.#r=null}})(),this.#r}replaceState(e,r){this.#e={state:e,isLoading:!1,isSynced:r?.markSynced??!1},r?.markSynced&&(this.#t=e),this.#s()}cancelPendingSync(){this.#o.cancel()}#s(){this.#i.forEach(e=>{e(this.#e)})}}const Jx=new Map;function $j(t){const e=Z1(t),r=Jx.get(e);if(r)return r;const n=new jj(e);return Jx.set(e,n),n}async function Bj(t,e){return $j(t).stageContent(e)}const Fj={damping:.7,stiffness:.05,mass:1.25},Wj=70,Hj=1e3/60,Uj=350,Qx=new Set(["scroll","auto"]);let cm=!1;globalThis.document?.addEventListener("mousedown",()=>{cm=!0});globalThis.document?.addEventListener("mouseup",()=>{cm=!1});globalThis.document?.addEventListener("click",()=>{cm=!1});const zj=(t={})=>{const[e,r]=x.useState(!1),[n,s]=x.useState(t.initial!==!1),[i,a]=x.useState(!1),o=x.useRef(null);o.current=t;const l=x.useCallback(()=>{if(!cm)return!1;const v=window.getSelection();if(!v||!v.rangeCount)return!1;const _=v.getRangeAt(0);return _.commonAncestorContainer.contains(p.current)||p.current?.contains(_.commonAncestorContainer)},[]),c=x.useCallback(v=>{d.isAtBottom=v,s(v)},[]),u=x.useCallback(v=>{d.escapedFromLock=v,r(v)},[]),d=x.useMemo(()=>{let v;return{escapedFromLock:e,isAtBottom:n,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return p.current?.scrollTop??0},set scrollTop(_){p.current&&(p.current.scrollTop=_,d.ignoreScrollToTop=p.current.scrollTop)},get targetScrollTop(){return!p.current||!y.current?0:p.current.scrollHeight-1-p.current.clientHeight},get calculatedTargetScrollTop(){if(!p.current||!y.current)return 0;const{targetScrollTop:_}=this;if(!t.targetScrollTop)return _;if(v?.targetScrollTop===_)return v.calculatedScrollTop;const w=Math.max(Math.min(t.targetScrollTop(_,{scrollElement:p.current,contentElement:y.current}),_),0);return v={targetScrollTop:_,calculatedScrollTop:w},requestAnimationFrame(()=>{v=void 0}),w},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=Wj}}},[]),h=x.useCallback((v={})=>{typeof v=="string"&&(v={animation:v}),v.preserveScrollPosition||c(!0);const _=Date.now()+(Number(v.wait)||0),w=Ig(o.current,v.animation),{ignoreEscapes:C=!1}=v;let A,E=d.calculatedTargetScrollTop;v.duration instanceof Promise?v.duration.finally(()=>{A=Date.now()}):A=_+(v.duration??0);const S=async()=>{const k=new Promise(requestAnimationFrame).then(()=>{if(!d.isAtBottom)return d.animation=void 0,!1;const{scrollTop:O}=d,T=performance.now(),R=(T-(d.lastTick??T))/Hj;if(d.animation||={behavior:w,promise:k,ignoreEscapes:C},d.animation.behavior===w&&(d.lastTick=T),l()||_>Date.now())return S();if(O<Math.min(E,d.calculatedTargetScrollTop)){if(d.animation?.behavior===w){if(w==="instant")return d.scrollTop=d.calculatedTargetScrollTop,S();d.velocity=(w.damping*d.velocity+w.stiffness*d.scrollDifference)/w.mass,d.accumulated+=d.velocity
3*R,d.scrollTop+=d.accumulated,d.scrollTop!==O&&(d.accumulated=0)}return S()}return A>Date.now()?(E=d.calculatedTargetScrollTop,S()):(d.animation=void 0,d.scrollTop<d.calculatedTargetScrollTop?h({animation:Ig(o.current,o.current.resize),ignoreEscapes:C,duration:Math.max(0,A-Date.now())||void 0}):d.isAtBottom)});return k.then(O=>(requestAnimationFrame(()=>{d.animation||(d.lastTick=void 0,d.velocity=0)}),O))};return v.wait!==!0&&(d.animation=void 0),d.animation?.behavior===w?d.animation.promise:S()},[c,l,d]),m=x.useCallback(()=>{u(!0),c(!1)},[u,c]),b=x.useCallback(({target:v})=>{if(v!==p.current)return;const{scrollTop:_,ignoreScrollToTop:w}=d;let{lastScrollTop:C=_}=d;d.lastScrollTop=_,d.ignoreScrollToTop=void 0,w&&w>_&&(C=w),a(d.isNearBottom),setTimeout(()=>{if(d.resizeDifference||_===w)return;if(l()){u(!0),c(!1);return}const A=_>C,E=_<C;if(d.animation?.ignoreEscapes){d.scrollTop=C;return}E&&(u(!0),c(!1)),A&&u(!1),!d.escapedFromLock&&d.isNearBottom&&c(!0)},1)},[u,c,l,d]),g=x.useCallback(({target:v,deltaY:_})=>{let w=v;for(;w;){const C=getComputedStyle(w);if(Qx.has(C.overflow)||Qx.has(C.overflowY))break;if(!w.parentElement)return;w=w.parentElement}w===p.current&&_<0&&p.current.scrollHeight>p.current.clientHeight&&!d.animation?.ignoreEscapes&&(u(!0),c(!1))},[u,c,d]),p=Zx(v=>{p.current?.removeEventListener("scroll",b),p.current?.removeEventListener("wheel",g),v?.addEventListener("scroll",b,{passive:!0}),v?.addEventListener("wheel",g,{passive:!0})},[]),y=Zx(v=>{if(d.resizeObserver?.disconnect(),!v)return;let _;d.resizeObserver=new ResizeObserver(([w])=>{const{height:C}=w.contentRect,A=C-(_??C);if(d.resizeDifference=A,d.scrollTop>d.targetScrollTop&&(d.scrollTop=d.targetScrollTop),a(d.isNearBottom),A>=0){const E=Ig(o.current,_?o.current.resize:o.current.initial);h({animation:E,wait:!0,preserveScrollPosition:!0,duration:E==="instant"?void 0:Uj})}else d.isNearBottom&&(u(!1),c(!0));_=C,requestAnimationFrame(()=>{setTimeout(()=>{d.resizeDifference===A&&(d.resizeDifference=0)},1)})}),d.resizeObserver?.observe(v)},[]);return{contentRef:y,scrollRef:p,scrollToBottom:h,stopScroll:m,isAtBottom:n||i,isNearBottom:i,escapedFromLock:e,state:d}};function Zx(t,e){const r=x.useCallback(n=>(r.current=n,t(n)),e);return r}const Rg=new Map;function Ig(...t){const e={...Fj};let r=!1;for(const s of t){if(s==="instant"){r=!0;continue}typeof s=="object"&&(r=!1,e.damping=s.damping??e.damping,e.stiffness=s.stiffness??e.stiffness,e.mass=s.mass??e.mass)}const n=JSON.stringify(e);return Rg.has(n)||Rg.set(n,Object.freeze(e)),r?"instant":Rg.get(n)}const PE=x.createContext(null),Vj=typeof window<"u"?x.useLayoutEffect:x.useEffect;function fv({instance:t,children:e,resize:r,initial:n,mass:s,damping:i,stiffness:a,targetScrollTop:o,contextRef:l,...c}){const u=x.useRef(null),d=x.useCallback((C,A)=>(w?.targetScrollTop??o)?.(C,A)??C,[o]),h=zj({mass:s,damping:i,stiffness:a,resize:r,initial:n,targetScrollTop:d}),{scrollRef:m,contentRef:b,scrollToBottom:g,stopScroll:p,isAtBottom:y,escapedFromLock:v,state:_}=t??h,w=x.useMemo(()=>({scrollToBottom:g,stopScroll:p,scrollRef:m,isAtBottom:y,escapedFromLock:v,contentRef:b,state:_,get targetScrollTop(){return u.current},set targetScrollTop(C){u.current=C}}),[g,y,b,m,p,v,_]);return x.useImperativeHandle(l,()=>w,[w]),Vj(()=>{if(!m.current)return;const C=getComputedStyle(m.current);C.overflow==="visible"&&C.overflowY==="visible"&&(m.current.style.overflowY="auto",m.current.style.overflowX="hidden")},[]),f.jsx(PE.Provider,{value:w,children:f.jsx("div",{...c,children:typeof e=="function"?e(w):e})})}function Gj({children:t,...e}){const r=TE();return f.jsx("div",{ref:r.scrollRef,className:"relative flex w-full min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden [scrollbar-gutter:stable]",children:f.jsx("div",{...e,ref:r.contentRef,children:typeof t=="function"?t(r):t})})}fv.Content=Gj;function TE(){const t=x.useContext(PE);if(!t)throw new Error("use-stick-to-bottom component context must be used within a StickToBottom component");return t}const qj=new Set(["my app","my website","my workspace","website","site","app","untitled","untitled app","untitled project","create initial files","imported files"]),ew=/<boltArtifact\b([^>]*)>/gi,Kj=/\bid=(['"])([^'"]+)\1/i,Yj=/\btitle=(['"])([^'"]+)\1/i,Xj=/(?:^\s*|\s+)\[(?:Model|Provider):[^\]]+\](?=\s|$)/gim,Jj=new Set(["template-bootstrap","starter-template-files","imported-files"]),Qj=["implicit-artifact-","missing-artifact-id-"];function RE(t){return typeof t.content=="string"?t.content:Array.isArray(t.parts)?t.parts.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(` 4`):""}function tw(t){return String(t||"").trim().toLowerCase().replace(/\.\.\.$/,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function Zj(t,e){const r=tw(t),n=tw(e);return!r||!n?!1:r===n||r.startsWith(n)||n.startsWith(r)}function e$(t){const e=lm(t)||t,r=String(e||"").replace(Xj," ").replace(/<boltArtifact[\s\S]*?<\/boltArtifact>/gi,"").replace(/<!--\s*system:[a-z-]+\s*-->[\s\S]*?<!--\s*\/system:[a-z-]+\s*-->/gi,"").replace(/<div class=["']__boltSelectedElement__["'][^>]*>[\s\S]*?<\/div>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return r?r.length>72?`${r.slice(0,69).trimEnd()}...`:r:""}function t$(t,e){return Array.isArray(t)?t.filter(r=>r.role==="user").map(r=>{const n=r.userVisibleContent,s=e$(typeof n=="string"&&n.trim()?n:RE(r));return e==="newsletter"&&s?Ad(s).workspaceTitle:s}).filter(r=>r.length>0):[]}function r$(t){const e=String(t?.id||"").trim().toLowerCase();return!e||Jj.has(e)?!1:!Qj.some(r=>e.startsWith(r))}function n$(t){if(!Array.isArray(t))return null;for(const e of t){if(e.role!=="assistant")continue;const r=RE(e);if(!(!r||!r.includes("<boltArtifact"))){ew.lastIndex=0;for(const n of r.matchAll(ew)){const s=String(n[1]||""),i=s.match(Kj),a=String(i?.[2]||"").trim();if(!a||!r$({id:a}))continue;const o=s.match(Yj),l=String(o?.[2]||"").trim();return l?{id:a,title:l}:{id:a}}}}return null}function s$(t){return String(t||"").trim().toLowerCase()}function IE(t){const e=s$(t);return e.length>0&&!qj.has(e)}function m_(t){const e=String(t.persistedPrimaryArtifactId||"").trim(),r
4=String(t.persistedWorkspaceTitle||"").trim(),n=String(t.originalArtifact?.id||"").trim();if(e||IE(r))return hx({id:e||n,title:r});if(t.originalArtifact)return hx({id:String(t.originalArtifact.id||"").trim(),title:String(t.originalArtifact.title||"").trim()});const s=String(t.fallbackTitle||"").trim();return s||r||"My Workspace"}function um(t){const e=t.mode||null,r=String(t.description||"").trim(),n=e==="newsletter"&&r&&!t.metadata?.workspaceTitle?Ad(r).workspaceTitle:r,s=t$(t.messages,e);if(IE(n)&&!s.some(o=>Zj(n,o)))return n;const a=n$(t.messages);return m_({persistedPrimaryArtifactId:String(t.metadata?.primaryArtifactId||"").trim()||a?.id,persistedWorkspaceTitle:String(t.metadata?.workspaceTitle||"").trim()||a?.title,originalArtifact:a,fallbackTitle:n})}function i$({initialDescription:t=sp.get(),customChatId:e,syncWithGlobalStore:r,mode:n}){const s=We(F1),[i,a]=x.useState(!1),[o,l]=x.useState(t),[c,u]=x.useState(),d=We(On),h=n||(typeof window<"u"?ap(window.location.pathname):"app");x.useEffect(()=>{u(e||s)},[e,s]),x.useEffect(()=>{l(t)},[t]);const m=x.useCallback(()=>a(w=>!w),[]),b=x.useCallback(w=>{l(w.target.value)},[]),g=x.useCallback(async()=>{if(!c)return t;try{const w=await ad();if(!w)return t;const C=await gM(w,c,h);return C?um(C):t}catch(w){return console.error("Failed to fetch latest description:",w),t}},[c,t,h]),p=x.useCallback(async()=>{const w=await g();l(w),m()},[g,m]),y=x.useCallback(w=>{const C=w.trim();if(C===t)return m(),!1;const A=C.length>0&&C.length<=100,E=/^[a-zA-Z0-9\s\-_.,!?()[\]{}'"]+$/.test(C);return A?E?!0:(Se.error("Description can only contain letters, numbers, spaces, and basic punctuation."),!1):(Se.error("Description must be between 1 and 100 characters."),!1)},[]),v=x.useCallback(async w=>{if(w.preventDefault(),!!y(o)){try{const C=await ad();if(!C){Se.error("Chat persistence is not available");return}if(!c){Se.error("Chat Id is not available");return}const A=d?.email;if(!A)return;await bM(C,A,c,o,h),r&&sp.set(o),Se.success("Chat description updated successfully")}catch(C){Se.error("Failed to update chat description: "+C.message)}m()}},[o,c,t,e,h,r,d?.email,y,m]),_=x.useCallback(async w=>{w.key==="Escape"&&await p()},[p]);return{editing:i,handleChange:b,handleBlur:p,handleSubmit:v,handleKeyDown:_,currentDescription:o,toggleEditMode:m}}const Ng=(t=1024)=>{const[e,r]=x.useState(window.innerWidth<t);return x.useEffect(()=>{const n=()=>r(window.innerWidth<t);return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)}},[t]),e},pv="output_data_inspection",o$=[/\bInternalError\.Algo\.DataInspectionFailed\b/i,/\bDataInspectionFailed\b/i,/\bOutput data may contain inappropriate content\b/i,/\boutput(?:\s+data)?\s+(?:may\s+contain|contains)\s+inappropriate content\b/i];function a$(t){return t instanceof Error?t.message||String(t):typeof t=="string"?t:t&&typeof t=="object"&&"message"in t?String(t.message||t):String(t??"")}function l$(t){const e=a$(t);return o$.some(r=>r.test(e))}function c$(t,e={}){const r=Number(t?.statusCode??422),n=Number.isFinite(r)&&r>=400?r:422;return{error:!0,type:pv,title:"Generation paused",message:"The model provider stopped this draft during its output safety check. Any files already written will be validated automatically.",content:"No blocked provider output was shown. If the app is incomplete, retry the same prompt or ask for a small follow-up change.",statusCode:n,isRetryable:!0,provider:e.provider||"unknown"}}function rw(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{const r=JSON.parse(e);if(r&&typeof r=="object"&&(r.error||r.message))return r}catch{}return l$(e)?c$(e):null}const u$=/\b(app|application|game|tool|dashboard|platform|software|quiz|calculator|tracker|editor|portal)\b/gi,d$=/\b(site|website|web site|webpage|web page|page|landing page|portfolio|blog|docs?|documentation|marketing page)\b/gi;function nw(t,e){const r=new RegExp(e.source,e.flags);let n=-1,s=r.exec(t);for(;s;)n=s.index,s=r.exec(t);return n}function sw(t,e="app"){const r=(t||"").toLowerCase();if(!r.trim())return e;const n=nw(r,u$),s=nw(r,d$);return n===-1&&s===-1?e:n===-1?"site":s===-1||n>=s?"app":"site"}function h$(t){return t==="site"?"site":"app"}function f$(t){return t==="site"?"Site":"App"}function p$(t){const e=t.timedOutStages.includes("install"),r=t.timedOutStages.some(n=>n==="build"||n==="typecheck");return t.syntaxPreflightPassed&&r&&!e&&t.buildIssueCount===0&&t.importIssueCount===0}const m$=3e4,Ha="Please describe the app or website you would like to create. For example: âCreate a modern website for a landscaping company with Home, Services, About, and Contact pages.â",g$=/\b(?:cloudmysite|platform|your\s+(?:server|servers|system|backend|runtime)|this\s+(?:app|platform|server|system))\b/i,b$=/\b(?:steal(?:s|ing)?|exfiltrat(?:e|es|ing)|leak|dump|reveal|bypass|disable)\b/i,v$=/\b(?:secrets?|credentials?|api\s*keys?|tokens?|auth|authentication|authorization|permissions?|billing|rate\s*limits?)\b/i,g_=/\b(?:build|create|design|develop|generate|make|need|want|launch|set\s*up|bulid|biuld|craete)\b/i,NE=/\b(?:app|application|website|web\s*site|site|landing\s*page|store|shop|portal|dashboard|portfolio|e-?commerce|marketplace|blog|booking\s*system|management\s*system|platform|game|webiste|wesbite)\b/i,y$=/\b(?:home|about|contact|services?|products?|menu|gallery|reviews?|pricing|checkout|booking|appointments?|tasks?|orders?|inventory|login|signup|register|profile|pages?|contct)\b/i,LE=/^(?:asdf(?:ghjkl|jkl)?|qwerty(?:uiop)?|zxcvbnm|hjkl|poiuytrewq)+$/i,DE=new Set(["a","about","an","and","app","application","better","biuld","build","bulid","business","company","contact","contct","create","craete","customer","customers","design","develop","for","gallery","generate","good","home","i","it","landing","login","make","management","menu","modern","my","need","nice","page","pages","platform","portal","pricing","product","products","professional","service","services","shop","signup","simple","site","something","system","the","to","use","user","users","want","web","webiste","website","wesbite","
4with","your"]);function ME(t){return t.toLowerCase().match(/[a-z][a-z'-]*/g)||[]}function _$(t){return t.length<3?!1:new Set(t).size===1?!0:t.every(r=>r.length>=3&&new Set(r).size===1)}function x$(t,e){const r=t.toLowerCase().match(/[a-z0-9]+/g)||[];if(r.length!==1)return!1;const n=r[0];if(n.length<7||g_.test(t)||NE.test(t))return!1;const s=/[a-z]/.test(n),i=/\d/.test(n),a=(n.match(/[aeiou]/g)||[]).length,o=/^(.{2,5})\1{1,}$/i.test(n);return LE.test(n)||o||s&&i&&a/n.length<.25||e.length===1&&n.length>=10&&a/n.length<.15}function OE(t){return LE.test(t)||/^(.)\1{3,}$/i.test(t)||/^(.{2,5})\1{1,}$/i.test(t)?!0:t.length<7?!1:(t.match(/[aeiou]/g)||[]).length/t.length<.15}function w$(t){const e=t.replace(/\s+/g,"");if(!e)return!1;const r=e.match(/[a-z]/gi)||[],n=ME(t);if(r.length===0&&e.length>=3||/^(.)\1{5,}$/i.test(e)||_$(n)||x$(t,n))return!0;const s=n.filter(o=>!DE.has(o));if(s.length>0&&s.every(OE))return!0;const i=e.length,a=i>0?r.length/i:0;return i>=6&&a<.25&&!g_.test(t)}function S$(t){const e=ME(t),r=e.filter(a=>!(DE.has(a)||a.length<3||OE(a))),n=g_.test(t),s=NE.test(t),i=y$.test(t);return s&&r.length>=1||n&&r.length>=2&&(i||e.length>=5)?!0:n&&i&&r.length>=1}function jE(t){const e=String(t||"").normalize("NFKC").trim();return e?w$(e)?{classification:"INVALID_GIBBERISH",reason:"The prompt is primarily repetition, random characters, numbers, punctuation, or keyboard noise."}:S$(e)?{classification:"READY",reason:"The prompt communicates an understandable app or website concept."}:{classification:null,reason:"The prompt is meaningful but requires semantic classification."}:{classification:"NEEDS_CLARIFICATION",reason:"No app or website request was provided."}}function C$(t){const e=t.trim();if(!e)return{ok:!1,reason:"Please describe what you want to build.",resolution:"qualify"};if(e.length>m$)return{ok:!1,reason:"This prompt is too long. Please shorten it and try again.",resolution:"block"};if(g$.test(e)&&b$.test(e)&&v$.test(e))return{ok:!1,reason:"Please describe the website or app you want to build, not an action against the CloudMySite platform.",resolution:"block"};const r=jE(e);return r.classification==="INVALID_GIBBERISH"?{ok:!1,reason:Ha,resolution:"block"}:r.classification==="READY"?{ok:!0}:{ok:!1,reason:"Please add the minimum details needed to understand what should be created.",resolution:"qualify"}}function A$(t){return!t.chatStarted&&t.chatMode==="build"&&!t.isNewsletterMode&&t.prompt.trim().length>0&&jE(t.prompt).classification==="INVALID_GIBBERISH"}const Lg="DELETE",E$=4;function k$(t){return t==="site"?{item:"website",items:"websites",destructiveDescription:"This permanently removes the selected website from history, synced chat records, and storage.",destructivePluralDescription:"This permanently removes the selected websites from history, synced chat records, and storage.",detailDescription:"This also deletes the saved builder workspace state for each selected website."}:t==="newsletter"?{item:"newsletter campaign",items:"newsletter campaigns",destructiveDescription:"This permanently removes the selected newsletter campaign from history, synced chat records, and storage.",destructivePluralDescription:"This permanently removes the selected newsletter campaigns from history, synced chat records, and storage.",detailDescription:"This cannot be recovered after deletion."}:{item:"app",items:"apps",destructiveDescription:"This action is irreversible. It will delete all app history, saved data, database records, objects, and the published triggers for the selected app.",destructivePluralDescription:"This action is irreversible. It will delete all app history, saved data, database records, objects, and published triggers for the selected apps.",detailDescription:"This cannot be recovered after deletion."}}function P$(t){if(!t)return"Unknown";const e=new Date(t);return Number.isNaN(e.getTime())?"Unknown":e.toLocaleString()}function T$({isOpen:t,items:e,mode:r,isDeleting:n=!1,onClose:s,onConfirm:i}){const[a,o]=x.useState(""),l=k$(r),c=l.item,u=l.items,d=e.length,h=a.trim()===Lg;x.useEffect(()=>{t||o("")},[t]);const m=x.useMemo(()=>e.slice(0,E$),[e]),b=Math.max(0,d-m.length),g=d===1?`Delete ${c}`:`Delete ${d} ${u}`,p=d===1?l.destructiveDescription:l.destructivePluralDescription,y=l.detailDescription;return f.jsx(Bl,{open:t,onOpenChange:v=>{!v&&!n&&s()},children:f.jsx(Lc,{showCloseButton:!1,className:"w-[min(92vw,640px)]",children:f.jsxs("div",{className:"p-6 bg-white dark:bg-gray-950 relative z-10",children:[f.jsx(Dc,{children:g}),f.jsx(Cd,{className:"mt-2",children:p}),f.jsx(Cd,{className:"mt-2",children:y}),f.jsxs("div",{className:"mt-5 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/40 dark:text-red-300",children:["Type ",f.jsx("span",{className:"font-semibold tracking-wide",children:Lg}
4)," to confirm this permanent deletion."]}),f.jsxs("div",{className:"mt-5 space-y-3",children:[m.map(v=>f.jsxs("div",{className:"rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-4 py-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:v.description?.trim()||"Untitled"}),f.jsxs("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:["Created: ",P$(v.timestamp)]}),f.jsxs("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary break-all",children:["ID: ",v.urlId||v.id]})]},v.id)),b>0&&f.jsxs("div",{className:"text-xs text-bolt-elements-textSecondary",children:["And ",b," more ",b===1?c:u,"."]})]}),f.jsxs("div",{className:"mt-5",children:[f.jsx("label",{className:"block text-sm font-medium text-bolt-elements-textPrimary mb-2",htmlFor:"delete-history-confirmation",children:"Confirmation"}),f.jsx("input",{id:"delete-history-confirmation",type:"text",value:a,onChange:v=>o(v.target.value),placeholder:`Type ${Lg} here`,autoComplete:"off",spellCheck:!1,className:"w-full rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background px-3 py-2 text-sm text-bolt-elements-textPrimary focus:outline-none focus:ring-1 focus:ring-red-400",disabled:n})]}),f.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[f.jsx(En,{variant:"outline",onClick:s,disabled:n,children:"Cancel"}),f.jsx(En,{variant:"destructive",onClick:i,disabled:!h||n,children:n?"Deleting...":d===1?`Delete ${c}`:`Delete ${u}`})]})]})})})}const $E=x.forwardRef(({tooltip:t,children:e,sideOffset:r=5,className:n="",arrowClassName:s="",tooltipStyle:i={},position:a="top",maxWidth:o=250,delay:l=0},c)=>f.jsx(t_,{children:f.jsxs(z1,{delayDuration:l,children:[f.jsx(V1,{asChild:!0,children:e}),f.jsx(WD,{children:f.jsxs(G1,{side:a,className:` 5 z-[2000] 6 px-2.5 7 py-1.5 8 max-h-[300px] 9 select-none 10 rounded-md 11 bg-bolt-elements-background-depth-3 12 text-bolt-elements-textPrimary 13 text-sm 14 leading-tight 15 shadow-lg 16 animate-in 17 fade-in-0 18 zoom-in-95 19 data-[state=closed]:animate-out 20 data-[state=closed]:fade-out-0 21 data-[state=closed]:zoom-out-95 22 ${n} 23 `,sideOffset:r,style:{maxWidth:o,...i},children:[f.jsx("div",{className:"break-words",children:t}),f.jsx(q1,{className:` 24 fill-bolt-elements-background-depth-3 25 ${s} 26 `,width:12,height:6})]})})]})}));function iw({content:t,children:e,side:r="top",align:n="center",delayDuration:s=300,className:i}){return f.jsx(t_,{children:f.jsxs(z1,{delayDuration:s,children:[f.jsx(V1,{asChild:!0,children:e}),f.jsxs(G1,{side:r,align:n,className:ue("z-50 overflow-hidden rounded-md bg-bolt-elements-background-depth-3 dark:bg-bolt-elements-background-depth-4 px-3 py-1.5 text-xs text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",i),sideOffset:5,children:[t,f.jsx(q1,{className:"fill-bolt-elements-background-depth-3 dark:fill-bolt-elements-background-depth-4"})]})]})})}function R$({item:t,onDelete:e,onDuplicate:r,exportChat:n,selectionMode:s=!1,isSelected:i=!1,onToggleSelection:a,mode:o="app"}){const l=rE(),c=am(l.pathname,l.search),u=t.urlId||t.id,h=(o==="site"?l.pathname.startsWith("/builder"):o==="newsletter"?l.pathname.startsWith("/newsletter"):l.pathname.startsWith("/app")||l.pathname.startsWith("/apps")||l.pathname.startsWith("/chat/"))&&(c===t.urlId||c===t.id),m=um(t),{editing:b,handleChange:g,handleBlur:p,handleSubmit:y,handleKeyDown:v,currentDescription:_,toggleEditMode:w}=i$({initialDescription:m,customChatId:t.id,syncWithGlobalStore:h,mode:o}),C=x.useCallback(S=>{s&&(S.preventDefault(),S.stopPropagation(),console.log("Item clicked in selection mode:",t.id),a?.(t.id))},[s,t.id,a]),A=x.useCallback(()=>{console.log("Checkbox changed for item:",t.id),a?.(t.id)},[t.id,a]),E=x.useCallback(S=>{S.preventDefault(),S.stopPropagation(),console.log("Delete button clicked for item:",t.id),e&&e(S)},[e,t.id]);return f.jsxs("div",{className:ue("group rounded-lg text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50/80 dark:hover:bg-gray-800/30 overflow-hidden flex justify-between items-center px-3 py-2 transition-colors",{"text-gray-900 dark:text-white bg-gray-50/80 dark:bg-gray-800/30":h},{"cursor-pointer":s}),onClick:s?C:void 0,children:[s&&f.jsx("div",{className:"flex items-center mr-2",onClick:S=>S.stopPropagation(),children:f.jsx(op,{id:`select-${t.id}`,checked:i,onCheckedChange:A,className:"h-4 w-4"})}),b?f.jsxs("form",{onSubmit:y,className:"flex-1 flex items-center gap-2",children:[f.jsx("input",{type:"text",className:"flex-1 bg-white dark:bg-gray-900 text-gray-900 dark:text-white rounded-md px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-800 focus:outline-none focus:ring-1 focus:ring-purple-500/50",autoFocus:!0,value:_,onCh
26ange:g,onBlur:p,onKeyDown:v}),f.jsx("button",{type:"submit",className:"i-ph:check h-4 w-4 text-gray-500 hover:text-purple-500 transition-colors",onMouseDown:y})]}):f.jsxs("a",{href:ih(o,u),className:"flex w-full relative truncate block",onClick:s?C:void 0,children:[f.jsx($E,{tooltip:_,children:f.jsx("span",{className:"truncate pr-24",children:_})}),f.jsx("div",{className:ue("absolute right-0 top-0 bottom-0 flex items-center bg-transparent px-2 transition-colors"),children:f.jsxs("div",{className:"flex items-center gap-2.5 text-gray-400 dark:text-gray-500 opacity-0 group-hover:opacity-100 transition-opacity",children:[r&&f.jsx(Dg,{toolTipContent:"Duplicate",icon:"i-ph:copy h-4 w-4",onClick:S=>{S.preventDefault(),r?.(t.id)}}),f.jsx(Dg,{toolTipContent:"Rename",icon:"i-ph:pencil-fill h-4 w-4",onClick:S=>{S.preventDefault(),w()}}),f.jsx(Dg,{toolTipContent:"Delete",icon:"i-ph:trash h-4 w-4",className:"hover:text-red-500 dark:hover:text-red-400",onClick:E})]})})]})]})}const Dg=x.forwardRef(({toolTipContent:t,icon:e,className:r,onClick:n},s)=>f.jsx($E,{tooltip:t,position:"bottom",sideOffset:4,children:f.jsx("button",{ref:s,type:"button",className:`text-gray-400 dark:text-gray-500 hover:text-purple-500 dark:hover:text-purple-400 transition-colors ${e} ${r||""}`,onClick:n})}));function I$(t,e){const r=ai(t);return isNaN(e)?el(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function ec(t,e){const r=im(),n=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=ai(t),i=s.getDay(),a=(i<n?7:0)+i-n;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function hp(t){return ec(t,{weekStartsOn:1})}function BE(t){const e=ai(t),r=e.getFullYear(),n=el(t,0);n.setFullYear(r+1,0,4),n.setHours(0,0,0,0);const s=hp(n),i=el(t,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const a=hp(i);return e.getTime()>=s.getTime()?r+1:e.getTime()>=a.getTime()?r:r-1}function fp(t){const e=ai(t);return e.setHours(0,0,0,0),e}function N$(t,e){const r=fp(t),n=fp(e),s=+r-ax(r),i=+n-ax(n);return Math.round((s-i)/HD)}function L$(t){const e=BE(t),r=el(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),hp(r)}function FE(t,e){const r=fp(t),n=fp(e);return+r==+n}function D$(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function M$(t){if(!D$(t)&&typeof t!="number")return!1;const e=ai(t);return!isNaN(Number(e))}function O$(t){const e=ai(t),r=el(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function j$(t){const e=ai(t);return N$(e,O$(e))+1}function $$(t){const e=ai(t),r=+hp(e)-+L$(e);return Math.round(r/K1)+1}function WE(t,e){const r=ai(t),n=r.getFullYear(),s=im(),i=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,a=el(t,0);a.setFullYear(n+1,0,i),a.setHours(0,0,0,0);const o=ec(a,e),l=el(t,0);l.setFullYear(n,0,i),l.setHours(0,0,0,0);const c=ec(l,e);return r.getTime()>=o.getTime()?n+1:r.getTime()>=c.getTime()?n:n-1}function B$(t,e){const r=im(),n=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,s=WE(t,e),i=el(t,0);return i.setFullYear(s,0,n),i.setHours(0,0,0,0),ec(i,e)}function F$(t,e){const r=ai(t),n=+ec(r,e)-+B$(r,e);return Math.round(n/K1)+1}function Hr(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const Ba={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return Hr(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):Hr(r+1,2)},d(t,e){return Hr(t.getDate(),e.length)},a(t,e){const r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(t,e){return Hr(t.getHours()%12||12,e.length)},H(t,e){return Hr(t.getHours(),e.length)},m(t,e){return Hr(t.getMinutes(),e.length)},s(t,e){return Hr(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),s=Math.trunc(n*Math.pow(10,r-3));return Hr(s,e.length)}},Sc={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ow={G:function(t,e,r){const n=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});case"GGGG":default:return r.era(n,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){const n=t.getFullYear(),s=n>0?n:1-n;return r.ordinalNumber(s,{unit:"year"})}return Ba.y(t,e)},Y:function(t,e,r,n){const s=WE(t,n),i=s>0?s:1-s;if(e==="YY"){const a=i%100;return Hr(a,2)}return e==="Yo"?r.ordinalNumber(i,{unit:"year"}):Hr(i,e.length)},R:function(t,e){const r=BE(t);return Hr(r,e.length)},u:function(t,e){const r=t.getFullYear();return Hr(r,e.length)},Q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return Hr(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return Hr(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(t,e,r){const n=t.getMonth();switch(e){case"M":case"MM":return Ba.M(t,e);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(t,e,r){const n=t.getMonth();switch(e){case"L":return String(n+1);case"LL":return Hr(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(t,e,r,n){const s=F$(t,n);return e==="wo"?r.ordinalNumber(s,{unit:"week"}):Hr(s,e.length)},I:function(t,e,r){const n=$$(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):Hr(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Ba.d(t,e)},D:function(t,e,r){const n=j$(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Hr(n,e.length)},E:function(t,e,r){const n=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});case"EEEE":default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(t,e,r,n){const s=t.getDay(),i=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return Hr(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(s,{width:"short",context:"formatting"});case"eeee":default:return r.day(s,{width:"wide",context:"formatting"})}},c:function(t,e,r,n){const s=t.getDay(),i=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return Hr(i,e.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(s,{width:"narrow",context:"standalone"});case"cccccc":return r.day(s,{width:"short",context:"standalone"});case"cccc":default:return r.day(s,{width:"wide",context:"standalone"})}},i:function(t,e,r){const n=t.getDay(),s=n===0?7:n;switch(e){case"i":return String(s);case"ii":return Hr(s,e.length);case"io":return r.ordinalNumber(s,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});case"iiii":default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(t,e,r){const s=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(t,e,r){const n=t.getHours();let s;switch(n===12?s=Sc.noon:n===0?s=Sc.midnight:s=n/12>
vendor: 4,314 bytes, line 26
26=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(t,e,r){const n=t.getHours();let s;switch(n>=17?s=Sc.evening:n>=12?s=Sc.afternoon:n>=4?s=Sc.morning:s=Sc.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let n=t.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return Ba.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Ba.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Hr(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):Hr(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Ba.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Ba.s(t,e)},S:function(t,e){return Ba.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return lw(n);case"XXXX":case"XX":return Il(n);case"XXXXX":case"XXX":default:return Il(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return lw(n);case"xxxx":case"xx":return Il(n);case"xxxxx":case"xxx":default:return Il(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+aw(n,":");case"OOOO":default:return"GMT"+Il(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+aw(n,":");case"zzzz":default:return"GMT"+Il(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return Hr(n,e.length)},T:function(t,e,r){const n=t.getTime();return Hr(n,e.length)}};function aw(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),s=Math.trunc(n/60),i=n%60;return i===0?r+String(s):r+String(s)+e+Hr(i,2)}function lw(t,e){return t%60===0?(t>0?"-":"+")+Hr(Math.abs(t)/60,2):Il(t,e)}function Il(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),s=Hr(Math.trunc(n/60),2),i=Hr(n%60,2);return r+s+e+i}const cw=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},HE=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},W$=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],s=r[2];if(!s)return cw(t,e);let i;switch(n){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",cw(n,e)).replace("{{time}}",HE(s,e))},H$={p:HE,P:W$},U$=/^D+$/,z$=/^Y+$/,V$=["D","DD","YY","YYYY"];function G$(t){return U$.test(t)}function q$(t){return z$.test(t)}function K$(t,e,r){const n=Y$(t,e,r);if(console.warn(n),V$.includes(t))throw new RangeError(n)}function Y$(t,e,r){const n=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const X$=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,J$=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Q$=/^'([^]*?)'?$/,Z$=/''/g,eB=/[a-zA-Z]/;function Mg(t,e,r){const n=im(),s=n.locale??UD,i=n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=n.weekStartsOn??n.locale?.options?.weekStartsOn??0,o=ai(t);if(!M$(o))throw new RangeError("Invalid time value");let l=e.match(J$).map(u=>{const d=u[0];if(d==="p"||d==="P"){const h=H$[d];return h(u,s.formatLong)}return u}).join("").match(X$).map(u=>{if(u==="''")return{isToken:!1,value:"'"};const d=u[0];if(d==="'")return{isToken:!1,value:tB(u)};if(ow[d])return{isToken:!0,value:u};
26if(d.match(eB))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:u}});s.localize.preprocessor&&(l=s.localize.preprocessor(o,l));const c={firstWeekContainsDate:i,weekStartsOn:a,locale:s};return l.map(u=>{if(!u.isToken)return u.value;const d=u.value;(q$(d)||G$(d))&&K$(d,e,String(t));const h=ow[d[0]];return h(o,d,s.localize,c)}).join("")}function tB(t){const e=t.match(Q$);return e?e[1].replace(Z$,"'"):t}function rB(t,e){const r=ai(t),n=ai(e);return r.getTime()>n.getTime()}function nB(t,e,r){const n=ec(t,r),s=ec(e,r);return+n==+s}function sB(t,e){const r=ai(t),n=ai(e);return r.getFullYear()===n.getFullYear()}function iB(t,e){return nB(t,om(t),e)}function oB(t){return sB(t,om(t))}function aB(t){return FE(t,om(t))}function UE(t,e){return I$(t,-e)}function lB(t){return FE(t,UE(om(t),1))}function cB(t){const e=t.toSorted((s,i)=>Date.parse(i.timestamp)-Date.parse(s.timestamp)),r={},n=[];return e.forEach(s=>{const i=uB(new Date(s.timestamp));if(i in r)r[i].items.push(s);else{const a={category:i,items:[s]};r[i]=a,n.push(a)}}),n}function uB(t){if(aB(t))return"Today";if(lB(t))return"Yesterday";if(iB(t))return Mg(t,"EEE");const e=UE(new Date,30);return rB(t,e)?"Past 30 Days":oB(t)?Mg(t,"LLL"):Mg(t,"LLL yyyy")}function dB({items:t=[],searchFields:e,debounceMs:r=300}){const[n,s]=x.useState(""),i=x.useMemo(()=>e||[],[e]),a=x.useCallback(sh(s,r),[]),o=x.useCallback(c=>{a(c.target.value)},[a]),l=x.useMemo(()=>{if(!n.trim())return t;const c=n.toLowerCase();return t.filter(u=>i.some(d=>{const h=u[d];return typeof h=="string"?h.toLowerCase().includes(c):!1}))},[t,i,n]);return{searchQuery:n,filteredItems:l,handleSearchChange:o}}function hB(t){return t.level==="blocked"?{card:"border-rose-200 bg-rose-50 text-rose-950",progress:"bg-rose-500",text:"text-rose-700",link:"text-rose-700 hover:text-rose-800"}:t.level==="warning"?{card:"border-amber-200 bg-amber-50 text-amber-950",progress:"bg-amber-500",text:"text-amber-700",link:"text-amber-700 hover:text-amber-800"}:t.level==="notice"?{card:"border-sky-200 bg-sky-50 text-slate-900",progress:"bg-sky-500",text:"text-sky-700",link:"text-sky-700 hover:text-sky-800"}:{card:"border-gray-200 bg-gray-50/90 text-gray-950 dark:border-gray-800 dark:bg-gray-900/70 dark:text-white",progress:"bg-emerald-500",text:"text-gray-600 dark:text-gray-300",link:"text-purple-600 hover:text-purple-700 dark:text-purple-300 dark:hover:text-purple-200"}}function fB(){return f.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50/80 p-3 dark:border-gray-800 dark:bg-gray-900/60",children:[f.jsx("div",{className:"h-3 w-20 animate-pulse rounded bg-gray-200 dark:bg-gray-700"}),f.jsx("div",{className:"mt-3 h-7 w-28 animate-pulse rounded bg-gray-200 dark:bg-gray-700"}),f.jsx("div",{className:"mt-3 h-2 w-full animate-pulse rounded-full bg-gray-200 dark:bg-gray-700"})]})}function pB(t){const e=t.summary||null;if(t.loading&&!e)return f.jsx(fB,{});if(!e)return null;const r=hB(e.threshold);return f.jsxs("div",{className:ue("rounded-xl border p-3 shadow-sm",r.card),children:[f.jsxs("div",{className:"flex items-start justify-between gap-3",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] opacity-70",children:"AI Tokens"}),f.jsx("div",{className:"mt-1 truncate text-sm font-semibold",children:e.planName})]}),f.jsx("a",{href:"/usage",className:ue("text-xs font-semibold transition-colors",r.link),children:"View usage"})]}),f.jsxs("div",{className:"mt-3",children:[f.jsx("div",{className:"text-2xl font-semibold leading-none",children:Yl(e.monthlyTokensRemaining)}),f.jsx("div",{className:ue("mt-1 text-xs",r.text),children:"remaining this billing cycle"})]}),f.jsxs("div",{className:"mt-3",children:[f.jsxs("div",{className:"flex items-center justify-between text-[11px] opacity-70",children:[f.jsx("span",{children:aE(e.monthlyTokensUsed,e.monthlyTokenLimit)}),f.jsx("span",{children:n_(e.threshold.percent)})]}),f.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-black/10 dark:bg-white/10",children:f.jsx("div",{className:ue("h-full rounded-full transition-[width] duration-300",r.progress),style:{width:`${e.threshold.percent}%`}})})]}),e.threshold.level!=="healthy"&&f.jsxs("div",{className:"mt-3 space-y-2",children:[f.jsx("div",{className:ue("text-xs font-medium",r.text),children:e.threshold.message}),f.jsx("a",{href:"/pricing",className:"inline-flex items-center rounded-lg bg-black px-3 py-1.5 text-xs font-semibold text-white transition-colors hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200",children:e.threshold.upgradeLabel||"Upgrade"})]})]})}const mB={closed:{opacity:0,visibility:"hidden",left:"-340px",transition:{duration:.2,ease:Ds}},open:{opacity:1,visibility:"initial",left:0,transition:{duration:.2,ease:Ds}}};function gB(){const[t,e]=x.useState(new Date);return x.useEffect(()=>{const r=setInterval(()=>{e(new Date)},6e4);return()=>clearInterval(r)},[]),f.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-sm text-gray-600 dark:text-gray-400 border-b border-gray-100 dark:border-gray-800/50",children:[f.jsx("div",{className:"h-4 w-4 i-ph:clock opacity-80"}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("span",{children:t.toLocaleDateString()}),f.jsx("span",{children:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}function bB(t,e){const r=Array.isArray(t.messages)?t.messages:[],n=um({...t,messages:r}),s=zE(e);return{...t,mode:e,messages:r,messageCount:r.length,urlId:t.urlId||t.id,description:n==="My Workspace"?s.fallbackTitle:n}}function zE(t){return t==="site"?{item:"site",itemTitle:"Site",items:"sites",itemsTitle:"Sites",fallbackTitle:"My Website",createLabel:"Create new website",newItemHref:"/builder-app",usageProductType:"genie-builder"}:t==="newsletter"?{item:"newsletter campaign",itemTitle:"Newsletter Campaign",items:"newsletter campaigns",itemsTitle:"Newsletter Campaigns",fallbackTitle:"My Newsletter",createLabel:"+
26New Newsletter",newItemHref:"/newsletter",usageProductType:"genie ai"}:{item:"app",itemTitle:"App",items:"apps",itemsTitle:"Apps",fallbackTitle:"My App",createLabel:"Build a new app",newItemHref:"/app",usageProductType:"genie ai"}}function mv(t){const e=String(t??"").trim().toLowerCase();return e==="saved_to_newsletter"||e==="saved to newsletter"?"saved_to_newsletter":e==="published"?"published":"draft"}function vB(t){const e=t.metadata;return e?.newsletterStatus?mv(e.newsletterStatus):e?.historyStatusOverride==="published"?"published":e?.newsletterCampaignSave?.campaignId?"saved_to_newsletter":mv(t.status)}function yB(t){return t==="saved_to_newsletter"?"saved to Newsletter":t}function _B(t){return t.metadata?.newsletterPublicationName||t.publicationName||t.publication_name||""}function xB(t){const e=Date.parse(String(t??"").trim());return Number.isFinite(e)?new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}).format(new Date(e)):""}function wB(t){const e=t.metadata?.newsletterContext,r=String(e?.workspace_id||t.workspaceId||"").trim().toLowerCase(),n=String(e?.publication_id||t.publicationId||"").trim().toLowerCase()||r;return{workspaceId:r,publicationId:n}}function uw(t,e){const r=String(e?.workspace_id||"").trim().toLowerCase(),n=String(e?.publication_id||"").trim().toLowerCase()||r;if(!r||!n)return!1;const s=wB(t);return s.workspaceId===r&&s.publicationId===n}function SB(t){const e=String(t?.workspace_id||"").trim(),r=String(t?.publication_id||"").trim();if(!e||!r)return"/newsletter";const n=new URLSearchParams({mode:"newsletter",workspace_id:e,publication_id:r}),s=String(t?.return_url||"").trim(),i=String(t?.handoff_token||"").trim();return s&&n.set("return_url",s),i&&n.set("handoff_token",i),`/newsletter?${n.toString()}`}function CB(t,e){if(!t||typeof t!="object")return null;const r=t,n=String(r.chatId||r.chat_id||r.id||"").trim();if(!n)return null;const s=String(r.timestamp||r.updatedAt||r.updated_at||r.createdAt||"").trim(),i=r.metadata&&typeof r.metadata=="object"?r.metadata:void 0,a=String(r.title||r.workspaceTitle||r.description||i?.workspaceTitle||"Newsletter Draft").trim();return{id:n,urlId:String(r.urlId||r.url_id||r.appId||n).trim(),description:a,messages:[],messageCount:0,timestamp:s||new Date().toISOString(),metadata:i,userEmail:String(r.userEmail||r.user_email||e).trim()||e,mode:"newsletter",status:mv(r.status),publicationName:r.publicationName||r.publication_name||null,workspaceId:r.workspaceId||r.workspace_id||i?.newsletterContext?.workspace_id||null,publicationId:r.publicationId||r.publication_id||i?.newsletterContext?.publication_id||null}}function AB(t,e){const r=new Map,n=s=>{const i=String(s.id||s.urlId||"").trim(),a=String(s.urlId||s.id||"").trim();if(!i)return;const o=r.get(i)||r.get(a);if(!o){r.set(i,s);return}const l=Date.parse(s.timestamp||""),c=Date.parse(o.timestamp||""),d=Number.isFinite(l)&&(!Number.isFinite(c)||l>=c)?s:o,h=(o.messages?.length||0)>0?o.messages:s.messages;r.set(String(o.id||i),{...o,...d,messages:h,messageCount:h.length,metadata:{...o.metadata||{},...d.metadata||{}}})};return t.forEach(n),e.forEach(n),[...r.values()].sort((s,i)=>Date.parse(i.timestamp||"")-Date.parse(s.timestamp||""))}function EB({item:t,onDelete:e}){const r=t.urlId||t.id,n=um(t),s=vB(t),i=_B(t),a=xB(t.timestamp);return f.jsxs("div",{className:"group rounded-lg px-3 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50/80 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800/30 dark:hover:text-white",children:[f.jsxs("a",{href:ih("newsletter",r),className:"block min-w-0",children:[f.jsxs("div",{className:"flex items-start justify-between gap-2",children:[f.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:n}),f.jsx("span",{className:ue("shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide",s==="published"?"bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300":s==="saved_to_newsletter"?"bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-300":"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300"),children:yB(s)})]}),f.jsxs("div",{className:"mt-1 flex min-w-0 items-center justify-between gap-2 text-xs text-gray-500 dark:text-gray-400",children:[f.jsx("span",{className:"min-w-0 truncate",children:i||"Newsletter publication"}),a?f.jsx("span",{className:"shrink-0",children:a}):null]})]}),f.jsx("div",{className:"mt-2 flex justify-end opacity-0 transition-opacity group-hover:opacity-100",children:f.jsx("button",{type:"button",className:"i-ph:trash h-4 w-4 text-gray-400 transition-colors hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400",title:"Delete","aria-label":"Delete newsletter draft",onClick:e})})]})}const kB=()=>{const{duplicateCurrentChat:t,exportChat:e}=W1(),r=nE(),n=x.useRef(null),s=x.useRef(!1),i=x.useRef(!1),[a,o]=x.useState([]),[l,c]=x.useState(!1),[u,d]=x.useState(!1),[h,m]=x.useState(null),[b,g]=x.use
26State(!1),[p,y]=x.useState(),v=We(Y1),_=We(On),[w,C]=x.useState(!1),[A,E]=x.useState([]),[S,k]=x.useState([]),[O,T]=x.useState(!1),[R,N]=x.useState(!1),M=rE(),B=ap(M.pathname),U=am(M.pathname,M.search),X=We(ip),oe=x.useMemo(()=>B==="newsletter"?lp({pathname:M.pathname,search:M.search},X?.newsletterContext):null,[X?.newsletterContext,B,M.pathname,M.search]),L=!!(oe?.workspace_id&&oe.publication_id),F=L?`${oe?.workspace_id||""}:${oe?.publication_id||""}`:"",V=g2({workspaceId:U,returnTo:`${M.pathname}${M.search}`}),Z=M.pathname.includes("/builder")||M.pathname==="/"||M.pathname==="/app"||M.pathname==="/newsletter"||M.pathname==="/apps"||M.pathname.startsWith("/app/")||M.pathname.startsWith("/newsletter/")||M.pathname.startsWith("/apps/")||M.pathname.startsWith("/chat/"),K=zE(B),ie=K.item,se=K.items,fe=K.createLabel,Y=B==="newsletter"?SB(oe?.newsletterContext||null):K.newItemHref,I=K.usageProductType,{summary:z,loading:q}=lE(I,{details:!1,enabled:!!_?.email}),{filteredItems:ae,handleSearchChange:ee}=dB({items:a,searchFields:["description"]});x.useEffect(()=>{let be=!1;return(async()=>{const Ne=await ad();be||y(Ne)})(),()=>{be=!0}},[]);const le=x.useCallback(async()=>{const be=_?.email;if(!be){o([]);return}const Te=p??await ad();if(!Te){o([]);return}Te!==p&&y(Te);try{let Fe=(await sE({db:Te,userEmail:be,requestedModes:[B]}))[B].items.filter(Fr=>iE(Fr)).map(Fr=>bB(Fr,B));if(B==="newsletter"){if(!L){o([]);return}Fe=Fe.filter(Yt=>uw(Yt,oe?.newsletterContext||null));const[Fr,Jr]=await Promise.all([vM(oe?.workspace_id,oe?.publication_id).catch(Yt=>(console.warn("[Menu] Failed to load scoped newsletter history.",{error:Yt instanceof Error?Yt.message:String(Yt)}),[])),yM(oe?.workspace_id,oe?.publication_id).catch(Yt=>(console.warn("[Menu] Failed to load scoped newsletter campaigns.",{error:Yt instanceof Error?Yt.message:String(Yt)}),[]))]),Dt=[...Array.isArray(Fr)?Fr:[],...Array.isArray(Jr)?Jr:[]].map(Yt=>CB(Yt,be)).filter(Yt=>!!Yt).filter(Yt=>uw(Yt,oe?.newsletterContext||null));Fe=AB(Fe,Dt)}o(Fe)}catch(Ne){Se.error(Ne instanceof Error?Ne.message:String(Ne))}},[oe,_?.email,p,L,B,F]),ve=x.useCallback(async be=>{const Te=p??await ad();if(!Te)throw new Error("Database not available");await o2({db:Te,item:be,historyMode:B,userEmail:_?.email})},[_?.email,B,p]),ye=x.useCallback(be=>{be.length!==0&&(k(be),T(!0))},[]),Ae=x.useCallback(()=>{R||(T(!1),k([]))},[R]),we=x.useCallback(async be=>{if(be.length===0)return;console.log(`Starting delete for ${be.length} chats`,be.map(Yt=>Yt.id));let Te=0;const Ne=[],Fe=F1.get();let Fr=!1;for(const Yt of be)try{await ve(Yt),Te++,Yt.id===Fe&&(Fr=!0)}catch(Os){console.error(`Error deleting chat ${Yt.id}
26:`,Os),Ne.push(Yt.description||Yt.id)}await le();const Jr=new Set(be.map(Yt=>Yt.id)),Dt=A.filter(Yt=>!Jr.has(Yt));E(Dt),w&&Dt.length===0&&C(!1),Ne.length===0?Se.success(be.length===1?`${K.itemTitle} deleted successfully`:`${Te} ${se} deleted successfully`,{autoClose:3500}):Te>0?Se.warning(`Deleted ${Te} of ${be.length} ${se}. ${Ne.length} failed.`,{autoClose:5e3}):Se.error(`Failed to delete ${be.length===1?ie:se}.`,{autoClose:4e3}),Fr&&(console.log("Navigating away from deleted chat"),window.location.href=ih(B))},[ve,B,ie,se,le,K.itemTitle,A,w]),pe=x.useCallback(async()=>{if(!(R||S.length===0)){N(!0);try{await we(S),T(!1),k([])}catch(be){console.error("Failed to delete history items:",be),Se.error("Failed to delete selected history items.",{autoClose:4e3})}finally{N(!1)}}},[R,we,S]),Ye=x.useCallback((be,Te)=>{be.preventDefault(),be.stopPropagation(),ye([Te])},[ye]),ft=()=>{C(!w),w&&E([])},pt=x.useCallback(be=>{E(Te=>{const Ne=Te.includes(be)?Te.filter(Fe=>Fe!==be):[...Te,be];return console.log("Selected items updated:",Ne),Ne})},[]),Lt=x.useCallback(()=>{if(A.length===0){Se.info(`Select at least one ${ie} to delete`);return}const be=a.filter(Ne=>A.includes(Ne.id)).map(Ne=>Ne.id);if(be.length===0){Se.error(`Could not find selected ${se}`);return}const Te=a.filter(Ne=>be.includes(Ne.id));ye(Te)},[A,a,ie,se,ye]),nt=x.useCallback(()=>{const be=ae.map(Te=>Te.id);E(Te=>{if(be.length>0&&be.every(Fe=>Te.includes(Fe))){const Fe=Te.filter(Fr=>!be.includes(Fr));return console.log("Deselecting all filtered items. New selection:",Fe),Fe}else{const Fe=[...new Set([...Te,...be])];return console.log("Selecting all filtered items. New selection:",Fe),Fe}})},[ae]);x.useEffect(()=>{l&&le()},[l,le]),x.useEffect(()=>{!l&&w&&console.log("Sidebar closed, preserving selection state")},[l,w]);const xt=x.useCallback(()=>{const be=window.sessionStorage.getItem("cms:pending-settings-tab");return be?(window.sessionStorage.removeItem("cms:pending-settings-tab"),be):null},[]),ct=x.useCallback((be=null)=>{s.current=!0,m(be),c(Te=>(i.current=Te,!0)),d(!0)},[]);x.useEffect(()=>{const be=()=>{c(Fr=>!Fr)},Te=()=>{c(!0)},Ne=()=>{ct(xt())},Fe=()=>{B==="newsletter"&&le()};return window.addEventListener("cms:toggle-history-menu",be),window.addEventListener("cms:open-history-menu",Te),window.addEventListener("cms:open-settings-panel",Ne),window.addEventListener("cms:newsletter-history-updated",Fe),()=>{window.removeEventListener("cms:toggle-history-menu",be),window.removeEventListener("cms:open-history-menu",Te),window.removeEventListener("cms:open-settings-panel",Ne),window.removeEventListener("cms:newsletter-history-updated",Fe)}},[xt,B,le,ct]),x.useEffect(()=>{const be=window.sessionStorage.getItem("cms:pending-menu-event");if(be){if(window.sessionStorage.removeItem("cms:pending-menu-event"),be==="cms:toggle-history-menu"||be==="cms:open-history-menu"){c(!0);return}be==="cms:open-settings-panel"&&ct(xt())}},[xt,ct]),x.useEffect(()=>{const be=new URLSearchParams(M.search);if(!(be.get(Cx)===p2&&be.get(Ax)===m2))return;const Ne=be.get(Ex),Fe=be.get(kx);ct("connection"),Ne==="success"?Se.success(Fe||"Connected Google Drive successfully."):Ne==="error"&&Se.error(Fe||"Unable to connect Google Drive."),be.delete(Cx),be.delete(Ax),be.delete(Ex),be.delete(kx),r({pathname:M.pathname,search:be.toString()?`?${be.toString()}`:""},{replace:!0})},[M.pathname,M.search,r,ct]);const _r=async()=>{await tE()||window.location.replace("/")},ht=async be=>{await t(be),le()},Pe=()=>{d(!1),m(null),s.current&&(i.current||c(!1),s.current=!1,i.current=!1)};return f.jsxs(f.Fragment,{children:[f.jsx(ar.div,{ref:n,initial:"closed",animate:l?"open":"closed",variants:mB,style:{width:"340px"},className:ue("flex selection-accent flex-col side-menu fixed rounded-r-2xl","bg-white dark:bg-gray-950 border-r border-bolt-elements-borderColor","shadow-sm text-sm",u?"z-40":"z-sidebar",{"top-0 h-full":!Z,"top-2 h-[calc(100%-1rem)] rounded-2xl":Z}),children:f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"h-12 flex items-center justify-between px-4 border-b border-gray-100 dark:border-gray-800/50 bg-gray-50/50 dark:bg-gray-900/50 rounded-tr-2xl",children:[f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("button",{onClick:()=>c(!1),className:"flex items-center justify-center w-7 h-7 rounded-md hover:bg-gray-200 dark:hover:bg-gray-800 transition-colors text-gray-600 dark:text-gray-300","aria-label":"Collapse history",title:"Collapse history",children:f.jsx("span",{className:"i-ph:caret-left-bold h-4 w-4"})})}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("div",{className:"flex flex-col items-end",children:[f.jsx("span",{className:"font-medium text-sm text-gray-900 dark:text-white truncate",children:_?.username||v?.username||"Guest User"}),_?.email&&f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:_.email})]}),_&&f.jsx("button",{onClick:_r,className:"flex items-center justify-center w-6 h-6 bg-black rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors","aria-label":"Logout",title:"Logout",children:f.jsx("div",{className:"i-ph:sign-out text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"})}),f.jsx("div",{className:"flex items-center justify-center w-[32px] h-[32px] overflow-hidden bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-500 rounded-full shrink-0",children:v?.avatar?f.jsx("img",{src:v.avatar,alt:_?.username||v?.username||"User",className:"w-full h-full object-cover",loading:"eager",decoding:"sync"}):f.jsx("div",{className:"i-ph:user-fill text-lg"})})]})]}),f.jsx(gB,{}),f.jsxs("div",{className:"flex-1 flex flex-col h-full w-full overflow-hidden",children:[f.jsxs("div",{className:"p-4 space-y-3",children:[f.jsx(pB,{summary:z,loading:q}),f.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[f.jsxs("a",{href:Y,className:"flex gap-2 items-center justify-center bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dar
26k:hover:bg-purple-500/20 rounded-lg px-4 py-2 transition-colors",children:[f.jsx("span",{className:"inline-block i-ph:plus-circle h-4 w-4"}),f.jsx("span",{className:"text-sm font-medium",children:fe})]}),f.jsxs("button",{onClick:()=>g(!0),className:"flex gap-2 items-center justify-center rounded-lg px-4 py-2 transition-colors bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-500/20 border border-amber-200 dark:border-amber-800",children:[f.jsx("span",{className:"i-ph:magic-wand h-4 w-4"}),f.jsx("span",{className:"text-sm font-medium",children:"Generate image"})]})]}),B!=="newsletter"&&f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:()=>r(a2(B==="site"?"websites":"apps")),className:"flex gap-1 items-center rounded-lg px-3 py-2 transition-colors bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-300 hover:bg-blue-100 dark:hover:bg-blue-500/20 border border-blue-200 dark:border-blue-800",title:"View as cards","aria-label":"View history as cards",children:f.jsx("span",{className:"i-ph:grid-four h-4 w-4"})}),f.jsx("button",{onClick:ft,className:ue("flex gap-1 items-center rounded-lg px-3 py-2 transition-colors",w?"bg-purple-600 dark:bg-purple-500 text-white border border-purple-700 dark:border-purple-600":"bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-700"),"aria-label":w?"Exit selection mode":"Enter selection mode",children:f.jsx("span",{className:w?"i-ph:x h-4 w-4":"i-ph:check-square h-4 w-4"})})]}),f.jsxs("div",{className:"relative w-full",children:[f.jsx("div",{className:"absolute left-3 top-1/2 -translate-y-1/2",children:f.jsx("span",{className:"i-ph:magnifying-glass h-4 w-4 text-gray-400 dark:text-gray-500"})}),f.jsx("input",{className:"w-full bg-gray-50 dark:bg-gray-900 relative pl-9 pr-3 py-2 rounded-lg focus:outline-none focus:ring-1 focus:ring-purple-500/50 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-500 border border-gray-200 dark:border-gray-800",type:"search",placeholder:`Search ${se}...`,onChange:ee,"aria-label":`Search ${se}`})]})]}),f.jsxs("div",{className:"flex items-center justify-between text-sm px-4 py-2",children:[f.jsx("div",{className:"font-medium text-gray-600 dark:text-gray-400",children:B==="newsletter"?"Newsletter":`Your ${se[0].toUpperCase()}${se.slice(1)}`}),w&&B!=="newsletter"&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(En,{variant:"ghost",size:"sm",onClick:nt,children:A.length===ae.length?"Deselect all":"Select all"}),f.jsx(En,{variant:"destructive",size:"sm",onClick:Lt,disabled:A.length===0,children:"Delete selected"})]})]}),f.jsxs("div",{className:"flex-1 overflow-auto px-3 pb-3",children:[ae.length===0&&f.jsx("div",{className:"px-4 text-gray-500 dark:text-gray-400 text-sm",children:B==="newsletter"?L?"No AI Studio newsletters yet. Create your first newsletter.":"This newsletter draft is missing workspace context. Open AI Studio from CloudMySite Newsletter or select a workspace.":a.length===0?`No previous ${se}`:`No matching ${se} found`}),cB(ae).map(({category:be,items:Te})=>f.jsxs("div",{className:"mt-2 first:mt-0 space-y-1",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400 sticky top-0 z-1 bg-white dark:bg-gray-950 px-4 py-1",children:be}),f.jsx("div",{className:"space-y-0.5 pr-1",children:Te.map(Ne=>B==="newsletter"?f.jsx(EB,{item:Ne,onDelete:Fe=>Ye(Fe,Ne)},Ne.id):f.jsx(R$,{item:Ne,exportChat:e,onDelete:Fe=>Ye(Fe,Ne),onDuplicate:()=>ht(Ne.id),selectionMode:w,isSelected:A.includes(Ne.id),onToggleSelection:pt,mode:B},Ne.id))})]},be))]})]})]})}),f.jsx(zD,{open:u,onClose:Pe,initialTab:h}),f.jsx(tM,{open:b,onOpenChange:g,workspaceId:U,openFullStudioHref:V}),f.jsx(T$,{isOpen:O,items:S,mode:B,isDeleting:R,onClose:Ae,onConfirm:pe})]})},VE=typeof document<"u"?_t.useLayoutEffect:()=>{};var Og;const PB=(Og=_t.useInsertionEffect)!==null&&Og!==void 0?Og:VE;function TB(t){const e=x.useRef(null);return PB(()=>{e.current=t},[t]),x.useCallback((...r)=>{const n=e.current;return n?.(...r)},[])}const cl=t=>{var e;return(e=t?.ownerDocument)!==null&&e!==void 0?e:document},Wl=t=>t&&"window"in t&&t.window===t?t:cl(t).defaultView||window;function RB(t){return t!==null&&typeof t=="object"&&"nodeType"in t&&typeof t.nodeType=="number"}function IB(t){return RB(t)&&t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}let NB=!1;function b_(){return NB}function GE(t,e){if(!b_())return e&&t?t.contains(e):!1;if(!t||!e)return!1;let r=e;for(;r!==null;){if(r===t)return!0;r.tagName==="SLOT"&&r.assignedSlot?r=r.assignedSlot.parentNode:IB(r)?r=r.host:r=r.parentNode}return!1}const gv=(t=document)=>{var e;if(!b_())return t.activeElement;let r=t.activeElement;for(;r&&"shadowRoot"in r&&(!((e=r.shadowRoot)===null||e===void 0)&&e.activeElement);)r=r.shadowRoot.activeElement;return r};function qE(t){return b_()&&t.target.shadowRoot&&t.composedPath?t.composedPath()[0]:t.target}function LB(t){var e;if(typeof window>"u"||window.navigator==null)return!1;let r=(e=window.navigator.userAgentData)===null||e===void 0?void 0:e.brands;return Array.isArray(r)&&r.some(n=>t.test(n.brand))||t.test(window.navigator.userAgent)}function DB(t){var e;return typeof window<"u"&&window.navigator!=null?t.test(((e=window.navigator.userAgentData)===null||e===void 0?void 0:e.platform)||window.navigator.platform):!1}function KE(t){let e=null;return()=>(e==null&&(e=t()),e)}const MB=KE(function(){return DB(/^Mac/i)}),OB=KE(function(){return LB(/Android/i)});function YE(){let t=x.useRef(new Map),e=x.useCallback((s,i,a,o)=>{let l=o?.once?(...c)=>{t.current.delete(a),a(...c)}:a;t.current.set(a,{type:i,eventTarget:s,fn:l,options:o}),s.addEventListener(i,l,o)},[]),r=x.useCallback((s,i,a,o)=>{var l;let c=((l=t.current.get(a))===null||l===void 0?void 0:l.fn)||a;s.removeEventListener(i,c,o),t.current.delete(a)},[]),n=x.useCallback(()=>{t.current.forEach((s,i)=>{r(s.eventTarget,s.type,i,s.options)})},[r]);return x.useEffect(()=>n,[n]),{addGlobalListener:e,removeGlobalListener:r,removeAllGlobalListeners:n}}function jB(t){return t.pointerType===""&&t.isTrusted?!0:OB()&&t.pointerType?t.type==="click"&&t.buttons===1:t.detail===0&&!t.pointerType}function XE(t){let e=t;return e.nativeEvent=t,e.isDefaultPrevented=()=>e.defaultPrevented,e.isPropagationStopped=()=>e.cancelBubble,e.persist=()=>{},e}function $B(t,e){Object.defineProperty(t,"target",{value:e}),Object.defineProperty(t,"currentTarget",{value:e})}function JE(t){let e=x.useRef({isFocused:!1,observer:null});VE(()=>{const n=e.current;return()=>{n.observer&&(n.observer.disconnect(),n.observer=null)}},[]);let r=TB(n=>{t?.(n)});return x.useCallback(n=>{if(n.target instanceof HTMLButtonElement||n.target instanceof HTMLInputElement||n.target instanceof HTMLTextAreaElement||n.target instanceof HTMLSelectElement){e.current.isFocused=!0;let s=n.target,i=a=>
vendor: 4,464 bytes, line 26
26{if(e.current.isFocused=!1,s.disabled){let o=XE(a);r(o)}e.current.observer&&(e.current.observer.disconnect(),e.current.observer=null)};s.addEventListener("focusout",i,{once:!0}),e.current.observer=new MutationObserver(()=>{if(e.current.isFocused&&s.disabled){var a;(a=e.current.observer)===null||a===void 0||a.disconnect();let o=s===document.activeElement?null:document.activeElement;s.dispatchEvent(new FocusEvent("blur",{relatedTarget:o})),s.dispatchEvent(new FocusEvent("focusout",{bubbles:!0,relatedTarget:o}))}}),e.current.observer.observe(s,{attributes:!0,attributeFilter:["disabled"]})}},[r])}let BB=!1,lh=null,bv=new Set,cd=new Map,tc=!1,vv=!1;const FB={Tab:!0,Escape:!0};function v_(t,e){for(let r of bv)r(t,e)}function WB(t){return!(t.metaKey||!MB()&&t.altKey||t.ctrlKey||t.key==="Control"||t.key==="Shift"||t.key==="Meta")}function pp(t){tc=!0,WB(t)&&(lh="keyboard",v_("keyboard",t))}function Vc(t){lh="pointer",(t.type==="mousedown"||t.type==="pointerdown")&&(tc=!0,v_("pointer",t))}function QE(t){jB(t)&&(tc=!0,lh="virtual")}function ZE(t){t.target===window||t.target===document||BB||!t.isTrusted||(!tc&&!vv&&(lh="virtual",v_("virtual",t)),tc=!1,vv=!1)}function ek(){tc=!1,vv=!0}function yv(t){if(typeof window>"u"||typeof document>"u"||cd.get(Wl(t)))return;const e=Wl(t),r=cl(t);let n=e.HTMLElement.prototype.focus;e.HTMLElement.prototype.focus=function(){tc=!0,n.apply(this,arguments)},r.addEventListener("keydown",pp,!0),r.addEventListener("keyup",pp,!0),r.addEventListener("click",QE,!0),e.addEventListener("focus",ZE,!0),e.addEventListener("blur",ek,!1),typeof PointerEvent<"u"&&(r.addEventListener("pointerdown",Vc,!0),r.addEventListener("pointermove",Vc,!0),r.addEventListener("pointerup",Vc,!0)),e.addEventListener("beforeunload",()=>{tk(t)},{once:!0}),cd.set(e,{focus:n})}const tk=(t,e)=>{const r=Wl(t),n=cl(t);e&&n.removeEventListener("DOMContentLoaded",e),cd.has(r)&&(r.HTMLElement.prototype.focus=cd.get(r).focus,n.removeEventListener("keydown",pp,!0),n.removeEventListener("keyup",pp,!0),n.removeEventListener("click",QE,!0),r.removeEventListener("focus",ZE,!0),r.removeEventListener("blur",ek,!1),typeof PointerEvent<"u"&&(n.removeEventListener("pointerdown",Vc,!0),n.removeEventListener("pointermove",Vc,!0),n.removeEventListener("pointerup",Vc,!0)),cd.delete(r))};function HB(t){const e=cl(t);let r;return e.readyState!=="loading"?yv(t):(r=()=>{yv(t)},e.addEventListener("DOMContentLoaded",r)),()=>tk(t,r)}typeof document<"u"&&HB();function rk(){return lh!=="pointer"}const UB=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function zB(t,e,r){let n=cl(r?.target);const s=typeof window<"u"?Wl(r?.target).HTMLInputElement:HTMLInputElement,i=typeof window<"u"?Wl(r?.target).HTMLTextAreaElement:HTMLTextAreaElement,a=typeof window<"u"?Wl(r?.target).HTMLElement:HTMLElement,o=typeof window<"u"?Wl(r?.target).KeyboardEvent:KeyboardEvent;return t=t||n.activeElement instanceof s&&!UB.has(n.activeElement.type)||n.activeElement instanceof i||n.activeElement instanceof a&&n.activeElement.isContentEditable,!(t&&e==="keyboard"&&r instanceof o&&!FB[r.key])}function VB(t,e,r){yv(),x.useEffect(()=>{let n=(s,i)=>{zB(!!r?.isTextInput,s,i)&&t(rk())};return bv.add(n),()=>{bv.delete(n)}},e)}function GB(t){let{isDisabled:e,onFocus:r,onBlur:n,onFocusChange:s}=t;const i=x.useCallback(l=>{if(l.target===l.currentTarget)return n&&n(l),s&&s(!1),!0},[n,s]),a=JE(i),o=x.useCallback(l=>{const c=cl(l.target),u=c?gv(c):gv();l.target===l.currentTarget&&u===qE(l.nativeEvent)&&(r&&r(l),s&&s(!0),a(l))},[s,r,a]);return{focusProps:{onFocus:!e&&(r||s||n)?o:void 0,onBlur:!e&&(n||s)?i:void 0}}}function qB(t){let{isDisabled:e,onBlurWithin:r,onFocusWithin:n,onFocusWithinChange:s}=t,i=x.useRef({isFocusWithin:!1}),{addGlobalListener:a,removeAllGlobalListeners:o}=YE(),l=x.useCallback(d=>{d.currentTarget.contains(d.target)&&i.current.isFocusWithin&&!d.currentTarget.contains(d.relatedTarget)&&(i.current.isFocusWithin=!1,o(),r&&r(d),s&&s(!1))},[r,s,i,o]),c=JE(l),u=x.useCallback(d=>{if(!d.currentTarget.contains(d.target))return;const h=cl(d.target),m=gv(h);if(!i.current.isFocusWithin&&m===qE(d.nativeEvent)){n&&n(d),s&&s(!0),i.current.isFocusWithin=!0,c(d);let b=d.currentTarget;a(h,"focus",g=>{if(i.current.isFocusWithin&&!GE(b,g.target)){let p=new h.defaultView.FocusEvent("blur",{relatedTarget:g.target});$B(p,b);let y=XE(p);l(y)}},{capture:!0})}},[n,s,c,a,l]);return e?{focusWithinProps:{onFocus:void 0,onBlur:void 0}}
vendor: 4,140 bytes, line 26
26:{focusWithinProps:{onFocus:u,onBlur:l}}}let _v=!1,Xh=0;function KB(){_v=!0,setTimeout(()=>{_v=!1},50)}function dw(t){t.pointerType==="touch"&&KB()}function YB(){if(!(typeof document>"u"))return Xh===0&&typeof PointerEvent<"u"&&document.addEventListener("pointerup",dw),Xh++,()=>{Xh--,!(Xh>0)&&typeof PointerEvent<"u"&&document.removeEventListener("pointerup",dw)}}function XB(t){let{onHoverStart:e,onHoverChange:r,onHoverEnd:n,isDisabled:s}=t,[i,a]=x.useState(!1),o=x.useRef({isHovered:!1,ignoreEmulatedMouseEvents:!1,pointerType:"",target:null}).current;x.useEffect(YB,[]);let{addGlobalListener:l,removeAllGlobalListeners:c}=YE(),{hoverProps:u,triggerHoverEnd:d}=x.useMemo(()=>{let h=(g,p)=>{if(o.pointerType=p,s||p==="touch"||o.isHovered||!g.currentTarget.contains(g.target))return;o.isHovered=!0;let y=g.currentTarget;o.target=y,l(cl(g.target),"pointerover",v=>{o.isHovered&&o.target&&!GE(o.target,v.target)&&m(v,v.pointerType)},{capture:!0}),e&&e({type:"hoverstart",target:y,pointerType:p}),r&&r(!0),a(!0)},m=(g,p)=>{let y=o.target;o.pointerType="",o.target=null,!(p==="touch"||!o.isHovered||!y)&&(o.isHovered=!1,c(),n&&n({type:"hoverend",target:y,pointerType:p}),r&&r(!1),a(!1))},b={};return typeof PointerEvent<"u"&&(b.onPointerEnter=g=>{_v&&g.pointerType==="mouse"||h(g,g.pointerType)},b.onPointerLeave=g=>{!s&&g.currentTarget.contains(g.target)&&m(g,g.pointerType)}),{hoverProps:b,triggerHoverEnd:m}},[e,r,n,s,o,l,c]);return x.useEffect(()=>{s&&d({currentTarget:o.target},o.pointerType)},[s]),{hoverProps:u,isHovered:i}}function JB(t={}){let{autoFocus:e=!1,isTextInput:r,within:n}=t,s=x.useRef({isFocused:!1,isFocusVisible:e||rk()}),[i,a]=x.useState(!1),[o,l]=x.useState(()=>s.current.isFocused&&s.current.isFocusVisible),c=x.useCallback(()=>l(s.current.isFocused&&s.current.isFocusVisible),[]),u=x.useCallback(m=>{s.current.isFocused=m,a(m),c()},[c]);VB(m=>{s.current.isFocusVisible=m,c()},[],{isTextInput:r});let{focusProps:d}=GB({isDisabled:n,onFocusChange:u}),{focusWithinProps:h}=qB({isDisabled:!n,onFocusWithinChange:u});return{isFocused:i,isFocusVisible:o,focusProps:n?h:d}}var QB=Object.defineProperty,ZB=(t,e,r)=>e in t?QB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jg=(t,e,r)=>(ZB(t,typeof e!="symbol"?e+"":e,r),r);let eF=class{constructor(){jg(this,"current",this.detect()),jg(this,"handoffState","pending"),jg(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}},Fo=new eF;function bu(t){var e;return Fo.isServer?null:t==null?document:(e=t?.ownerDocument)!=null?e:document}function rc(t){var e,r;return Fo.isServer?null:t==null?document:(r=(e=t?.getRootNode)==null?void 0:e.call(t))!=null?r:document}function nc(t){var e,r;return(r=(e=rc(t))==null?void 0:e.activeElement)!=null?r:null}function moe(t){return nc(t)===t}function nk(t){typeof queueMicrotask=="function"?queueMicrotask(t):Promise.resolve().then(t).catch(e=>setTimeout(()=>{throw e}))}function _a(){let t=[],e={addEventListener(r,n,s,i){return r.addEventListener(n,s,i),e.add(()=>r.removeEventListener(n,s,i))},requestAnimationFrame(...r){let n=requestAnimationFrame(...r);return e.add(()=>cancelAnimationFrame(n))},nextFrame(...r){return e.requestAnimationFrame(()=>e.requestAnimationFrame(...r))},setTimeout(...r){let n=setTimeout(...r);return e.add(()=>clearTimeout(n))},microTask(...r){let n={current:!0};return nk(()=>{n.current&&r[0]()}),e.add(()=>{n.current=!1})},style(r,n,s){let i=r.style.getPropertyValue(n);return Object.assign(r.style,{[n]:s}),this.add(()=>{Object.assign(r.style,{[n]:i})})},group(r){let n=_a();return r(n),this.add(()=>n.dispose())},add(r){return t.includes(r)||t.push(r),()=>{let n=t.indexOf(r);if(n>=0)for(let s of t.splice(n,1))s()}},dispose(){for(let r of t.splice(0))r()}};return e}
26function ch(){let[t]=x.useState(_a);return x.useEffect(()=>()=>t.dispose(),[t]),t}let Us=(t,e)=>{Fo.isServer?x.useEffect(t,e):x.useLayoutEffect(t,e)};function pa(t){let e=x.useRef(t);return Us(()=>{e.current=t},[t]),e}let dr=function(t){let e=pa(t);return _t.useCallback((...r)=>e.current(...r),[e])};function tF(t){let e=t.width/2,r=t.height/2;return{top:t.clientY-r,right:t.clientX+e,bottom:t.clientY+r,left:t.clientX-e}}function rF(t,e){return!(!t||!e||t.right<e.left||t.left>e.right||t.bottom<e.top||t.top>e.bottom)}function nF({disabled:t=!1}={}){let e=x.useRef(null),[r,n]=x.useState(!1),s=ch(),i=dr(()=>{e.current=null,n(!1),s.dispose()}),a=dr(o=>{if(s.dispose(),e.current===null){e.current=o.currentTarget,n(!0);{let l=bu(o.currentTarget);s.addEventListener(l,"pointerup",i,!1),s.addEventListener(l,"pointermove",c=>{if(e.current){let u=tF(c);n(rF(u,e.current.getBoundingClientRect()))}},!1),s.addEventListener(l,"pointercancel",i,!1)}}});return{pressed:r,pressProps:t?{}:{onPointerDown:a,onPointerUp:i,onClick:i}}}function uh(t){return x.useMemo(()=>t,Object.values(t))}function xv(...t){return Array.from(new Set(t.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function Zi(t,e,...r){if(t in e){let s=e[t];return typeof s=="function"?s(...r):s}let n=new Error(`Tried to handle "${t}" but there is no handler defined. Only defined handlers are: ${Object.keys(e).map(s=>`"${s}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,Zi),n}var nu=(t=>(t[t.None=0]="None",t[t.RenderStrategy=1]="RenderStrategy",t[t.Static=2]="Static",t))(nu||{}),Ya=(t=>(t[t.Unmount=0]="Unmount",t[t.Hidden=1]="Hidden",t))(Ya||{});function bo(){let t=iF();return x.useCallback(e=>sF({mergeRefs:t,...e}),[t])}function sF({ourProps:t,theirProps:e,slot:r,defaultTag:n,features:s,visible:i=!0,name:a,mergeRefs:o}){o=o??oF;let l=sk(e,t);if(i)return Jh(l,r,n,a,o);let c=s??0;if(c&2){let{static:u=!1,...d}=l;if(u)return Jh(d,r,n,a,o)}if(c&1){let{unmount:u=!0,...d}=l;return Zi(u?0:1,{0(){return null},1(){return Jh({...d,hidden:!0,style:{display:"none"}},r,n,a,o)}})}return Jh(l,r,n,a,o)}function Jh(t,e={},r,n,s){let{as:i=r,children:a,refName:o="ref",...l}=$g(t,["unmount","static"]),c=t.ref!==void 0?{[o]:t.ref}:{},u=typeof a=="function"?a(e):a;"className"in l&&l.className&&typeof l.className=="function"&&(l.className=l.className(e)),l["aria-labelledby"]&&l["aria-labelledby"]===l.id&&(l["aria-labelledby"]=void 0);let d={};if(e){let h=!1,m=[];for(let[b,g]of Object.entries(e))typeof g=="boolean"&&(h=!0),g===!0&&m.push(b.replace(/([A-Z])/g,p=>`-${p.toLowerCase()}`));if(h){d["data-headlessui-state"]=m.join(" ");for(let b of m)d[`data-${b}`]=""}}if(ud(i)&&(Object.keys(Nl(l)).length>0||Object.keys(Nl(d)).length>0))if(!x.isValidElement(u)||Array.isArray(u)&&u.length>1||lF(u)){if(Object.keys(Nl(l)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${n} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(Nl(l)).concat(Object.keys(Nl(d))).map(h=>` - ${h}`).join(` 27`),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(h=>` - ${h}`).join(` 28`)].join(` 29`))}else{let h=u.props,m=h?.className,b=typeof m=="function"?(...y)=>xv(m(...y),l.className):xv(m,l.className),g=b?{className:b}:{},p=sk(u.props,Nl($g(l,["ref"])));for(let y in d)y in p&&delete d[y];return x.cloneElement(u,Object.assign({},p,d,c,{ref:s(aF(u),c.ref)},g))}return x.createElement(i,Object.assign({},$g(l,["ref"]),!ud(i)&&c,!ud(i)&&d),u)}function iF(){let t=x.useRef([]),e=x.useCallback(r=>{for(let n of t.current)n!=null&&(typeof n=="function"?n(r):n.current=r)},[]);return(...r)=>{if(!r.every(n=>n==null))return t.current=r,e}}function oF(...t){return t.every(e=>e==null)?void 0:e=>{for(let r of t)r!=null&&(typeof r=="function"?r(e):r.current=e)}}function sk(...t){if(t.length===0)return{};if(t.length===1)return t[0];let e={},r={};for(let n of t)for(let s in n)s.startsWith("on")&&typeof n[s]=="function"?(r[s]!=null||(r[s]=[]),r[s].push(n[s])):e[s]=n[s];if(e.disabled||e["aria-disabled"])for(let n in r)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(n)&&(r[n]=[s=>{var i;return(i=s?.preventDefault)==null?void 0:i.call(s)}]);for(let n in r)Object.assign(e,{[n](s,...i){let a=r[n];for(let o of a){if((s instanceof Event||s?.nativeEvent instanceof Event)&&s.defaultPrevented)return;o(s,...i)}}});return e}function wv(...t){if(t.length===0)return{};if(t.length===1)return t[0];let e={},r={};for(let n of t)for(let s in n)s.startsWith("on")&&typeof n[s]=="function"?(r[s]!=null||(r[s]=[]),r[s].push(n[s])):e[s]=n[s];for(let n in r)Object.assign(e,{[n](...s){let i=r[n];for(let a of i)a?.(...s)}});return e}function ji(t){var e;return Object.assign(x.forwardRef(t),{displayName:(e=t.displayName)!=null?e:t.name})}function Nl(t){let e=Object.assign({},t);for(let r in e)e[r]===void 0&&delete e[r];return e}function $g(t,e=[]){let r=Object.assign({},t);for(let n of e)n in r&&delete r[n];return r}function aF(t){return _t.version.split(".")[0]>="19"?t.props.ref:t.ref}function ud(t){return t===x.Fragment||t===Symbol.for("react.fragment")}function lF(t){return ud(t.type)}let cF="span";var kd=(t=>(t[t.None=1]="None",t[t.Focusable=2]="Focusable",t[t.Hidden=4]="Hidden",t))(kd||{});function uF(t,e){var r;let{features:n=1,...s}=t,i={ref:e,"aria-hidden":(n&2)===2?!0:(r=s["aria-hidden"])!=null?r:void 0,hidden:(n&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(n&4)===4&&(n&2)!==2&&{display:"none"}}};return bo()({ourProps:i,theirProps:s,slot:{},defaultTag:cF,name:"Hidden"})}let mp=ji(uF);function dF(t){return typeof t!="object"||t===null?!1:"nodeType"in t}function Xl(t){return dF(t)&&"tagName"in t}function ma(t){return Xl(t)&&"accessKey"in t}function Oc(t){return Xl(t)&&"tabIndex"in t}function hF(t){return Xl(t)&&"style"in t}function fF(t){return ma(t)&&t.nodeName==="IFRAME"}function pF(t){return ma(t)&&t.nodeName==="INPUT"}function mF(t){return ma(t)&&t.nodeName==="FIELDSET"}function ik(t){return ma(t)&&t.nodeName==="LEGEND"}function ok(t){let e=t.parentElement,r=null;for(;e&&!mF(e);)ik(e)&&(r=e),e=e.parentElement;let n=e?.getAttribute("disabled")==="";return n&&gF(r)?!1:n}function gF(t){if(!t)return!1;let e=t.previousElementSibling;for(;e!==null;){if(ik(e))return!1;e=e.previousElementSibling}return!0}let ak=Symbol();function lk(t,e=!0){return Object.assign(t,{[ak]:e})}function mo(...t){let e=x.useRef(t);x.useEffect(()=>{e.current=t},[t]);let r=dr(n=>{for(let s of e.current)s!=null&&(typeof s=="function"?s(n):s.current=n)});return t.every(n=>n==null||n?.[ak])?void 0:r}var Ua=(t=>(t.Space=" ",t.Enter="Enter",t.Escape="Escape",t.Backspace="Backspace",t.Delete="Delete",t.ArrowLeft="ArrowLeft",t.ArrowUp="ArrowUp",t.ArrowRight="ArrowRight",t.ArrowDown="ArrowDown",t.Home="Home",t.End="End",t.PageUp="PageUp",t.PageDown="PageDown",t.Tab="Tab",t))(Ua||{});let bF=x.createContext(()=>{});function ck({value:t,children:e}){return _t.createElement(bF.Provider,{value:t},e)}function hw(t){if(t===null)return{width:0,height:0};let{width:e,height:r}=t.getBoundingClientRect();return{width:e,height:r}}function vF(t,e,r=!1){let[n,s]=x.useState(()=>hw(e));return Us(()=>
vendor: 4,459 bytes, lines 29-37
29{if(!e||!t)return;let i=_a();return i.requestAnimationFrame(function a(){i.requestAnimationFrame(a),s(o=>{let l=hw(e);return l.width===o.width&&l.height===o.height?o:l})}),()=>{i.dispose()}},[e,t]),r?{width:`${n.width}px`,height:`${n.height}px`}:n}let uk=class extends Map{constructor(e){super(),this.factory=e}get(e){let r=super.get(e);return r===void 0&&(r=this.factory(e),this.set(e,r)),r}};var yF=Object.defineProperty,_F=(t,e,r)=>e in t?yF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xF=(t,e,r)=>(_F(t,e+"",r),r),dk=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},zi=(t,e,r)=>(dk(t,e,"read from private field"),r?r.call(t):e.get(t)),Bg=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},fw=(t,e,r,n)=>(dk(t,e,"write to private field"),e.set(t,r),r),Po,Xu,Ju;let hk=class{constructor(e){Bg(this,Po,{}),Bg(this,Xu,new uk(()=>new Set)),Bg(this,Ju,new Set),xF(this,"disposables",_a()),fw(this,Po,e),Fo.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return zi(this,Po)}subscribe(e,r){if(Fo.isServer)return()=>{};let n={selector:e,callback:r,current:e(zi(this,Po))};return zi(this,Ju).add(n),this.disposables.add(()=>{zi(this,Ju).delete(n)})}on(e,r){return Fo.isServer?()=>{}:(zi(this,Xu).get(e).add(r),this.disposables.add(()=>{zi(this,Xu).get(e).delete(r)}))}send(e){let r=this.reduce(zi(this,Po),e);if(r!==zi(this,Po)){fw(this,Po,r);for(let n of zi(this,Ju)){let s=n.selector(zi(this,Po));fk(n.current,s)||(n.current=s,n.callback(s))}for(let n of zi(this,Xu).get(e.type))n(zi(this,Po),e)}}};Po=new WeakMap,Xu=new WeakMap,Ju=new WeakMap;function fk(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null?!1:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:Fg(t[Symbol.iterator](),e[Symbol.iterator]()):t instanceof Map&&e instanceof Map||t instanceof Set&&e instanceof Set?t.size!==e.size?!1:Fg(t.entries(),e.entries()):pw(t)&&pw(e)?Fg(Object.entries(t)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function Fg(t,e){do{let r=t.next(),n=e.next();if(r.done&&n.done)return!0;if(r.done||n.done||!Object.is(r.value,n.value))return!1}while(!0)}function pw(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}var wF=Object.defineProperty,SF=(t,e,r)=>e in t?wF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mw=(t,e,r)=>(SF(t,typeof e!="symbol"?e+"":e,r),r),CF=(t=>(t[t.Push=0]="Push",t[t.Pop=1]="Pop",t))(CF||{});let AF={0(t,e){let r=e.id,n=t.stack,s=t.stack.indexOf(r);if(s!==-1){let i=t.stack.slice();return i.splice(s,1),i.push(r),n=i,{...t,stack:n}}return{...t,stack:[...t.stack,r]}},1(t,e){let r=e.id,n=t.stack.indexOf(r);if(n===-1)return t;let s=t.stack.slice();return s.splice(n,1),{...t,stack:s}}},EF=class pk extends hk{constructor(){super(...arguments),mw(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),mw(this,"selectors",{isTop:(e,r)=>e.stack[e.stack.length-1]===r,inStack:(e,r)=>e.stack.includes(r)})}static new(){return new pk({stack:[]})}reduce(e,r){return Zi(r.type,AF,e,r)}};const mk=new uk(()=>EF.new());var gk={exports:{}},bk={};/** 30 * @license React 31 * use-sync-external-store-with-selector.production.js 32 * 33 * Copyright (c) Meta Platforms, Inc. and affiliates. 34 * 35 * This source code is licensed under the MIT license found in the 36 * LICENSE file in the root directory of this source tree. 37 */var dh=x;function kF(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var PF=typeof Object.is=="function"?Object.is:kF,TF=dh.useSyncExternalStore,RF=dh.useRef,IF=dh.useEffect,NF=dh.useMemo,LF=dh.useDebugValue;bk.useSyncExternalStoreWithSelector=function(t,e,r,n,s){var i=RF(null);if(i.current===null){var a={hasValue:!1,value:null};i.current=a}else a=i.current;i=NF(function(){function l(m){if(!c){if(c=!0,u=m,m=n(m),s!==void 0&&a.hasValue){var b=a.value;if(s(b,m))return d=b}return d=m}if(b=d,PF(u,m))return b;var g=n(m);return s!==void 0&&s(b,g)?(u=m,b):(u=m,d=g)}var c=!1,u,d,h=r===void 0?null:r;return[function(){return l(e())},h===null?void 0:function(){return l(h())}]},[e,r,n,s]);var o=TF(t,i[0],i[1]);return IF(function(){a.hasValue=!0,a.value=o},[o]),LF(o),o};gk.exports=bk;var DF=gk.exports;function sc(t,e,r=fk){return DF.useSyncExternalStoreWithSelector(dr(n=>
vendor: 10,750 bytes, lines 37-38
37t.subscribe(MF,n)),dr(()=>t.state),dr(()=>t.state),dr(e),r)}function MF(t){return t}function OF(t,e){let r=x.useId(),n=mk.get(e),[s,i]=sc(n,x.useCallback(a=>[n.selectors.isTop(a,r),n.selectors.inStack(a,r)],[n,r]));return Us(()=>{if(t)return n.actions.push(r),()=>n.actions.pop(r)},[n,t,r]),t?i?s:!0:!1}function jF(t,e,r){let n=pa(s=>{let i=s.getBoundingClientRect();i.x===0&&i.y===0&&i.width===0&&i.height===0&&r()});x.useEffect(()=>{if(!t)return;let s=e===null?null:ma(e)?e:e.current;if(!s)return;let i=_a();if(typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>n.current(s));a.observe(s),i.add(()=>a.disconnect())}if(typeof IntersectionObserver<"u"){let a=new IntersectionObserver(()=>n.current(s));a.observe(s),i.add(()=>a.disconnect())}return()=>i.dispose()},[e,n,t])}let Sv=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","details>summary","textarea:not([disabled])"].map(t=>`${t}:not([tabindex='-1'])`).join(","),$F=["[data-autofocus]"].map(t=>`${t}:not([tabindex='-1'])`).join(",");var aa=(t=>(t[t.First=1]="First",t[t.Previous=2]="Previous",t[t.Next=4]="Next",t[t.Last=8]="Last",t[t.WrapAround=16]="WrapAround",t[t.NoScroll=32]="NoScroll",t[t.AutoFocus=64]="AutoFocus",t))(aa||{}),gp=(t=>(t[t.Error=0]="Error",t[t.Overflow=1]="Overflow",t[t.Success=2]="Success",t[t.Underflow=3]="Underflow",t))(gp||{}),BF=(t=>(t[t.Previous=-1]="Previous",t[t.Next=1]="Next",t))(BF||{});function dm(t=document.body){return t==null?[]:Array.from(t.querySelectorAll(Sv)).sort((e,r)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(r.tabIndex||Number.MAX_SAFE_INTEGER)))}function FF(t=document.body){return t==null?[]:Array.from(t.querySelectorAll($F)).sort((e,r)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(r.tabIndex||Number.MAX_SAFE_INTEGER)))}var y_=(t=>(t[t.Strict=0]="Strict",t[t.Loose=1]="Loose",t))(y_||{});function vk(t,e=0){var r;return t===((r=bu(t))==null?void 0:r.body)?!1:Zi(e,{0(){return t.matches(Sv)},1(){let n=t;for(;n!==null;){if(n.matches(Sv))return!0;n=n.parentElement}return!1}})}var WF=(t=>(t[t.Keyboard=0]="Keyboard",t[t.Mouse=1]="Mouse",t))(WF||{});typeof window<"u"&&typeof document<"u"&&(document.addEventListener("keydown",t=>{t.metaKey||t.altKey||t.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",t=>{t.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:t.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function voe(t){t?.focus({preventScroll:!0})}let HF=["textarea","input"].join(",");function UF(t){var e,r;return(r=(e=t?.matches)==null?void 0:e.call(t,HF))!=null?r:!1}function zF(t,e=r=>r){return t.slice().sort((r,n)=>{let s=e(r),i=e(n);if(s===null||i===null)return 0;let a=s.compareDocumentPosition(i);return a&Node.DOCUMENT_POSITION_FOLLOWING?-1:a&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function Hl(t,e,{sorted:r=!0,relativeTo:n=null,skipElements:s=[]}={}){let i=Array.isArray(t)?t.length>0?rc(t[0]):document:rc(t),a=Array.isArray(t)?r?zF(t):t:e&64?FF(t):dm(t);s.length>0&&a.length>1&&(a=a.filter(m=>!s.some(b=>b!=null&&"current"in b?b?.current===m:b===m))),n=n??i?.activeElement;let o=(()=>{if(e&5)return 1;if(e&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),l=(()=>{if(e&1)return 0;if(e&2)return Math.max(0,a.indexOf(n))-1;if(e&4)return Math.max(0,a.indexOf(n))+1;if(e&8)return a.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),c=e&32?{preventScroll:!0}:{},u=0,d=a.length,h;do{if(u>=d||u+d<=0)return 0;let m=l+u;if(e&16)m=(m+d)%d;else{if(m<0)return 3;if(m>=d)return 1}h=a[m],h?.focus(c),u+=o}while(h!==nc(h));return e&6&&UF(h)&&h.select(),2}function yk(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function VF(){return/Android/gi.test(window.navigator.userAgent)}function gw(){return yk()||VF()}function Qh(t,e,r,n){let s=pa(r);x.useEffect(()=>{if(!t)return;function i(a){s.current(a)}return document.addEventListener(e,i,n),()=>document.removeEventListener(e,i,n)},[t,e,n])}function _k(t,e,r,n){let s=pa(r);x.useEffect(()=>{if(!t)return;function i(a){s.current(a)}return window.addEventListener(e,i,n),()=>window.removeEventListener(e,i,n)},[t,e,n])}const bw=30;function GF(t,e,r){let n=pa(r),s=x.useCallback(function(o,l){if(o.defaultPrevented)return;let c=l(o);if(c===null||!c.getRootNode().contains(c)||!c.isConnected)return;let u=function d(h){return typeof h=="function"?d(h()):Array.isArray(h)||h instanceof Set?h:[h]}(e);for(let d of u)if(d!==null&&(d.contains(c)||o.composed&&o.composedPath().includes(d)))return;return!vk(c,y_.Loose)&&c.tabIndex!==-1&&o.preventDefault(),n.current(o,c)},[n,e]),i=x.useRef(null);Qh(t,"pointerdown",o=>{var l,c;gw()||(i.current=((c=(l=o.composedPath)==null?void 0:l.call(o))==null?void 0:c[0])||o.target)},!0),Qh(t,"pointerup",o=>{if(gw()||!i.current)return;let l=i.current;return i.current=null,s(o,()=>l)},!0);let a=x.useRef({x:0,y:0});Qh(t,"touchstart",o=>{a.current.x=o.touches[0].clientX,a.current.y=o.touches[0].clientY},!0),Qh(t,"touchend",o=>{let l={x:o.changedTouches[0].clientX,y:o.changedTouches[0].clientY};if(!(Math.abs(l.x-a.current.x)>=bw||Math.abs(l.y-a.current.y)>=bw))return s(o,()=>Oc(o.target)?o.target:null)},!0),_k(t,"blur",o=>s(o,()=>fF(window.document.activeElement)?window.document.activeElement:null),!0)}function Cv(...t){return x.useMemo(()=>bu(...t),[...t])}function qF(...t){return x.useMemo(()=>rc(...t),[...t])}function KF(t,e,r,n){let s=pa(r);x.useEffect(()=>{t=t??window;function i(a){s.current(a)}return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i,n)},[t,e,n])}function YF(t,e){return x.useMemo(()=>{var r;if(t.type)return t.type;let n=(r=t.as)!=null?r:"button";if(typeof n=="string"&&n.toLowerCase()==="button"||e?.tagName==="BUTTON"&&!e.hasAttribute("type"))return"button"},[t.type,t.as,e])}function XF(t){return x.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot)}function JF(t,e){let r=t(),n=new Set;return{getSnapshot(){return r},subscribe(s){return n.add(s),()=>n.delete(s)},dispatch(s,...i){let a=e[s].call(r,...i);a&&(r=a,n.forEach(o=>o()))}}}function QF(){let t;return{before({doc:e}){var r;let n=e.documentElement,s=(r=e.defaultView)!=null?r:window;t=Math.max(0,s.innerWidth-n.clientWidth)},after({doc:e,d:r}){let n=e.documentElement,s=Math.max(0,n.clientWidth-n.offsetWidth),i=Math.max(0,t-s);r.style(n,"paddingRight",`${i}px`)}}}function ZF(){return yk()?{before({doc:t,d:e,meta:r}){function n(s){for(let i of r().containers)for(let a of i())if(a.contains(s))return!0;return!1}e.microTask(()=>{var s;if(window.getComputedStyle(t.documentElement).scrollBehavior!=="auto"){let o=_a();o.style(t.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>o.dispose()))}let i=(s=window.scrollY)!=null?s:window.pageYOffset,a=null;e.addEventListener(t,"click",o=>{if(Oc(o.target))try{let l=o.target.closest("a");if(!l)return;let{hash:c}=new URL(l.href),u=t.querySelector(c);Oc(u)&&!n(u)&&(a=u)}catch{}},!0),e.group(o=>{e.addEventListener(t,"touchstart",l=>{if(o.dispose(),Oc(l.target)&&hF(l.target))if(n(l.target)){let c=l.target;for(;c.parentElement&&n(c.parentElement);)c=c.parentElement;o.style(c,"overscrollBehavior","contain")}else o.style(l.target,"touchAction","none")})}),e.addEventListener(t,"touchmove",o=>{if(Oc(o.target)){if(pF(o.target))return;if(n(o.target)){let l=o.target;for(;l.parentElement&&l.dataset.headlessuiPortal!==""&&!(l.scrollHeight>l.clientHeight||l.scrollWidth>l.clientWidth);)l=l.parentElement;l.dataset.headlessuiPortal===""&&o.preventDefault()}else o.preventDefault()}},{passive:!1}),e.add(()=>{var o;let l=(o=window.scrollY)!=null?o:window.pageYOffset;i!==l&&window.scrollTo(0,i),a&&a.isConnected&&(a.scrollIntoView({block:"nearest"}),a=null)})})}}:{}}function e5(){return{before({doc:t,d:e}){e.style(t.documentElement,"overflow","hidden")}}}function vw(t){let e={};for(let r of t)Object.assign(e,r(e));return e}let Ul=JF(()=>new Map,{PUSH(t,e){var r;let n=(r=this.get(t))!=null?r:{doc:t,count:0,d:_a(),meta:new Set,computedMeta:{}};return n.count++,n.meta.add(e),n.computedMeta=vw(n.meta),this.set(t,n),this},POP(t,e){let r=this.get(t);return r&&(r.count--,r.meta.delete(e),r.computedMeta=vw(r.meta)),this},SCROLL_PREVENT(t){let e={doc:t.doc,d:t.d,meta(){return t.computedMeta}},r=[ZF(),QF(),e5()];r.forEach(({before:n})=>n?.(e)),r.forEach(({after:n})=>n?.(e))},SCROLL_ALLOW({d:t}){t.dispose()},TEARDOWN({doc:t}){this.delete(t)}});Ul.subscribe(()=>{let t=Ul.getSnapshot(),e=new Map;for(let[r]of t)e.set(r,r.documentElement.style.overflow);for(let r of t.values()){let n=e.get(r.doc)==="hidden",s=r.count!==0;(s&&!n||!s&&n)&&Ul.dispatch(r.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",r),r.count===0&&Ul.dispatch("TEARDOWN",r)}});function t5(t,e,r=()=>({containers:[]})){let n=XF(Ul),s=e?n.get(e):void 0,i=s?s.count>0:!1;return Us(()=>{if(!(!e||!t))return Ul.dispatch("PUSH",e,r),()=>Ul.dispatch("POP",e,r)},[t,e]),i}function r5(t,e,r=()=>[document.body]){let n=OF(t,"scroll-lock");t5(n,e,s=>{var i;return{containers:[...(i=s.containers)!=null?i:[],r]}})}function n5(t=0){let[e,r]=x.useState(t),n=x.useCallback(l=>r(l),[]),s=x.useCallback(l=>r(c=>c|l),[]),i=x.useCallback(l=>(e&l)===l,[e]),a=x.useCallback(l=>r(c=>c&~l),[]),o=x.useCallback(l=>r(c=>c^l),[]);return{flags:e,setFlag:n,addFlag:s,hasFlag:i,removeFlag:a,toggleFlag:o}}var s5={},yw,_w;typeof cp<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((yw=cp==null?void 0:s5)==null?void 0:yw.NODE_ENV)==="test"&&typeof((_w=Element?.prototype)==null?void 0:_w.getAnimations)>"u"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` 38`)),[]});var i5=(t=>(t[t.None=0]="None",t[t.Closed=1]="Closed",t[t.Enter=2]="Enter",t[t.Leave=4]="Leave",t))(i5||{});function __(t){let e={};for(let r in t)t[r]===!0&&(e[`data-${r}`]="");return e}function x_(t,e,r,n){let[s,i]=x.useState(r),{hasFlag:a,addFlag:o,removeFlag:l}=n5(t&&s?3:0),c=x.useRef(!1),u=x.useRef(!1),d=ch();return Us(()=>{var h;if(t){if(r&&i(!0),!e){r&&o(3);return}return(h=n?.start)==null||h.call(n,r),o5(e,{inFlight:c,prepare(){u.current?u.current=!1:u.current=c.current,c.current=!0,!u.current&&(r?(o(3),l(4)):(o(4),l(2)))},run(){u.current?r?(l(3),o(4)):(l(4),o(3)):r?l(1):o(1)},done(){var m;u.current&&c5(e)||(c.current=!1,l(7),r||i(!1),(m=n?.end)==null||m.call(n,r))}})}}
38,[t,r,e,d]),t?[s,{closed:a(1),enter:a(2),leave:a(4),transition:a(2)||a(4)}]:[r,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function o5(t,{prepare:e,run:r,done:n,inFlight:s}){let i=_a();return l5(t,{prepare:e,inFlight:s}),i.nextFrame(()=>{r(),i.requestAnimationFrame(()=>{i.add(a5(t,n))})}),i.dispose}function a5(t,e){var r,n;let s=_a();if(!t)return s.dispose;let i=!1;s.add(()=>{i=!0});let a=(n=(r=t.getAnimations)==null?void 0:r.call(t).filter(o=>o instanceof CSSTransition))!=null?n:[];return a.length===0?(e(),s.dispose):(Promise.allSettled(a.map(o=>o.finished)).then(()=>{i||e()}),s.dispose)}function l5(t,{inFlight:e,prepare:r}){if(e!=null&&e.current){r();return}let n=t.style.transition;t.style.transition="none",r(),t.offsetHeight,t.style.transition=n}function c5(t){var e,r;return((r=(e=t.getAnimations)==null?void 0:e.call(t))!=null?r:[]).some(n=>n instanceof CSSTransition&&n.playState!=="finished")}function u5(){const t=navigator.userAgentData;return t&&Array.isArray(t.brands)?t.brands.map(e=>{let{brand:r,version:n}=e;return r+"/"+n}).join(" "):navigator.userAgent}const xk={...rp},d5=xk.useInsertionEffect,h5=d5||(t=>t());function wk(t){const e=x.useRef(()=>{});return h5(()=>{e.current=t}),x.useCallback(function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return e.current==null?void 0:e.current(...n)},[])}var Av=typeof document<"u"?x.useLayoutEffect:x.useEffect;let xw=!1,f5=0;const ww=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+f5++;function p5(){const[t,e]=x.useState(()=>xw?ww():void 0);return Av(()=>{t==null&&e(ww())},[]),x.useEffect(()=>{xw=!0},[]),t}const m5=xk.useId,g5=m5||p5;function b5(){const t=new Map;return{emit(e,r){var n;(n=t.get(e))==null||n.forEach(s=>s(r))},on(e,r){t.set(e,[...t.get(e)||[],r])},off(e,r){var n;t.set(e,((n=t.get(e))==null?void 0:n.filter(s=>s!==r))||[])}}}const v5=x.createContext(null),y5=x.createContext(null),_5=()=>{var t;return((t=x.useContext(v5))==null?void 0:t.id)||null},x5=()=>x.useContext(y5),w5="data-floating-ui-focusable";function S5(t){const{open:e=!1,onOpenChange:r,elements:n}=t,s=g5(),i=x.useRef({}),[a]=x.useState(()=>b5()),o=_5()!=null,[l,c]=x.useState(n.reference),u=wk((m,b,g)=>{i.current.openEvent=m?b:void 0,a.emit("openchange",{open:m,event:b,reason:g,nested:o}),r?.(m,b,g)}),d=x.useMemo(()=>({setPositionReference:c}),[]),h=x.useMemo(()=>({reference:l||n.reference||null,floating:n.floating||null,domReference:n.reference}),[l,n.reference,n.floating]);return x.useMemo(()=>({dataRef:i,open:e,onOpenChange:u,elements:h,events:a,floatingId:s,refs:d}),[e,u,h,a,s,d])}function C5(t){t===void 0&&(t={});const{nodeId:e}=t,r=S5({...t,elements:{reference:null,floating:null,...t.elements}}),n=t.rootContext||r,s=n.elements,[i,a]=x.useState(null),[o,l]=x.useState(null),u=s?.domReference||i,d=x.useRef(null),h=x5();Av(()=>{u&&(d.current=u)},[u]);const m=C2({...t,elements:{...s,...o&&{reference:o}}}),b=x.useCallback(_=>{const w=Uh(_)?{getBoundingClientRect:()=>_.getBoundingClientRect(),contextElement:_}:_;l(w),m.refs.setReference(w)},[m.refs]),g=x.useCallback(_=>{(Uh(_)||_===null)&&(d.current=_,a(_)),(Uh(m.refs.reference.current)||m.refs.reference.current===null||_!==null&&!Uh(_))&&m.refs.setReference(_)},[m.refs]),p=x.useMemo(()=>({...m.refs,setReference:g,setPositionReference:b,domReference:d}),[m.refs,g,b]),y=x.useMemo(()=>({...m.elements,domReference:u}),[m.elements,u]),v=x.useMemo(()=>({...m,...n,refs:p,elements:y,nodeId:e}),[m,p,y,e,n]);return Av(()=>{n.dataRef.current.floatingContext=v;const _=h?.nodesRef.current.find(w=>w.id===e);_&&(_.context=v)}),x.useMemo(()=>({...m,context:v,refs:p,elements:y}),[m,p,y,v])}const Sw="active",Cw="selected";function Wg(t,e,r){const n=new Map,s=r==="item";let i=t;if(s&&t){const{[Sw]:a,[Cw]:o,...l}=t;i=l}return{...r==="floating"&&{tabIndex:-1,[w5]:""},...i,...e.map(a=>{const o=a?a[r]:null;return typeof o=="function"?t?o(t):null:o}).concat(t).reduce((a,o)=>(o&&Object.entries(o).forEach(l=>{let[c,u]=l;if(!(s&&[Sw,Cw].includes(c)))if(c.indexOf("on")===0){if(n.has(c)||n.set(c,[]),typeof u=="function"){var d;(d=n.get(c))==null||d.push(u),a[c]=function(){for(var h,m=arguments.length,b=new Array(m),g=0;g<m;g++)b[g]=arguments[g];
38return(h=n.get(c))==null?void 0:h.map(p=>p(...b)).find(p=>p!==void 0)}}}else a[c]=u}),a),{})}}function A5(t){t===void 0&&(t=[]);const e=t.map(o=>o?.reference),r=t.map(o=>o?.floating),n=t.map(o=>o?.item),s=x.useCallback(o=>Wg(o,t,"reference"),e),i=x.useCallback(o=>Wg(o,t,"floating"),r),a=x.useCallback(o=>Wg(o,t,"item"),n);return x.useMemo(()=>({getReferenceProps:s,getFloatingProps:i,getItemProps:a}),[s,i,a])}function Aw(t,e){return{...t,rects:{...t.rects,floating:{...t.rects.floating,height:e}}}}const E5=t=>({name:"inner",options:t,async fn(e){const{listRef:r,overflowRef:n,onFallbackChange:s,offset:i=0,index:a=0,minItemsVisible:o=4,referenceOverflowThreshold:l=0,scrollRef:c,...u}=A2(t,e),{rects:d,elements:{floating:h}}=e,m=r.current[a],b=c?.current||h,g=h.clientTop||b.clientTop,p=h.clientTop!==0,y=b.clientTop!==0,v=h===b;if(!m)return{};const _={...e,...await cE(-m.offsetTop-h.clientTop-d.reference.height/2-m.offsetHeight/2-i).fn(e)},w=await mg(Aw(_,b.scrollHeight+g+h.clientTop),u),C=await mg(_,{...u,elementContext:"reference"}),A=gg(0,w.top),E=_.y+A,O=(b.scrollHeight>b.clientHeight?T=>T:E2)(gg(0,b.scrollHeight+(p&&v||y?g*2:0)-A-gg(0,w.bottom)));if(b.style.maxHeight=O+"px",b.scrollTop=A,s){const T=b.offsetHeight<m.offsetHeight*k2(o,r.current.length)-1||C.top>=-l||C.bottom>=-l;up.flushSync(()=>s(T))}return n&&(n.current=await mg(Aw({..._,y:E},b.offsetHeight+g+h.clientTop),u)),{y:E}}});function k5(t,e){const{open:r,elements:n}=t,{enabled:s=!0,overflowRef:i,scrollRef:a,onChange:o}=e,l=wk(o),c=x.useRef(!1),u=x.useRef(null),d=x.useRef(null);x.useEffect(()=>{if(!s)return;function m(g){if(g.ctrlKey||!b||i.current==null)return;const p=g.deltaY,y=i.current.top>=-.5,v=i.current.bottom>=-.5,_=b.scrollHeight-b.clientHeight,w=p<0?-1:1,C=p<0?"max":"min";b.scrollHeight<=b.clientHeight||(!y&&p>0||!v&&p<0?(g.preventDefault(),up.flushSync(()=>{l(A=>A+Math[C](p,_*w))})):/firefox/i.test(u5())&&(b.scrollTop+=p))}const b=a?.current||n.floating;if(r&&b)return b.addEventListener("wheel",m),requestAnimationFrame(()=>{u.current=b.scrollTop,i.current!=null&&(d.current={...i.current})}),()=>{u.current=null,d.current=null,b.removeEventListener("wheel",m)}},[s,r,n.floating,i,a,l]);const h=x.useMemo(()=>({onKeyDown(){c.current=!0},onWheel(){c.current=!1},onPointerMove(){c.current=!1},onScroll(){const m=a?.current||n.floating;if(!(!i.current||!m||!c.current)){if(u.current!==null){const b=m.scrollTop-u.current;(i.current.bottom<-.5&&b<-1||i.current.top<-.5&&b>1)&&up.flushSync(()=>l(g=>g+b))}requestAnimationFrame(()=>{u.current=m.scrollTop})}}}),[n.floating,l,i,a]);return x.useMemo(()=>s?{floating:h}:{},[s,h])}let hh=x.createContext({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});hh.displayName="FloatingContext";let w_=x.createContext(null);w_.displayName="PlacementContext";function P5(t){return x.useMemo(()=>t?typeof t=="string"?{to:t}:t:null,[t])}function T5(){return x.useContext(hh).setReference}function R5(){let{getFloatingProps:t,slot:e}=x.useContext(hh);return x.useCallback((...r)=>Object.assign({},t(...r),{"data-anchor":e.anchor}),[t,e])}function I5(t=null){t===!1&&(t=null),typeof t=="string"&&(t={to:t});let e=x.useContext(w_),r=x.useMemo(()=>t,[JSON.stringify(t,(s,i)=>{var a;return(a=i?.outerHTML)!=null?a:i})]);Us(()=>{e?.(r??null)},[e,r]);let n=x.useContext(hh);return x.useMemo(()=>[n.setFloating,t?n.styles:{}],[n.setFloating,t,n.styles])}let Ew=4;function N5({children:t,enabled:e=!0}){let[r,n]=x.useState(null),[s,i]=x.useState(0),a=x.useRef(null),[o,l]=x.useState(null);L5(o);let c=e&&r!==null&&o!==null,{to:u="bottom",gap:d=0,offset:h=0,padding:m=0,inner:b}=D5(r,o),[g,p="center"]=u.split(" ");Us(()=>{c&&i(0)},[c]);let{refs:y,floatingStyles:v,context:_}=C5({open:c,placement:g==="selection"?p==="center"?"bottom":`bottom-${p}`:p==="center"?`${g}`:`${g}-${p}`,strategy:"absolute",transform:!1,middleware:[cE({mainAxis:g==="selection"?0:d,crossAxis:h}),P2({padding:m}),g!=="selection"&&T2({padding:m}),g==="selection"&&b?E5({...b,padding:m,overflowRef:a,offset:s,minItemsVisible:Ew,referenceOverflowThreshold:m,onFallbackChange(T){var R,N;if(!T)return;let M=_.elements.floating;if(!M)return;
38let B=parseFloat(getComputedStyle(M).scrollPaddingBottom)||0,U=Math.min(Ew,M.childElementCount),X=0,oe=0;for(let L of(N=(R=_.elements.floating)==null?void 0:R.childNodes)!=null?N:[])if(ma(L)){let F=L.offsetTop,V=F+L.clientHeight+B,Z=M.scrollTop,K=Z+M.clientHeight;if(F>=Z&&V<=K)U--;else{oe=Math.max(0,Math.min(V,K)-Math.max(F,Z)),X=L.clientHeight;break}}U>=1&&i(L=>{let F=X*U-oe+B;return L>=F?L:F})}}):null,R2({padding:m,apply({availableWidth:T,availableHeight:R,elements:N}){Object.assign(N.floating.style,{overflow:"auto",maxWidth:`${T}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${R}px)`})}})].filter(Boolean),whileElementsMounted:I2}),[w=g,C=p]=_.placement.split("-");g==="selection"&&(w="selection");let A=x.useMemo(()=>({anchor:[w,C].filter(Boolean).join(" ")}),[w,C]),E=k5(_,{overflowRef:a,onChange:i}),{getReferenceProps:S,getFloatingProps:k}=A5([E]),O=dr(T=>{l(T),y.setFloating(T)});return x.createElement(w_.Provider,{value:n},x.createElement(hh.Provider,{value:{setFloating:O,setReference:y.setReference,styles:v,getReferenceProps:S,getFloatingProps:k,slot:A}},t))}function L5(t){Us(()=>{if(!t)return;let e=new MutationObserver(()=>{let r=window.getComputedStyle(t).maxHeight,n=parseFloat(r);if(isNaN(n))return;let s=parseInt(r);isNaN(s)||n!==s&&(t.style.maxHeight=`${Math.ceil(n)}px`)});return e.observe(t,{attributes:!0,attributeFilter:["style"]}),()=>{e.disconnect()}},[t])}function D5(t,e){var r,n,s;let i=Hg((r=t?.gap)!=null?r:"var(--anchor-gap, 0)",e),a=Hg((n=t?.offset)!=null?n:"var(--anchor-offset, 0)",e),o=Hg((s=t?.padding)!=null?s:"var(--anchor-padding, 0)",e);return{...t,gap:i,offset:a,padding:o}}function Hg(t,e,r=void 0){let n=ch(),s=dr((l,c)=>{if(l==null)return[r,null];if(typeof l=="number")return[l,null];if(typeof l=="string"){if(!c)return[r,null];let u=kw(l,c);return[u,d=>{let h=Sk(l);{let m=h.map(b=>window.getComputedStyle(c).getPropertyValue(b));n.requestAnimationFrame(function b(){n.nextFrame(b);let g=!1;for(let[y,v]of h.entries()){let _=window.getComputedStyle(c).getPropertyValue(v);if(m[y]!==_){m[y]=_,g=!0;break}}if(!g)return;let p=kw(l,c);u!==p&&(d(p),u=p)})}return n.dispose}]}return[r,null]}),i=x.useMemo(()=>s(t,e)[0],[t,e]),[a=i,o]=x.useState();return Us(()=>{let[l,c]=s(t,e);if(o(l),!!c)return c(o)},[t,e]),a}function Sk(t){let e=/var\((.*)\)/.exec(t);if(e){let r=e[1].indexOf(",");if(r===-1)return[e[1]];let n=e[1].slice(0,r).trim(),s=e[1].slice(r+1).trim();return s?[n,...Sk(s)]:[n]}return[]}function kw(t,e){let r=document.createElement("div");e.appendChild(r),r.style.setProperty("margin-top","0px","important"),r.style.setProperty("margin-top",t,"important");let n=parseFloat(window.getComputedStyle(r).marginTop)||0;return e.removeChild(r),n}let hm=x.createContext(null);hm.displayName="OpenClosedContext";var Mi=(t=>(t[t.Open=1]="Open",t[t.Closed=2]="Closed",t[t.Closing=4]="Closing",t[t.Opening=8]="Opening",t))(Mi||{});function fm(){return x.useContext(hm)}function Ck({value:t,children:e}){return _t.createElement(hm.Provider,{value:t},e)}function M5({children:t}){return _t.createElement(hm.Provider,{value:null},t)}function Ak(t){let e=dr(t),r=x.useRef(!1);x.useEffect(()=>(r.current=!1,()=>{r.current=!0,nk(()=>{r.current&&e()})}),[e])}let Ek=x.createContext(!1);function O5(){return x.useContext(Ek)}function yoe(t){return _t.createElement(Ek.Provider,{value:t.force},t.children)}function j5(t){let e=O5(),r=x.useContext(Pk),[n,s]=x.useState(()=>{var i;if(!e&&r!==null)return(i=r.current)!=null?i:null;if(Fo.isServer)return null;let a=t?.getElementById("headlessui-portal-root");if(a)return a;if(t===null)return null;let o=t.createElement("div");return o.setAttribute("id","headlessui-portal-root"),t.body.appendChild(o)});return x.useEffect(()=>{n!==null&&(t!=null&&t.body.contains(n)||t==null||t.body.appendChild(n))},[n,t]),x.useEffect(()=>{e||r!==null&&s(r.current)},[r,s,e]),n}let kk=x.Fragment,$5=ji(function(t,e){let{ownerDocument:r=null,...n}=t,s=x.useRef(null),i=mo(lk(h=>{s.current=h}),e),a=Cv(s.current),o=r??a,l=j5(o),c=x.useContext(Ev),u=ch(),d=bo();return Ak(()=>{var h;l&&l.childNodes.length<=0&&((h=l.parentElement)==null||h.removeChild(l))}),l?up.createPortal(_t.createElement("div",{"data-headlessui-portal":"",ref:h=>{u.dispose(),c&&h&&u.add(c.register(h))}},d({ourProps:{ref:i},theirProps:n,slot:{},defaultTag:kk,name:"Portal"})),l):null});function B5(t,e){let r=mo(e),{enabled:n=!0,ownerDocument:s,...i}=t,a=bo();return n?_t.createElement($5,{...i,ownerDocument:s,ref:r}):a({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:kk,name:"Portal"})}let F5=x.Fragment,Pk=x.createContext(null);function W5(t,e){let{target:r,...n}=t,s={ref:mo(e)},i=bo();return _t.createElement(Pk.Provider,{value:r},i({ourProps:s,theirProps:n,defaultTag:F5,name:"Popover.Group"}))}let Ev=x.createContext(null);function H5(){let t=x.useContext(Ev),e=x.useRef([]),r=dr(i=>(e.current.push(i),t&&t.register(i),()=>
vendor: 4,410 bytes, line 38
38n(i))),n=dr(i=>{let a=e.current.indexOf(i);a!==-1&&e.current.splice(a,1),t&&t.unregister(i)}),s=x.useMemo(()=>({register:r,unregister:n,portals:e}),[r,n,e]);return[e,x.useMemo(()=>function({children:i}){return _t.createElement(Ev.Provider,{value:s},i)},[s])]}let U5=ji(B5),z5=ji(W5),V5=Object.assign(U5,{Group:z5});function G5({defaultContainers:t=[],portals:e,mainTreeNode:r}={}){let n=dr(()=>{var s,i;let a=bu(r),o=[];for(let l of t)l!==null&&(Xl(l)?o.push(l):"current"in l&&Xl(l.current)&&o.push(l.current));if(e!=null&&e.current)for(let l of e.current)o.push(l);for(let l of(s=a?.querySelectorAll("html > *, body > *"))!=null?s:[])l!==document.body&&l!==document.head&&Xl(l)&&l.id!=="headlessui-portal-root"&&(r&&(l.contains(r)||l.contains((i=r?.getRootNode())==null?void 0:i.host))||o.some(c=>l.contains(c))||o.push(l));return o});return{resolveContainers:n,contains:dr(s=>n().some(i=>i.contains(s)))}}let Tk=x.createContext(null);function Rk({children:t,node:e}){let[r,n]=x.useState(null),s=Ik(e??r);return _t.createElement(Tk.Provider,{value:s},t,s===null&&_t.createElement(mp,{features:kd.Hidden,ref:i=>{var a,o;if(i){for(let l of(o=(a=bu(i))==null?void 0:a.querySelectorAll("html > *, body > *"))!=null?o:[])if(l!==document.body&&l!==document.head&&Xl(l)&&l!=null&&l.contains(i)){n(l);break}}}}))}function Ik(t=null){var e;return(e=x.useContext(Tk))!=null?e:t}function q5(){let t=typeof document>"u";return"useSyncExternalStore"in rp?(e=>e.useSyncExternalStore)(rp)(()=>()=>{},()=>!1,()=>!t):!1}function Nk(){let t=q5(),[e,r]=x.useState(Fo.isHandoffComplete);return e&&Fo.isHandoffComplete===!1&&r(!1),x.useEffect(()=>{e!==!0&&r(!0)},[e]),x.useEffect(()=>Fo.handoff(),[]),t?!1:e}function K5(){let t=x.useRef(!1);return Us(()=>(t.current=!0,()=>{t.current=!1}),[]),t}var la=(t=>(t[t.Forwards=0]="Forwards",t[t.Backwards=1]="Backwards",t))(la||{});function Lk(){let t=x.useRef(0);return _k(!0,"keydown",e=>{e.key==="Tab"&&(t.current=e.shiftKey?1:0)},!0),t}function Dk(t){var e;return!!(t.enter||t.enterFrom||t.enterTo||t.leave||t.leaveFrom||t.leaveTo)||!ud((e=t.as)!=null?e:Ok)||_t.Children.count(t.children)===1}let pm=x.createContext(null);pm.displayName="TransitionContext";var Y5=(t=>(t.Visible="visible",t.Hidden="hidden",t))(Y5||{});function X5(){let t=x.useContext(pm);if(t===null)throw new Error("A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.");return t}function J5(){let t=x.useContext(mm);if(t===null)throw new Error("A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.");return t}let mm=x.createContext(null);mm.displayName="NestingContext";function gm(t){return"children"in t?gm(t.children):t.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function Mk(t,e){let r=pa(t),n=x.useRef([]),s=K5(),i=ch(),a=dr((m,b=Ya.Hidden)=>{let g=n.current.findIndex(({el:p})=>p===m);g!==-1&&(Zi(b,{[Ya.Unmount](){n.current.splice(g,1)},[Ya.Hidden](){n.current[g].state="hidden"}}),i.microTask(()=>{var p;!gm(n)&&s.current&&((p=r.current)==null||p.call(r))}))}),o=dr(m=>{let b=n.current.find(({el:g})=>g===m);return b?b.state!=="visible"&&(b.state="visible"):n.current.push({el:m,state:"visible"}),()=>a(m,Ya.Unmount)}),l=x.useRef([]),c=x.useRef(Promise.resolve()),u=x.useRef({enter:[],leave:[]}),d=dr((m,b,g)=>{l.current.splice(0),e&&(e.chains.current[b]=e.chains.current[b].filter(([p])=>p!==m)),e?.chains.current[b].push([m,new Promise(p=>{l.current.push(p)})]),e?.chains.current[b].push([m,new Promise(p=>{Promise.all(u.current[b].map(([y,v])=>v)).then(()=>p())})]),b==="enter"?c.current=c.current.then(()=>e?.wait.current).then(()=>g(b)):g(b)}),h=dr((m,b,g)=>{Promise.all(u.current[b].splice(0).map(([p,y])=>y)).then(()=>{var p;(p=l.current.shift())==null||p()}).then(()=>g(b))});return x.useMemo(()=>({children:n,register:o,unregister:a,onStart:d,onStop:h,wait:c,chains:u}),[o,a,n,d,h,u,c])}let Ok=x.Fragment,jk=nu.RenderStrategy;function Q5(t,e){var r,n;let{transition:s=!0,beforeEnter:i,afterEnter:a,beforeLeave:o,afterLeave:l,enter:c,enterFrom:u,enterTo:d,entered:h,leave:m,leaveFrom:b,leaveTo:g,...p}=t,[y,v]=x.useState(null),_=x.useRef(null),w=Dk(t),C=mo(...w?[_,e,v]:e===null?[]:[e]),A=(r=p.unmount)==null||r?Ya.Unmount:Ya.Hidden,{show:E,appear:S,initial:k}=X5(),[O,T]=x.useState(E?"visible":"hidden"),R=J5(),{register:N,unregister:M}=R;Us(()=>N(_),[N,_]),Us(()=>
38{if(A===Ya.Hidden&&_.current){if(E&&O!=="visible"){T("visible");return}return Zi(O,{hidden:()=>M(_),visible:()=>N(_)})}},[O,_,N,M,E,A]);let B=Nk();Us(()=>{if(w&&B&&O==="visible"&&_.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[_,O,B,w]);let U=k&&!S,X=S&&E&&k,oe=x.useRef(!1),L=Mk(()=>{oe.current||(T("hidden"),M(_))},R),F=dr(Y=>{oe.current=!0;let I=Y?"enter":"leave";L.onStart(_,I,z=>{z==="enter"?i?.():z==="leave"&&o?.()})}),V=dr(Y=>{let I=Y?"enter":"leave";oe.current=!1,L.onStop(_,I,z=>{z==="enter"?a?.():z==="leave"&&l?.()}),I==="leave"&&!gm(L)&&(T("hidden"),M(_))});x.useEffect(()=>{w&&s||(F(E),V(E))},[E,w,s]);let Z=!(!s||!w||!B||U),[,K]=x_(Z,y,E,{start:F,end:V}),ie=Nl({ref:C,className:((n=xv(p.className,X&&c,X&&u,K.enter&&c,K.enter&&K.closed&&u,K.enter&&!K.closed&&d,K.leave&&m,K.leave&&!K.closed&&b,K.leave&&K.closed&&g,!K.transition&&E&&h))==null?void 0:n.trim())||void 0,...__(K)}),se=0;O==="visible"&&(se|=Mi.Open),O==="hidden"&&(se|=Mi.Closed),E&&O==="hidden"&&(se|=Mi.Opening),!E&&O==="visible"&&(se|=Mi.Closing);let fe=bo();return _t.createElement(mm.Provider,{value:L},_t.createElement(Ck,{value:se},fe({ourProps:ie,theirProps:p,defaultTag:Ok,features:jk,visible:O==="visible",name:"Transition.Child"})))}function Z5(t,e){let{show:r,appear:n=!1,unmount:s=!0,...i}=t,a=x.useRef(null),o=Dk(t),l=mo(...o?[a,e]:e===null?[]:[e]);Nk();let c=fm();if(r===void 0&&c!==null&&(r=(c&Mi.Open)===Mi.Open),r===void 0)throw new Error("A <Transition /> is used but it is missing a `show={true | false}` prop.");let[u,d]=x.useState(r?"visible":"hidden"),h=Mk(()=>{r||d("hidden")}),[m,b]=x.useState(!0),g=x.useRef([r]);Us(()=>{m!==!1&&g.current[g.current.length-1]!==r&&(g.current.push(r),b(!1))},[g,r]);let p=x.useMemo(()=>({show:r,appear:n,initial:m}),[r,n,m]);Us(()=>{r?d("visible"):!gm(h)&&a.current!==null&&d("hidden")},[r,h]);let y={unmount:s},v=dr(()=>{var C;m&&b(!1),(C=t.beforeEnter)==null||C.call(t)}),_=dr(()=>{var C;m&&b(!1),(C=t.beforeLeave)==null||C.call(t)}),w=bo();return _t.createElement(mm.Provider,{value:h},_t.createElement(pm.Provider,{value:p},w({ourProps:{...y,as:x.Fragment,children:_t.createElement($k,{ref:l,...y,...i,beforeEnter:v,beforeLeave:_})},theirProps:{},defaultTag:x.Fragment,features:jk,visible:u==="visible",name:"Transition"})))}function e3(t,e){let r=x.useContext(pm)!==null,n=fm()!==null;return _t.createElement(_t.Fragment,null,!r&&n?_t.createElement(kv,{ref:e,...t}):_t.createElement($k,{ref:e,...t}))}let kv=ji(Z5),$k=ji(Q5),t3=ji(e3),r3=Object.assign(kv,{Child:t3,Root:kv});var n3=Object.defineProperty,s3=(t,e,r)=>e in t?n3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pw=(t,e,r)=>(s3(t,typeof e!="symbol"?e+"":e,r),r),Gn=(t=>(t[t.Open=0]="Open",t[t.Closed=1]="Closed",t))(Gn||{}),i3=(t=>(t[t.OpenPopover=0]="OpenPopover",t[t.ClosePopover=1]="ClosePopover",t[t.SetButton=2]="SetButton",t[t.SetButtonId=3]="SetButtonId",t[t.SetPanel=4]="SetPanel",t[t.SetPanelId=5]="SetPanelId",t))(i3||{});let o3={0:t=>t.popoverState===0?t:{...t,popoverState:0,__demoMode:!1},1(t){return t.popoverState===1?t:{...t,popoverState:1,__demoMode:!1}},2(t,e){return t.button===e.button?t:{...t,button:e.button}},3(t,e){return t.buttonId===e.buttonId?t:{...t,buttonId:e.buttonId}},4(t,e){return t.panel===e.panel?t:{...t,panel:e.panel}},5(t,e){return t.panelId===e.panelId?t:{...t,panelId:e.panelId}}};class S_ extends hk{constructor(e){super(e),Pw(this,"actions",{close:()=>this.send({type:1}),refocusableClose:r=>{this.actions.close();let n=r?ma(r)?r:"current"in r&&ma(r.current)?r.current:this.state.button:this.state.button;n?.focus()},open:()=>this.send({type:0}),setButtonId:r=>this.send({type:3,buttonId:r}),setButton:r=>this.send({type:2,button:r}),setPanelId:r=>this.send({type:5,panelId:r}),setPanel:r=>this.send({type:4,panel:r})}),Pw(this,"selectors",{isPortalled:r=>{var n;if(!r.button||!r.panel)return!1;let s=(n=bu(r.button))!=null?n:document;for(let d of s.querySelectorAll("body > *"))if(Number(d?.contains(r.button))^Number(d?.contains(r.panel)))return!0;let i=dm(s),a=i.indexOf(r.button),o=(a+i.length-1)%i.length,l=(a+1)%i.length,c=i[o],u=i[l];
38return!r.panel.contains(c)&&!r.panel.contains(u)}});{let r=this.state.id,n=mk.get(null);this.on(0,()=>n.actions.push(r)),this.on(1,()=>n.actions.pop(r))}}static new({id:e,__demoMode:r=!1}){return new S_({id:e,__demoMode:r,popoverState:r?0:1,buttons:{current:[]},button:null,buttonId:null,panel:null,panelId:null,beforePanelSentinel:{current:null},afterPanelSentinel:{current:null},afterButtonSentinel:{current:null}})}reduce(e,r){return Zi(r.type,o3,e,r)}}const Bk=x.createContext(null);function bm(t){let e=x.useContext(Bk);if(e===null){let r=new Error(`<${t} /> is missing a parent <Popover /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,bm),r}return e}function a3({id:t,__demoMode:e=!1}){let r=x.useMemo(()=>S_.new({id:t,__demoMode:e}),[]);return Ak(()=>r.dispose()),r}let C_=x.createContext(null);C_.displayName="PopoverGroupContext";function Fk(){return x.useContext(C_)}let vm=x.createContext(null);vm.displayName="PopoverPanelContext";function l3(){return x.useContext(vm)}let c3="div";function u3(t,e){var r;let n=x.useId(),{__demoMode:s=!1,...i}=t,a=a3({id:n,__demoMode:s}),o=x.useRef(null),l=mo(e,lk(M=>{o.current=M})),[c,u,d,h,m]=sc(a,x.useCallback(M=>[M.popoverState,M.button,M.panel,M.buttonId,M.panelId],[])),b=qF((r=o.current)!=null?r:u),g=pa(h),p=pa(m),y=x.useMemo(()=>({buttonId:g,panelId:p,close:a.actions.close}),[g,p,a]),v=Fk(),_=v?.registerPopover,w=dr(()=>{var M,B;let U=nc((M=o.current)!=null?M:u);return(B=v?.isFocusWithinPopoverGroup())!=null?B:U&&(u?.contains(U)||d?.contains(U))});x.useEffect(()=>_?.(y),[_,y]);let[C,A]=H5(),E=Ik(u),S=G5({mainTreeNode:E,portals:C,defaultContainers:[{get current(){return a.state.button}},{get current(){return a.state.panel}}]});KF(b,"focus",M=>{var B,U,X,oe,L,F;M.target!==window&&Oc(M.target)&&a.state.popoverState===Gn.Open&&(w()||a.state.button&&a.state.panel&&(S.contains(M.target)||(U=(B=a.state.beforePanelSentinel.current)==null?void 0:B.contains)!=null&&U.call(B,M.target)||(oe=(X=a.state.afterPanelSentinel.current)==null?void 0:X.contains)!=null&&oe.call(X,M.target)||(F=(L=a.state.afterButtonSentinel.current)==null?void 0:L.contains)!=null&&F.call(L,M.target)||a.actions.close()))},!0);let k=c===Gn.Open;GF(k,S.resolveContainers,(M,B)=>{a.actions.close(),vk(B,y_.Loose)||(M.preventDefault(),u?.focus())});let O=uh({open:c===Gn.Open,close:a.actions.refocusableClose}),T=sc(a,x.useCallback(M=>Zi(M.popoverState,{[Gn.Open]:Mi.Open,[Gn.Closed]:Mi.Closed}),[])),R={ref:l},N=bo();return _t.createElement(Rk,{node:E},_t.createElement(N5,null,_t.createElement(vm.Provider,{value:null},_t.createElement(Bk.Provider,{value:a},_t.createElement(ck,{value:a.actions.refocusableClose},_t.createElement(Ck,{value:T},_t.createElement(A,null,N({ourProps:R,theirProps:i,slot:O,defaultTag:c3,name:"Popover"}))))))))}let d3="button";function h3(t,e){let r=x.useId(),{id:n=`headlessui-popover-button-${r}`,disabled:s=!1,autoFocus:i=!1,...a}=t,o=bm("Popover.Button"),[l,c,u,d,h,m,b]=sc(o,x.useCallback(ie=>[ie.popoverState,o.selectors.isPortalled(ie),ie.button,ie.buttonId,ie.panel,ie.panelId,ie.afterButtonSentinel],[])),g=x.useRef(null),p=`headlessui-focus-sentinel-${x.useId()}`,y=Fk(),v=y?.closeOthers,_=l3()!==null;x.useEffect(()=>{if(!_)return o.actions.setButtonId(n),()=>o.actions.setButtonId(null)},[_,n,o]);let[w]=x.useState(()=>Symbol()),C=mo(g,e,T5(),dr(ie=>{if(!_){if(ie)o.state.buttons.current.push(w);else{let se=o.state.buttons.current.indexOf(w);se!==-1&&o.state.buttons.current.splice(se,1)}o.state.buttons.current.length>1&&console.warn("You are already using a <Popover.Button /> but only 1 <Popover.Button /> is supported."),ie&&o.actions.setButton(ie)}})),A=mo(g,e),E=dr(ie=>{var se,fe,Y;if(_){if(o.state.popoverState===Gn.Closed)return;switch(ie.key){case Ua.Space:case Ua.Enter:ie.preventDefault(),(fe=(se=ie.target).click)==null||fe.call(se),o.actions.close(),(Y=o.state.button)==null||Y.focus();break}}else switch(ie.key){case Ua.Space:case Ua.Enter:ie.preventDefault(),ie.stopPropagation(),o.state.popoverState===Gn.Closed?(v?.(o.state.buttonId),o.actions.open()):o.actions.close();break;case Ua.Escape:if(o.state.popoverState!==Gn.Open)return v?.(o.state.buttonId);if(!g.current)return;let I=nc(g.current);if(I&&!g.current.contains(I))return;ie.preventDefault(),ie.stopPropagation(),o.actions.close();break}}),S=dr(ie=>{_||ie.key===Ua.Space&&ie.preventDefault()}),k=dr(ie=>{var se,fe;ok(ie.currentTarget)||s||(_?(o.actions.close(),(se=o.state.button)==null||se.focu
38s()):(ie.preventDefault(),ie.stopPropagation(),o.state.popoverState===Gn.Closed?(v?.(o.state.buttonId),o.actions.open()):o.actions.close(),(fe=o.state.button)==null||fe.focus()))}),O=dr(ie=>{ie.preventDefault(),ie.stopPropagation()}),{isFocusVisible:T,focusProps:R}=JB({autoFocus:i}),{isHovered:N,hoverProps:M}=XB({isDisabled:s}),{pressed:B,pressProps:U}=nF({disabled:s}),X=l===Gn.Open,oe=uh({open:X,active:B||X,disabled:s,hover:N,focus:T,autofocus:i}),L=YF(t,u),F=wv(_?{ref:A,type:L,onKeyDown:E,onClick:k,disabled:s||void 0,autoFocus:i}:{ref:C,id:d,type:L,"aria-expanded":l===Gn.Open,"aria-controls":h?m:void 0,disabled:s||void 0,autoFocus:i,onKeyDown:E,onKeyUp:S,onClick:k,onMouseDown:O},R,M,U),V=Lk(),Z=dr(()=>{if(!ma(o.state.panel))return;let ie=o.state.panel;function se(){Zi(V.current,{[la.Forwards]:()=>Hl(ie,aa.First),[la.Backwards]:()=>Hl(ie,aa.Last)})===gp.Error&&Hl(dm(rc(o.state.button)).filter(fe=>fe.dataset.headlessuiFocusGuard!=="true"),Zi(V.current,{[la.Forwards]:aa.Next,[la.Backwards]:aa.Previous}),{relativeTo:o.state.button})}se()}),K=bo();return _t.createElement(_t.Fragment,null,K({ourProps:F,theirProps:a,slot:oe,defaultTag:d3,name:"Popover.Button"}),X&&!_&&c&&_t.createElement(mp,{id:p,ref:b,features:kd.Focusable,"data-headlessui-focus-guard":!0,as:"button",type:"button",onFocus:Z}))}let f3="div",p3=nu.RenderStrategy|nu.Static;function Wk(t,e){let r=x.useId(),{id:n=`headlessui-popover-backdrop-${r}`,transition:s=!1,...i}=t,a=bm("Popover.Backdrop"),o=sc(a,x.useCallback(y=>y.popoverState,[])),[l,c]=x.useState(null),u=mo(e,c),d=fm(),[h,m]=x_(s,l,d!==null?(d&Mi.Open)===Mi.Open:o===Gn.Open),b=dr(y=>{if(ok(y.currentTarget))return y.preventDefault();a.actions.close()}),g=uh({open:o===Gn.Open}),p={ref:u,id:n,"aria-hidden":!0,onClick:b,...__(m)};return bo()({ourProps:p,theirProps:i,slot:g,defaultTag:f3,features:p3,visible:h,name:"Popover.Backdrop"})}let m3="div",g3=nu.RenderStrategy|nu.Static;function b3(t,e){let r=x.useId(),{id:n=`headlessui-popover-panel-${r}`,focus:s=!1,anchor:i,portal:a=!1,modal:o=!1,transition:l=!1,...c}=t,u=bm("Popover.Panel"),d=sc(u,u.selectors.isPortalled),[h,m,b,g,p]=sc(u,x.useCallback(K=>[K.popoverState,K.button,K.__demoMode,K.beforePanelSentinel,K.afterPanelSentinel],[])),y=`headlessui-focus-sentinel-before-${r}`,v=`headlessui-focus-sentinel-after-${r}`,_=x.useRef(null),w=P5(i),[C,A]=I5(w),E=R5();w&&(a=!0);let[S,k]=x.useState(null),O=mo(_,e,w?C:null,u.actions.setPanel,k),T=Cv(m),R=Cv(_.current);Us(()=>(u.actions.setPanelId(n),()=>u.actions.setPanelId(null)),[n,u]);let N=fm(),[M,B]=x_(l,S,N!==null?(N&Mi.Open)===Mi.Open:h===Gn.Open);jF(M,m,u.actions.close),r5(b?!1:o&&M,R);let U=dr(K=>{var ie;switch(K.key){case Ua.Escape:if(u.state.popoverState!==Gn.Open||!_.current)return;let se=nc(_.current);if(se&&!_.current.contains(se))return;K.preventDefault(),K.stopPropagation(),u.actions.close(),(ie=u.state.button)==null||ie.focus();break}});x.useEffect(()=>{var K;t.static||h===Gn.Closed&&((K=t.unmount)==null||K)&&u.actions.setPanel(null)},[h,t.unmount,t.static,u]),x.useEffect(()=>{if(b||!s||h!==Gn.Open||!_.current)return;let K=nc(_.current);_.current.contains(K)||Hl(_.current,aa.First)},[b,s,_.current,h]);let X=uh({open:h===Gn.Open,close:u.actions.refocusableClose}),oe=wv(w?E():{},{ref:O,id:n,onKeyDown:U,onBlur:s&&h===Gn.Open?K=>{var ie,se,fe,Y,I;let z=K.relatedTarget;z&&_.current&&((ie=_.current)!=null&&ie.contains(z)||(u.actions.close(),((fe=(se=g.current)==null?void 0:se.contains)!=null&&fe.call(se,z)||(I=(Y=p.current)==null?void 0:Y.contains)!=null&&I.call(Y,z))&&z.focus({preventScroll:!0})))}:void 0,tabIndex:-1,style:{...c.style,...A,"--button-width":vF(M,m,!0).width},...__(B)}),L=Lk(),F=dr(()=>{let K=_.current;if(!K)return;function ie(){Zi(L.current,{[la.Forwards]:()=>{var se;Hl(K,aa.First)===gp.Error&&((se=u.state.afterPanelSentinel.current)==null||se.focus())},[la.Backwards]:()=>{var se;(se=u.state.button)==null||se.focus({preventScroll:!0})}})}ie()}),V=dr(()=>{let K=_.current;if(!K)return;function ie(){Zi(L.current,{[la.Forwards]:()=>{var se;if(!u.state.button)return;let fe=(se=rc(u.state.button))!=null?se:document.body,Y=dm(fe),I=Y.indexOf(u.state.button),z=Y.slice(0,I+1),q=[...Y.slice(I+1),...z];for(let ae of q.slice())if(ae.dataset.headlessuiFocusGuard==="true"||S!=null&&S.contains(ae)){let ee=q.indexOf(ae);ee!==-1&&q.splice(ee,1)}Hl(q,aa.First,{sorted:!1})},[la.Backwards]:()=>{var se;Hl(K,aa.Previous)===gp.Error&&((se=u.state.button)==null||se.focu
38s())}})}ie()}),Z=bo();return _t.createElement(M5,null,_t.createElement(vm.Provider,{value:n},_t.createElement(ck,{value:u.actions.refocusableClose},_t.createElement(V5,{enabled:a?t.static||M:!1,ownerDocument:T},M&&d&&_t.createElement(mp,{id:y,ref:g,features:kd.Focusable,"data-headlessui-focus-guard":!0,as:"button",type:"button",onFocus:F}),Z({ourProps:oe,theirProps:c,slot:X,defaultTag:m3,features:g3,visible:M,name:"Popover.Panel"}),M&&d&&_t.createElement(mp,{id:v,ref:p,features:kd.Focusable,"data-headlessui-focus-guard":!0,as:"button",type:"button",onFocus:V})))))}let v3="div";function y3(t,e){let r=x.useRef(null),n=mo(r,e),[s,i]=x.useState([]),a=dr(g=>{i(p=>{let y=p.indexOf(g);if(y!==-1){let v=p.slice();return v.splice(y,1),v}return p})}),o=dr(g=>(i(p=>[...p,g]),()=>a(g))),l=dr(()=>{var g;let p=rc(r.current);if(!p)return!1;let y=nc(r.current);return(g=r.current)!=null&&g.contains(y)?!0:s.some(v=>{var _,w;return((_=p.getElementById(v.buttonId.current))==null?void 0:_.contains(y))||((w=p.getElementById(v.panelId.current))==null?void 0:w.contains(y))})}),c=dr(g=>{for(let p of s)p.buttonId.current!==g&&p.close()}),u=x.useMemo(()=>({registerPopover:o,unregisterPopover:a,isFocusWithinPopoverGroup:l,closeOthers:c}),[o,a,l,c]),d=uh({}),h=t,m={ref:n},b=bo();return _t.createElement(Rk,null,_t.createElement(C_.Provider,{value:u},b({ourProps:m,theirProps:h,slot:d,defaultTag:v3,name:"Popover.Group"})))}let _3=ji(u3),x3=ji(h3),w3=ji(Wk),S3=ji(Wk),C3=ji(b3),A3=ji(y3),Ug=Object.assign(_3,{Button:x3,Backdrop:S3,Overlay:w3,Panel:C3,Group:A3});const E3=t=>({js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",json:"json",html:"html",css:"css",py:"python",java:"java",rb:"ruby",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",php:"php",swift:"swift",md:"plaintext",sh:"bash"})[t]||"typescript";let Pv=[],Hk=[];(()=>{let t="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,r=0;e<t.length;e++)(e%2?Hk:Pv).push(r=r+t[e])})();function k3(t){if(t<768)return!1;for(let e=0,r=Pv.length;;){let n=e+r>>1;if(t<Pv[n])r=n;else if(t>=Hk[n])e=n+1;else return!0;if(e==r)return!1}}function Tw(t){return t>=127462&&t<=127487}const Rw=8205;function P3(t,e,r=!0,n=!0){return(r?Uk:T3)(t,e,n)}function Uk(t,e,r){if(e==t.length)return e;e&&zk(t.charCodeAt(e))&&Vk(t.charCodeAt(e-1))&&e--;let n=zg(t,e);for(e+=Iw(n);e<t.length;){let s=zg(t,e);if(n==Rw||s==Rw||r&&k3(s))e+=Iw(s),n=s;else if(Tw(s)){let i=0,a=e-2;for(;a>=0&&Tw(zg(t,a));)i++,a-=2;if(i%2==0)break;e+=2}else break}return e}function T3(t,e,r){for(;e>0;){let n=Uk(t,e-2,r);if(n<e)return n;e--}return 0}function zg(t,e){let r=t.charCodeAt(e);if(!Vk(r)||e+1==t.length)return r;let n=t.charCodeAt(e+1);return zk(n)?(r-55296<<10)+(n-56320)+65536:r}function zk(t){return t>=56320&&t<57344}function Vk(t){return t>=55296&&t<56320}function Iw(t){return t<65536?1:2}let Mr=class Gk{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,r,n){[e,r]=su(this,e,r);let s=[];return this.decompose(0,e,s,2),n.length&&n.decompose(0,n.length,s,3),this.decompose(r,this.length,s,1),Mo.from(s,this.length-(r-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,r=this.length){[e,r]=su(this,e,r);let n=[];return this.decompose(e,r,n,0),Mo.from(n,r-e)}eq(e){if(e==this)return!0;
vendor: 69,248 bytes, lines 38-44
38if(e.length!=this.length||e.lines!=this.lines)return!1;let r=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),s=new dd(this),i=new dd(e);for(let a=r,o=r;;){if(s.next(a),i.next(a),a=0,s.lineBreak!=i.lineBreak||s.done!=i.done||s.value!=i.value)return!1;if(o+=s.value.length,s.done||o>=n)return!0}}iter(e=1){return new dd(this,e)}iterRange(e,r=this.length){return new qk(this,e,r)}iterLines(e,r){let n;if(e==null)n=this.iter();else{r==null&&(r=this.lines+1);let s=this.line(e).from;n=this.iterRange(s,Math.max(s,r==this.lines+1?this.length:r<=1?0:this.line(r-1).to))}return new Kk(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Gk.empty:e.length<=32?new jn(e):Mo.from(jn.split(e,[]))}};class jn extends Mr{constructor(e,r=R3(e)){super(),this.text=e,this.length=r}get lines(){return this.text.length}get children(){return null}lineInner(e,r,n,s){for(let i=0;;i++){let a=this.text[i],o=s+a.length;if((r?n:o)>=e)return new I3(s,o,n,a);s=o+1,n++}}decompose(e,r,n,s){let i=e<=0&&r>=this.length?this:new jn(Nw(this.text,e,r),Math.min(r,this.length)-Math.max(0,e));if(s&1){let a=n.pop(),o=$f(i.text,a.text.slice(),0,i.length);if(o.length<=32)n.push(new jn(o,a.length+i.length));else{let l=o.length>>1;n.push(new jn(o.slice(0,l)),new jn(o.slice(l)))}}else n.push(i)}replace(e,r,n){if(!(n instanceof jn))return super.replace(e,r,n);[e,r]=su(this,e,r);let s=$f(this.text,$f(n.text,Nw(this.text,0,e)),r),i=this.length+n.length-(r-e);return s.length<=32?new jn(s,i):Mo.from(jn.split(s,[]),i)}sliceString(e,r=this.length,n=` 39`){[e,r]=su(this,e,r);let s="";for(let i=0,a=0;i<=r&&a<this.text.length;a++){let o=this.text[a],l=i+o.length;i>e&&a&&(s+=n),e<l&&r>i&&(s+=o.slice(Math.max(0,e-i),r-i)),i=l+1}return s}flatten(e){for(let r of this.text)e.push(r)}scanIdentical(){return 0}static split(e,r){let n=[],s=-1;for(let i of e)n.push(i),s+=i.length+1,n.length==32&&(r.push(new jn(n,s)),n=[],s=-1);return s>-1&&r.push(new jn(n,s)),r}}class Mo extends Mr{constructor(e,r){super(),this.children=e,this.length=r,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,r,n,s){for(let i=0;;i++){let a=this.children[i],o=s+a.length,l=n+a.lines-1;if((r?l:o)>=e)return a.lineInner(e,r,n,s);s=o+1,n=l+1}}decompose(e,r,n,s){for(let i=0,a=0;a<=r&&i<this.children.length;i++){let o=this.children[i],l=a+o.length;if(e<=l&&r>=a){let c=s&((a<=e?1:0)|(l>=r?2:0));a>=e&&l<=r&&!c?n.push(o):o.decompose(e-a,r-a,n,c)}a=l+1}}replace(e,r,n){if([e,r]=su(this,e,r),n.lines<this.lines)for(let s=0,i=0;s<this.children.length;s++){let a=this.children[s],o=i+a.length;if(e>=i&&r<=o){let l=a.replace(e-i,r-i,n),c=this.lines-a.lines+l.lines;if(l.lines<c>>4&&l.lines>c>>6){let u=this.children.slice();return u[s]=l,new Mo(u,this.length-(r-e)+n.length)}return super.replace(i,o,l)}i=o+1}return super.replace(e,r,n)}sliceString(e,r=this.length,n=` 40`){[e,r]=su(this,e,r);let s="";for(let i=0,a=0;i<this.children.length&&a<=r;i++){let o=this.children[i],l=a+o.length;a>e&&i&&(s+=n),e<l&&r>a&&(s+=o.sliceString(e-a,r-a,n)),a=l+1}return s}flatten(e){for(let r of this.children)r.flatten(e)}scanIdentical(e,r){if(!(e instanceof Mo))return 0;let n=0,[s,i,a,o]=r>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=r,i+=r){if(s==a||i==o)return n;let l=this.children[s],c=e.children[i];if(l!=c)return n+l.scanIdentical(c,r);n+=l.length+1}}static from(e,r=e.reduce((n,s)=>n+s.length+1,-1)){let n=0;for(let m of e)n+=m.lines;if(n<32){let m=[];for(let b of e)b.flatten(m);return new jn(m,r)}let s=Math.max(32,n>>5),i=s<<1,a=s>>1,o=[],l=0,c=-1,u=[];function d(m){let b;if(m.lines>i&&m instanceof Mo)for(let g of m.children)d(g);else m.lines>a&&(l>a||!l)?(h(),o.push(m)):m instanceof jn&&l&&(b=u[u.length-1])instanceof jn&&m.lines+b.lines<=32?(l+=m.lines,c+=m.length+1,u[u.length-1]=new jn(b.text.concat(m.text),b.length+1+m.length)):(l+m.lines>s&&h(),l+=m.lines,c+=m.length+1,u.push(m))}function h(){l!=0&&(o.push(u.length==1?u[0]:Mo.from(u,c)),c=-1,l=u.length=0)}for(let m of e)d(m);return h(),o.length==1?o[0]:new Mo(o,r)}}Mr.empty=new jn([""],0);function R3(t){let e=-1;for(let r of t)e+=r.length+1;return e}function $f(t,e,r=0,n=1e9){for(let s=0,i=0,a=!0;i<t.length&&s<=n;i++){let o=t[i],l=s+o.length;l>=r&&(l>n&&(o=o.slice(0,n-s)),s<r&&(o=o.slice(r-s)),a?(e[e.length-1]+=o,a=!1):e.push(o)),s=l+1}return e}function Nw(t,e,r){return $f(t,[""],e,r)}class dd{constructor(e,r=1){this.dir=r,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[r>0?1:(e instanceof jn?e.text.length:e.children.length)<<1]}nextInner(e,r){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,s=this.nodes[n],i=this.offsets[n],a=i>>1,o=s instanceof jn?s.text.length:s.children.length;if(a==(r>0?o:0)){if(n==0)return this.done=!0,this.value="",this;r>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(r>0?0:1)){if(this.offsets[n]+=r,e==0)return this.lineBreak=!0,this.value=` 41`,this;e--}else if(s instanceof jn){let l=s.text[a+(r<0?-1:0)];if(this.offsets[n]+=r,l.length>Math.max(0,e))return this.value=e==0?l:r>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[a+(r<0?-1:0)];e>l.length?(e-=l.length,this.offsets[n]+=r):(r<0&&this.offsets[n]--,this.nodes.push(l),this.offsets.push(r>0?1:(l instanceof jn?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class qk{constructor(e,r,n){this.value="",this.done=!1,this.cursor=new dd(e,r>n?-1:1),this.pos=r>n?e.length:0,this.from=Math.min(r,n),this.to=Math.max(r,n)}nextInner(e,r){if(r<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,r<0?this.pos-this.to:this.from-this.pos);let n=r<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*r,this.value=s.length<=n?s:r<0?s.slice(s.length-n):s.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Kk{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:r,lineBreak:n,value:s}=this.inner.next(e);return r&&this.afterBreak?(this.value="",this.afterBreak=!1):r?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(Mr.prototype[Symbol.iterator]=function(){return this.iter()},dd.prototype[Symbol.iterator]=qk.prototype[Symbol.iterator]=Kk.prototype[Symbol.iterator]=function(){return this});class I3{constructor(e,r,n,s){this.from=e,this.to=r,this.number=n,this.text=s}get length(){return this.to-this.from}}function su(t,e,r){return e=Math.max(0,Math.min(t.length,e)),[e,Math.max(e,Math.min(t.length,r))]}function ts(t,e,r=!0,n=!0){return P3(t,e,r,n)}function N3(t){return t>=56320&&t<57344}function L3(t){return t>=55296&&t<56320}function lo(t,e){let r=t.charCodeAt(e);if(!L3(r)||e+1==t.length)return r;let n=t.charCodeAt(e+1);return N3(n)?(r-55296<<10)+(n-56320)+65536:r}function A_(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}function na(t){return t<65536?1:2}const Tv=/\r\n?|\n/;var Hs=function(t){return t[t.Simple=0]="Simple",t[t.TrackDel=1]="TrackDel",t[t.TrackBefore=2]="TrackBefore",t[t.TrackAfter=3]="TrackAfter",t}(Hs||(Hs={}));class Wo{constructor(e){this.sections=e}get length(){let e=0;for(let r=0;r<this.sections.length;r+=2)e+=this.sections[r];return e}get newLength(){let e=0;for(let r=0;r<this.sections.length;r+=2){let n=this.sections[r+1];e+=n<0?this.sections[r]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let r=0,n=0,s=0;r<this.sections.length;){let i=this.sections[r++],a=this.sections[r++];a<0?(e(n,s,i),s+=i):s+=a,n+=i}}iterChangedRanges(e,r=!1){Rv(this,e,r)}get invertedDesc(){let e=[];for(let r=0;r<this.sections.length;){let n=this.sections[r++],s=this.sections[r++];s<0?e.push(n,s):e.push(s,n)}return new Wo(e)}composeDesc(e){return this.empty?e:e.empty?this:Yk(this,e)}mapDesc(e,r=!1){return e.empty?this:Iv(this,e,r)}mapPos(e,r=-1,n=Hs.Simple){let s=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],l=this.sections[a++],c=s+o;if(l<0){if(c>e)return i+(e-s);i+=o}else{if(n!=Hs.Simple&&c>=e&&(n==Hs.TrackDel&&s<e&&c>e||n==Hs.TrackBefore&&s<e||n==Hs.TrackAfter&&c>e))return null;if(c>e||c==e&&r<0&&!o)return e==s||r<0?i:i+l;i+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return i}touchesRange(e,r=e){for(let n=0,s=0;n<this.sections.length&&s<=r;){let i=this.sections[n++],a=this.sections[n++],o=s+i;if(a>=0&&s<=r&&o>=e)return s<e&&o>r?"cover":!0;s=o}return!1}toString(){let e="";for(let r=0;r<this.sections.length;){let n=this.sections[r++],s=this.sections[r++];e+=(e?" ":"")+n+(s>=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(r=>typeof r!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Wo(e)}static create(e){return new Wo(e)}}class es extends Wo{constructor(e,r){super(e),this.inserted=r}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Rv(this,(r,n,s,i,a)=>e=e.replace(s,s+(n-r),a),!1),e}mapDesc(e,r=!1){return Iv(this,e,r,!0)}invert(e){let r=this.sections.slice(),n=[];for(let s=0,i=0;s<r.length;s+=2){let a=r[s],o=r[s+1];if(o>=0){r[s]=o,r[s+1]=a;let l=s>>1;for(;n.length<l;)n.push(Mr.empty);n.push(a?e.slice(i,i+a):Mr.empty)}i+=a}return new es(r,n)}compose(e){return this.empty?e:e.empty?this:Yk(this,e,!0)}map(e,r=!1){return e.empty?this:Iv(this,e,r,!0)}iterChanges(e,r=!1){Rv(this,e,r)}get desc(){return Wo.create(this.sections)}filter(e){let r=[],n=[],s=[],i=new Pd(this);e:for(let a=0,o=0;;){let l=a==e.length?1e9:e[a++];for(;o<l||o==l&&i.len==0;){if(i.done)break e;let u=Math.min(i.len,l-o);Fs(s,u,-1);let d=i.ins==-1?-1:i.off==0?i.ins:0;Fs(r,u,d),d>0&&Xa(n,r,i.text),i.forward(u),o+=u}let c=e[a++];for(;o<c;){if(i.done)break e;let u=Math.min(i.len,c-o);Fs(r,u,-1),Fs(s,u,i.ins==-1?-1:i.off==0?i.ins:0),i.forward(u),o+=u}}return{changes:new es(r,n),filtered:Wo.create(s)}}toJSON(){let e=[];for(let r=0;r<this.sections.length;r+=2){let n=this.sections[r],s=this.sections[r+1];s<0?e.push(n):s==0?e.push([n]):e.push([n].concat(this.inserted[r>>1].toJSON()))}return e}static of(e,r,n){let s=[],i=[],a=0,o=null;function l(u=!1){if(!u&&!s.length)return;a<r&&Fs(s,r-a,-1);let d=new es(s,i);o=o?o.compose(d.map(o)):d,s=[],i=[],a=0}function c(u){if(Array.isArray(u))for(let d of u)c(d);else if(u instanceof es){if(u.length!=r)throw new RangeError(`Mismatched change set length (got ${u.length}, expected ${r})`);l(),o=o?o.compose(u.map(o)):u}else{let{from:d,to:h=d,insert:m}=u;if(d>h||d<0||h>r)throw new RangeError(`Invalid change range ${d} to ${h} (in doc of length ${r})`);let b=m?typeof m=="string"?Mr.of(m.split(n||Tv)):m:Mr.empty,g=b.length;if(d==h&&g==0)return;d<a&&l(),d>a&&Fs(s,d-a,-1),Fs(s,h-d,g),Xa(i,s,b),a=h}}return c(e),l(!o),o}static empty(e){return new es(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let r=[],n=[];for(let s=0;s<e.length;s++){let i=e[s];if(typeof i=="number")r.push(i,-1);else{if(!Array.isArray(i)||typeof i[0]!="number"||i.some((a,o)=>o&&typeof a!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(i.length==1)r.push(i[0],0);else{for(;n.length<s;)n.push(Mr.empty);n[s]=Mr.of(i.slice(1)),r.push(i[0],n[s].length)}}}return new es(r,n)}static createSet(e,r){return new es(e,r)}}function Fs(t,e,r,n=!1){if(e==0&&r<=0)return;let s=t.length-2;s>=0&&r<=0&&r==t[s+1]?t[s]+=e:s>=0&&e==0&&t[s]==0?t[s+1]+=r:n?(t[s]+=e,t[s+1]+=r):t.push(e,r)}function Xa(t,e,r){if(r.length==0)return;let n=e.length-2>>1;if(n<t.length)t[t.length-1]=t[t.length-1].append(r);else{for(;t.length<n;)t.push(Mr.empty);t.push(r)}}function Rv(t,e,r){let n=t.inserted;for(let s=0,i=0,a=0;a<t.sections.length;){let o=t.sections[a++],l=t.sections[a++];if(l<0)s+=o,i+=o;else{let c=s,u=i,d=Mr.empty;for(;c+=o,u+=l,l&&n&&(d=d.append(n[a-2>>1])),!(r||a==t.sections.length||t.sections[a+1]<0);)o=t.sections[a++],l=t.sections[a++];e(s,c,i,u,d),s=c,i=u}}}function Iv(t,e,r,n=!1){let s=[],i=n?[]:null,a=new Pd(t),o=new Pd(e);for(let l=-1;;){if(a.done&&o.len||o.done&&a.len)throw new Error("Mismatched change set lengths");if(a.ins==-1&&o.ins==-1){let c=Math.min(a.len,o.len);Fs(s,c,-1),a.forward(c),o.forward(c)}else if(o.ins>=0&&(a.ins<0||l==a.i||a.off==0&&(o.len<a.len||o.len==a.len&&!r))){let c=o.len;for(Fs(s,o.ins,-1);c;){let u=Math.min(a.len,c);a.ins>=0&&l<a.i&&a.len<=u&&(Fs(s,0,a.ins),i&&Xa(i,s,a.text),l=a.i),a.forward(u),c-=u}o.next()}else if(a.ins>=0){let c=0,u=a.len;for(;u;)if(o.ins==-1){let d=Math.min(u,o.len);c+=d,u-=d,o.forward(d)}else if(o.ins==0&&o.len<u)u-=o.len,o.next();else break;Fs(s,c,l<a.i?a.ins:0),i&&l<a.i&&Xa(i,s,a.text),l=a.i,a.forward(a.len-u)}else{if(a.done&&o.done)return i?es.createSet(s,i):Wo.create(s);throw new Error("Mismatched change set lengths")}}}function Yk(t,e,r=!1){let n=[],s=r?[]:null,i=new Pd(t),a=new Pd(e);for(let o=!1;;){if(i.done&&a.done)return s?es.createSet(n,s):Wo.create(n);if(i.ins==0)Fs(n,i.len,0,o),i.next();else if(a.len==0&&!a.done)Fs(n,0,a.ins,o),s&&Xa(s,n,a.text),a.next();else{if(i.done||a.done)throw new Error("Mismatched change set lengths");{let l=Math.min(i.len2,a.len),c=n.length;if(i.ins==-1){let u=a.ins==-1?-1:a.off?0:a.ins;Fs(n,l,u,o),s&&u&&Xa(s,n,a.text)}else a.ins==-1?(Fs(n,i.off?0:i.len,l,o),s&&Xa(s,n,i.textBit(l))):(Fs(n,i.off?0:i.len,a.off?0:a.ins,o),s&&!a.off&&Xa(s,n,a.text));o=(i.ins>l||a.ins>=0&&a.len>l)&&(o||n.length>c),i.forward2(l),a.forward(l)}}}}class Pd{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,r=this.i-2>>1;return r>=e.length?Mr.empty:e[r]}textBit(e){let{inserted:r}=this.set,n=this.i-2>>1;return n>=r.length&&!e?Mr.empty:r[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class zl{constructor(e,r,n){this.from=e,this.to=r,this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,r=-1){let n,s;return this.empty?n=s=e.mapPos(this.from,r):(n=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),n==this.from&&s==this.to?this:new zl(n,s,this.flags)}extend(e,r=e){if(e<=this.anchor&&r>=this.anchor)return ke.range(e,r);let n=Math.abs(e-this.anchor)>Math.abs(r-this.anchor)?e:r;return ke.range(this.anchor,n)}eq(e,r=!1){return this.anchor==e.anchor&&this.head==e.head&&(!r||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return ke.range(e.anchor,e.head)}static create(e,r,n){return new zl(e,r,n)}}class ke{constructor(e,r){this.ranges=e,this.mainIndex=r}map(e,r=-1){return e.empty?this:ke.create(this.ranges.map(n=>n.map(e,r)),this.mainIndex)}eq(e,r=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],r))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new ke([this.main],0)}addRange(e,r=!0){return ke.create([e].concat(this.ranges),r?0:this.mainIndex+1)}replaceRange(e,r=this.mainIndex){let n=this.ranges.slice();return n[r]=e,ke.create(n,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new ke(e.ranges.map(r=>zl.fromJSON(r)),e.main)}static single(e,r=e){return new ke([ke.range(e,r)],0)}static create(e,r=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,s=0;s<e.length;s++){let i=e[s];if(i.empty?i.from<=n:i.from<n)return ke.normalized(e.slice(),r);n=i.to}return new ke(e,r)}static cursor(e,r=0,n,s){return zl.create(e,e,(r==0?0:r<0?8:16)|(n==null?7:Math.min(6,n))|(s??16777215)<<6)}static range(e,r,n,s){let i=(n??16777215)<<6|(s==null?7:Math.min(6,s));return r<e?zl.create(r,e,48|i):zl.create(e,r,(r>e?8:0)|i)}static normalized(e,r=0){let n=e[r];e.sort((s,i)=>s.from-i.from),r=e.indexOf(n);for(let s=1;s<e.length;s++){let i=e[s],a=e[s-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,l=Math.max(i.to,a.to);s<=r&&r--,e.splice(--s,2,i.anchor>i.head?ke.range(l,o):ke.range(o,l))}}return new ke(e,r)}}function Xk(t,e){for(let r of t.ranges)if(r.to>e)throw new RangeError("Selection points outside of document")}let E_=0;class it{constructor(e,r,n,s,i){this.combine=e,this.compareInput=r,this.compare=n,this.isStatic=s,this.id=E_++,this.default=e([]),this.extensions=typeof i=="function"?i(this):i}get reader(){return this}static define(e={}){return new it(e.combine||(r=>r),e.compareInput||((r,n)=>r===n),e.compare||(e.combine?(r,n)=>r===n:k_),!!e.static,e.enables)}of(e){return new Bf([],this,0,e)}compute(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new Bf(e,this,1,r)}computeN(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new Bf(e,this,2,r)}from(e,r){return r||(r=n=>n),this.compute([e],n=>r(n.field(e)))}}function k_(t,e){return t==e||t.length==e.length&&t.every((r,n)=>r===e[n])}class Bf{constructor(e,r,n,s){this.dependencies=e,this.facet=r,this.type=n,this.value=s,this.id=E_++}dynamicSlot(e){var r;let n=this.value,s=this.facet.compareInput,i=this.id,a=e[i]>>1,o=this.type==2,l=!1,c=!1,u=[];for(let d of this.dependencies)d=="doc"?l=!0:d=="selection"?c=!0:((r=e[d.id])!==null&&r!==void 0?r:1)&1||u.push(e[d.id]);return{create(d){return d.values[a]=n(d),1},update(d,h){if(l&&h.docChanged||c&&(h.docChanged||h.selection)||Nv(d,u)){let m=n(d);if(o?!Lw(m,d.values[a],s):!s(m,d.values[a]))return d.values[a]=m,1}return 0},reconfigure:(d,h)=>{let m,b=h.config.address[i];if(b!=null){let g=vp(h,b);if(this.dependencies.every(p=>p instanceof it?h.facet(p)===d.facet(p):p instanceof gs?h.field(p,!1)==d.field(p,!1):!0)||(o?Lw(m=n(d),g,s):s(m=n(d),g)))return d.values[a]=g,0}else m=n(d);return d.values[a]=m,1}}}}function Lw(t,e,r){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!r(t[n],e[n]))return!1;return!0}function Nv(t,e){let r=!1;for(let n of e)hd(t,n)&1&&(r=!0);return r}function D3(t,e,r){let n=r.map(l=>t[l.id]),s=r.map(l=>l.type),i=n.filter(l=>!(l&1)),a=t[e.id]>>1;function o(l){let c=[];for(let u=0;u<n.length;u++){let d=vp(l,n[u]);if(s[u]==2)for(let h of d)c.push(h);else c.push(d)}return e.combine(c)}return{create(l){for(let c of n)hd(l,c);return l.values[a]=o(l),1},update(l,c){if(!Nv(l,i))return 0;let u=o(l);return e.compare(u,l.values[a])?0:(l.values[a]=u,1)},reconfigure(l,c){let u=Nv(l,n),d=c.config.facets[e.id],h=c.facet(e);if(d&&!u&&k_(r,d))return l.values[a]=h,0;let m=o(l);return e.compare(m,h)?(l.values[a]=h,0):(l.values[a]=m,1)}}}const Zh=it.define({static:!0});class gs{constructor(e,r,n,s,i){this.id=e,this.createF=r,this.updateF=n,this.compareF=s,this.spec=i,this.provides=void 0}static define(e){let r=new gs(E_++,e.create,e.update,e.compare||((n,s)=>n===s),e);return e.provide&&(r.provides=e.provide(r)),r}create(e){let r=e.facet(Zh).find(n=>n.field==this);return(r?.create||this.createF)(e)}slot(e){let r=e[this.id]>>1;return{create:n=>(n.values[r]=this.create(n),1),update:(n,s)=>{let i=n.values[r],a=this.updateF(i,s);return this.compareF(i,a)?0:(n.values[r]=a,1)},reconfigure:(n,s)=>{let i=n.facet(Zh),a=s.facet(Zh),o;return(o=i.find(l=>l.field==this))&&o!=a.find(l=>l.field==this)?(n.values[r]=o.create(n),1):s.config.address[this.id]!=null?(n.values[r]=s.field(this),0):(n.values[r]=this.create(n),1)}}}init(e){return[this,Zh.of({field:this,create:e})]}get extension(){return this}}const Ol={lowest:4,low:3,default:2,high:1,highest:0};function Bu(t){return e=>new Jk(e,t)}const ul={highest:Bu(Ol.highest),high:Bu(Ol.high),default:Bu(Ol.default),low:Bu(Ol.low),lowest:Bu(Ol.lowest)};class Jk{constructor(e,r){this.inner=e,this.prec=r}}class ic{of(e){return new Lv(this,e)}reconfigure(e){return ic.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Lv{constructor(e,r){this.compartment=e,this.inner=r}}class bp{constructor(e,r,n,s,i,a){for(this.base=e,this.compartments=r,this.dynamicSlots=n,this.address=s,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let r=this.address[e.id];return r==null?e.default:this.staticValues[r>>1]}static resolve(e,r,n){let s=[],i=Object.create(null),a=new Map;for(let h of M3(e,r,a))h instanceof gs?s.push(h):(i[h.facet.id]||(i[h.facet.id]=[])).push(h);let o=Object.create(null),l=[],c=[];for(let h of s)o[h.id]=c.length<<1,c.push(m=>h.slot(m));let u=n?.config.facets;for(let h in i){let m=i[h],b=m[0].facet,g=u&&u[h]||[];if(m.every(p=>p.type==0))if(o[b.id]=l.length<<1|1,k_(g,m))l.push(n.facet(b));else{let p=b.combine(m.map(y=>y.value));l.push(n&&b.compare(p,n.facet(b))?n.facet(b):p)}else{for(let p of m)p.type==0?(o[p.id]=l.length<<1|1,l.push(p.value)):(o[p.id]=c.length<<1,c.push(y=>p.dynamicSlot(y)));o[b.id]=c.length<<1,c.push(p=>D3(p,b,m))}}let d=c.map(h=>h(o));return new bp(e,a,d,o,l,i)}}function M3(t,e,r){let n=[[],[],[],[],[]],s=new Map;function i(a,o){let l=s.get(a);if(l!=null){if(l<=o)return;let c=n[l].indexOf(a);c>-1&&n[l].splice(c,1),a instanceof Lv&&r.delete(a.compartment)}if(s.set(a,o),Array.isArray(a))for(let c of a)i(c,o);else if(a instanceof Lv){if(r.has(a.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(a.compartment)||a.inner;r.set(a.compartment,c),i(c,o)}else if(a instanceof Jk)i(a.inner,a.prec);else if(a instanceof gs)n[o].push(a),a.provides&&i(a.provides,o);else if(a instanceof Bf)n[o].push(a),a.facet.extensions&&i(a.facet.extensions,Ol.default);else{let c=a.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${a}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);i(c,o)}}return i(t,Ol.default),n.reduce((a,o)=>a.concat(o))}function hd(t,e){if(e&1)return 2;let r=e>>1,n=t.status[r];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;t.status[r]=4;let s=t.computeSlot(t,t.config.dynamicSlots[r]);return t.status[r]=2|s}function vp(t,e){return e&1?t.config.staticValues[e>>1]:t.values[e>>1]}const Qk=it.define(),Dv=it.define({combine:t=>t.some(e=>e),static:!0}),Zk=it.define({combine:t=>t.length?t[0]:void 0,static:!0}),eP=it.define(),tP=it.define(),rP=it.define(),nP=it.define({combine:t=>t.length?t[0]:!1});class xa{constructor(e,r){this.type=e,this.value=r}static define(){return new O3}}class O3{of(e){return new xa(this,e)}}class j3{constructor(e){this.map=e}of(e){return new sr(this,e)}}class sr{constructor(e,r){this.type=e,this.value=r}map(e){let r=this.type.map(this.value,e);return r===void 0?void 0:r==this.value?this:new sr(this.type,r)}is(e){return this.type==e}static define(e={}){return new j3(e.map||(r=>r))}static mapEffects(e,r){if(!e.length)return e;let n=[];for(let s of e){let i=s.map(r);i&&n.push(i)}return n}}sr.reconfigure=sr.define();sr.appendConfig=sr.define();class qn{constructor(e,r,n,s,i,a){this.startState=e,this.changes=r,this.selection=n,this.effects=s,this.annotations=i,this.scrollIntoView=a,this._doc=null,this._state=null,n&&Xk(n,r.newLength),i.some(o=>o.type==qn.time)||(this.annotations=i.concat(qn.time.of(Date.now())))}static create(e,r,n,s,i,a){return new qn(e,r,n,s,i,a)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let r of this.annotations)if(r.type==e)return r.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let r=this.annotation(qn.userEvent);return!!(r&&(r==e||r.length>e.length&&r.slice(0,e.length)==e&&r[e.length]=="."))}}qn.time=xa.define();qn.userEvent=xa.define();qn.addToHistory=xa.define();qn.remote=xa.define();function $3(t,e){let r=[];for(let n=0,s=0;;){let i,a;if(n<t.length&&(s==e.length||e[s]>=t[n]))i=t[n++],a=t[n++];else if(s<e.length)i=e[s++],a=e[s++];else return r;!r.length||r[r.length-1]<i?r.push(i,a):r[r.length-1]<a&&(r[r.length-1]=a)}}function sP(t,e,r){var n;let s,i,a;return r?(s=e.changes,i=es.empty(e.changes.length),a=t.changes.compose(e.changes)):(s=e.changes.map(t.changes),i=t.changes.mapDesc(e.changes,!0),a=t.changes.compose(s)),{changes:a,selection:e.selection?e.selection.map(i):(n=t.selection)===null||n===void 0?void 0:n.map(s),effects:sr.mapEffects(t.effects,s).concat(sr.mapEffects(e.effects,i)),annotations:t.annotations.length?t.annotations.concat(e.annotations):e.annotations,scrollIntoView:t.scrollIntoView||e.scrollIntoView}}function Mv(t,e,r){let n=e.selection,s=Gc(e.annotations);return e.userEvent&&(s=s.concat(qn.userEvent.of(e.userEvent))),{changes:e.changes instanceof es?e.changes:es.of(e.changes||[],r,t.facet(Zk)),selection:n&&(n instanceof ke?n:ke.single(n.anchor,n.head)),effects:Gc(e.effects),annotations:s,scrollIntoView:!!e.scrollIntoView}}function iP(t,e,r){let n=Mv(t,e.length?e[0]:{},t.doc.length);e.length&&e[0].filter===!1&&(r=!1);for(let i=1;i<e.length;i++){e[i].filter===!1&&(r=!1);let a=!!e[i].sequential;n=sP(n,Mv(t,e[i],a?n.changes.newLength:t.doc.length),a)}let s=qn.create(t,n.changes,n.selection,n.effects,n.annotations,n.scrollIntoView);return F3(r?B3(s):s)}function B3(t){let e=t.startState,r=!0;for(let s of e.facet(eP)){let i=s(t);if(i===!1){r=!1;break}Array.isArray(i)&&(r=r===!0?i:$3(r,i))}if(r!==!0){let s,i;if(r===!1)i=t.changes.invertedDesc,s=es.empty(e.doc.length);else{let a=t.changes.filter(r);s=a.changes,i=a.filtered.mapDesc(a.changes).invertedDesc}t=qn.create(e,s,t.selection&&t.selection.map(i),sr.mapEffects(t.effects,i),t.annotations,t.scrollIntoView)}let n=e.facet(tP);for(let s=n.length-1;s>=0;s--){let i=n[s](t);i instanceof qn?t=i:Array.isArray(i)&&i.length==1&&i[0]instanceof qn?t=i[0]:t=iP(e,Gc(i),!1)}return t}function F3(t){let e=t.startState,r=e.facet(rP),n=t;for(let s=r.length-1;s>=0;s--){let i=r[s](t);i&&Object.keys(i).length&&(n=sP(n,Mv(e,i,t.changes.newLength),!0))}return n==t?t:qn.create(e,t.changes,t.selection,n.effects,n.annotations,n.scrollIntoView)}const W3=[];function Gc(t){return t==null?W3:Array.isArray(t)?t:[t]}var Kn=function(t){return t[t.Word=0]="Word",t[t.Space=1]="Space",t[t.Other=2]="Other",t}(Kn||(Kn={}));const H3=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Ov;try{Ov=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function U3(t){if(Ov)return Ov.test(t);for(let e=0;e<t.length;e++){let r=t[e];if(/\w/.test(r)||r>"Â"&&(r.toUpperCase()!=r.toLowerCase()||H3.test(r)))return!0}return!1}function z3(t){return e=>{if(!/\S/.test(e))return Kn.Space;if(U3(e))return Kn.Word;for(let r=0;r<t.length;r++)if(e.indexOf(t[r])>-1)return Kn.Word;return Kn.Other}}class Cr{constructor(e,r,n,s,i,a){this.config=e,this.doc=r,this.selection=n,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let o=0;o<this.config.dynamicSlots.length;o++)hd(this,o<<1);this.computeSlot=null}field(e,r=!0){let n=this.config.address[e.id];if(n==null){if(r)throw new RangeError("Field is not present in this state");return}return hd(this,n),vp(this,n)}update(...e){return iP(this,e,!0)}applyTransaction(e){let r=this.config,{base:n,compartments:s}=r;for(let o of e.effects)o.is(ic.reconfigure)?(r&&(s=new Map,r.compartments.forEach((l,c)=>s.set(c,l)),r=null),s.set(o.value.compartment,o.value.extension)):o.is(sr.reconfigure)?(r=null,n=o.value):o.is(sr.appendConfig)&&(r=null,n=Gc(n).concat(o.value));let i;r?i=e.startState.values.slice():(r=bp.resolve(n,s,this),i=new Cr(r,this.doc,this.selection,r.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let a=e.startState.facet(Dv)?e.newSelection:e.newSelection.asSingle();new Cr(r,e.newDoc,a,i,(o,l)=>l.update(o,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:e},range:ke.cursor(r.from+e.length)}))}changeByRange(e){let r=this.selection,n=e(r.ranges[0]),s=this.changes(n.changes),i=[n.range],a=Gc(n.effects);for(let o=1;o<r.ranges.length;o++){let l=e(r.ranges[o]),c=this.changes(l.changes),u=c.map(s);for(let h=0;h<o;h++)i[h]=i[h].map(u);let d=s.mapDesc(c,!0);i.push(l.range.map(d)),s=s.compose(u),a=sr.mapEffects(a,u).concat(sr.mapEffects(Gc(l.effects),d))}return{changes:s,selection:ke.create(i,r.mainIndex),effects:a}}changes(e=[]){return e instanceof es?e:es.of(e,this.doc.length,this.facet(Cr.lineSeparator))}toText(e){return Mr.of(e.split(this.facet(Cr.lineSeparator)||Tv))}sliceDoc(e=0,r=this.doc.length){return this.doc.sliceString(e,r,this.lineBreak)}facet(e){let r=this.config.address[e.id];return r==null?e.default:(hd(this,r),vp(this,r))}toJSON(e){let r={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let s=e[n];s instanceof gs&&this.config.address[s.id]!=null&&(r[n]=s.spec.toJSON(this.field(e[n]),this))}return r}static fromJSON(e,r={},n){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let s=[];if(n){for(let i in n)if(Object.prototype.hasOwnProperty.call(e,i)){let a=n[i],o=e[i];s.push(a.init(l=>a.spec.fromJSON(o,l)))}}return Cr.create({doc:e.doc,selection:ke.fromJSON(e.selection),extensions:r.extensions?s.concat([r.extensions]):s})}static create(e={}){let r=bp.resolve(e.extensions||[],new Map),n=e.doc instanceof Mr?e.doc:Mr.of((e.doc||"").split(r.staticFacet(Cr.lineSeparator)||Tv)),s=e.selection?e.selection instanceof ke?e.selection:ke.single(e.selection.anchor,e.selection.head):ke.single(0);return Xk(s,n.length),r.staticFacet(Dv)||(s=s.asSingle()),new Cr(r,n,s,r.dynamicSlots.map(()=>null),(i,a)=>a.create(i),null)}get tabSize(){return this.facet(Cr.tabSize)}get lineBreak(){return this.facet(Cr.lineSeparator)||` 42`}get readOnly(){return this.facet(nP)}phrase(e,...r){for(let n of this.facet(Cr.phrases))if(Object.prototype.hasOwnProperty.call(n,e)){e=n[e];break}return r.length&&(e=e.replace(/\$(\$|\d*)/g,(n,s)=>{if(s=="$")return"$";let i=+(s||1);return!i||i>r.length?n:r[i-1]})),e}languageDataAt(e,r,n=-1){let s=[];for(let i of this.facet(Qk))for(let a of i(this,r,n))Object.prototype.hasOwnProperty.call(a,e)&&s.push(a[e]);return s}charCategorizer(e){return z3(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:r,from:n,length:s}=this.doc.lineAt(e),i=this.charCategorizer(e),a=e-n,o=e-n;for(;a>0;){let l=ts(r,a,!1);if(i(r.slice(l,a))!=Kn.Word)break;a=l}for(;o<s;){let l=ts(r,o);if(i(r.slice(o,l))!=Kn.Word)break;o=l}return a==o?null:ke.range(a+n,o+n)}}Cr.allowMultipleSelections=Dv;Cr.tabSize=it.define({combine:t=>t.length?t[0]:4});Cr.lineSeparator=Zk;Cr.readOnly=nP;Cr.phrases=it.define({compare(t,e){let r=Object.keys(t),n=Object.keys(e);return r.length==n.length&&r.every(s=>t[s]==e[s])}});Cr.languageData=Qk;Cr.changeFilter=eP;Cr.transactionFilter=tP;Cr.transactionExtender=rP;ic.reconfigure=sr.define();function uc(t,e,r={}){let n={};for(let s of t)for(let i of Object.keys(s)){let a=s[i],o=n[i];if(o===void 0)n[i]=a;else if(!(o===a||a===void 0))if(Object.hasOwnProperty.call(r,i))n[i]=r[i](o,a);else throw new Error("Config merge conflict for field "+i)}for(let s in e)n[s]===void 0&&(n[s]=e[s]);return n}class rl{eq(e){return this==e}range(e,r=e){return jv.create(e,r,this)}}rl.prototype.startSide=rl.prototype.endSide=0;rl.prototype.point=!1;rl.prototype.mapMode=Hs.TrackDel;let jv=class oP{constructor(e,r,n){this.from=e,this.to=r,this.value=n}static create(e,r,n){return new oP(e,r,n)}};function $v(t,e){return t.from-e.from||t.value.startSide-e.value.startSide}class P_{constructor(e,r,n,s){this.from=e,this.to=r,this.value=n,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,r,n,s=0){let i=n?this.to:this.from;for(let a=s,o=i.length;;){if(a==o)return a;let l=a+o>>1,c=i[l]-e||(n?this.value[l].endSide:this.value[l].startSide)-r;if(l==a)return c>=0?a:o;c>=0?o=l:a=l+1}}between(e,r,n,s){for(let i=this.findIndex(r,-1e9,!0),a=this.findIndex(n,1e9,!1,i);i<a;i++)if(s(this.from[i]+e,this.to[i]+e,this.value[i])===!1)return!1}map(e,r){let n=[],s=[],i=[],a=-1,o=-1;for(let l=0;l<this.value.length;l++){let c=this.value[l],u=this.from[l]+e,d=this.to[l]+e,h,m;if(u==d){let b=r.mapPos(u,c.startSide,c.mapMode);if(b==null||(h=m=b,c.startSide!=c.endSide&&(m=r.mapPos(u,c.endSide),m<h)))continue}else if(h=r.mapPos(u,c.startSide),m=r.mapPos(d,c.endSide),h>m||h==m&&c.startSide>0&&c.endSide<=0)continue;(m-h||c.endSide-c.startSide)<0||(a<0&&(a=h),c.point&&(o=Math.max(o,m-h)),n.push(c),s.push(h-a),i.push(m-a))}return{mapped:n.length?new P_(s,i,n,o):null,pos:a}}}class gr{constructor(e,r,n,s){this.chunkPos=e,this.chunk=r,this.nextLayer=n,this.maxPoint=s}static create(e,r,n,s){return new gr(e,r,n,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let r of this.chunk)e+=r.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:r=[],sort:n=!1,filterFrom:s=0,filterTo:i=this.length}=e,a=e.filter;if(r.length==0&&!a)return this;if(n&&(r=r.slice().sort($v)),this.isEmpty)return r.length?gr.of(r):this;let o=new aP(this,null,-1).goto(0),l=0,c=[],u=new oc;for(;o.value||l<r.length;)if(l<r.length&&(o.from-r[l].from||o.startSide-r[l].value.startSide)>=0){let d=r[l++];u.addInner(d.from,d.to,d.value)||c.push(d)}else o.rangeIndex==1&&o.chunkIndex<this.chunk.length&&(l==r.length||this.chunkEnd(o.chunkIndex)<r[l].from)&&(!a||s>this.chunkEnd(o.chunkIndex)||i<this.chunkPos[o.chunkIndex])&&u.addChunk(this.chunkPos[o.chunkIndex],this.chunk[o.chunkIndex])?o.nextChunk():((!a||s>o.to||i<o.from||a(o.from,o.to,o.value))&&(u.addInner(o.from,o.to,o.value)||c.push(jv.create(o.from,o.to,o.value))),o.next());return u.finishInner(this.nextLayer.isEmpty&&!c.length?gr.empty:this.nextLayer.update({add:c,filter:a,filterFrom:s,filterTo:i}))}map(e){if(e.empty||this.isEmpty)return this;let r=[],n=[],s=-1;for(let a=0;a<this.chunk.length;a++){let o=this.chunkPos[a],l=this.chunk[a],c=e.touchesRange(o,o+l.length);if(c===!1)s=Math.max(s,l.maxPoint),r.push(l),n.push(e.mapPos(o));else if(c===!0){let{mapped:u,pos:d}=l.map(o,e);u&&(s=Math.max(s,u.maxPoint),r.push(u),n.push(d))}}let i=this.nextLayer.map(e);return r.length==0?i:new gr(n,r,i||gr.empty,s)}between(e,r,n){if(!this.isEmpty){for(let s=0;s<this.chunk.length;s++){let i=this.chunkPos[s],a=this.chunk[s];if(r>=i&&e<=i+a.length&&a.between(i,e-i,r-i,n)===!1)return}this.nextLayer.between(e,r,n)}}iter(e=0){return Td.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,r=0){return Td.from(e).goto(r)}static compare(e,r,n,s,i=-1){let a=e.filter(d=>d.maxPoint>0||!d.isEmpty&&d.maxPoint>=i),o=r.filter(d=>d.maxPoint>0||!d.isEmpty&&d.maxPoint>=i),l=Dw(a,o,n),c=new Fu(a,l,i),u=new Fu(o,l,i);n.iterGaps((d,h,m)=>Mw(c,d,u,h,m,s)),n.empty&&n.length==0&&Mw(c,0,u,0,0,s)}static eq(e,r,n=0,s){s==null&&(s=999999999);let i=e.filter(u=>!u.isEmpty&&r.indexOf(u)<0),a=r.filter(u=>!u.isEmpty&&e.indexOf(u)<0);if(i.length!=a.length)return!1;if(!i.length)return!0;let o=Dw(i,a),l=new Fu(i,o,0).goto(n),c=new Fu(a,o,0).goto(n);for(;;){if(l.to!=c.to||!Bv(l.active,c.active)||l.point&&(!c.point||!l.point.eq(c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,r,n,s,i=-1){let a=new Fu(e,null,i).goto(r),o=r,l=a.openStart;for(;;){let c=Math.min(a.to,n);if(a.point){let u=a.activeForPoint(a.to),d=a.pointFrom<r?u.length+1:a.point.startSide<0?u.length:Math.min(u.length,l);s.point(o,c,a.point,u,d,a.pointRank),l=Math.min(a.openEnd(c),u.length)}else c>o&&(s.span(o,c,a.active,l),l=a.openEnd(c));if(a.to>n)return l+(a.point&&a.to>n?1:0);o=a.to,a.next()}}static of(e,r=!1){let n=new oc;for(let s of e instanceof jv?[e]:r?V3(e):e)n.add(s.from,s.to,s.value);return n.finish()}static join(e){if(!e.length)return gr.empty;let r=e[e.length-1];for(let n=e.length-2;n>=0;n--)for(let s=e[n];s!=gr.empty;s=s.nextLayer)r=new gr(s.chunkPos,s.chunk,r,Math.max(s.maxPoint,r.maxPoint));return r}}gr.empty=new gr([],[],null,-1);function V3(t){if(t.length>1)for(let e=t[0],r=1;r<t.length;r++){let n=t[r];if($v(e,n)>0)return t.slice().sort($v);e=n}return t}gr.empty.nextLayer=gr.empty;class oc{finishChunk(e){this.chunks.push(new P_(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,r,n){this.addInner(e,r,n)||(this.nextLayer||(this.nextLayer=new oc)).add(e,r,n)}addInner(e,r,n){let s=e-this.lastTo||n.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(r-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=r,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,r-e)),!0)}addChunk(e,r){if((e-this.lastTo||r.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,r.maxPoint),this.chunks.push(r),this.chunkPos.push(e);let n=r.value.length-1;return this.last=r.value[n],this.lastFrom=r.from[n]+e,this.lastTo=r.to[n]+e,!0}finish(){return this.finishInner(gr.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let r=gr.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,r}}function Dw(t,e,r){let n=new Map;for(let i of t)for(let a=0;a<i.chunk.length;a++)i.chunk[a].maxPoint<=0&&n.set(i.chunk[a],i.chunkPos[a]);let s=new Set;for(let i of e)for(let a=0;a<i.chunk.length;a++){let o=n.get(i.chunk[a]);o!=null&&(r?r.mapPos(o):o)==i.chunkPos[a]&&!r?.touchesRange(o,o+i.chunk[a].length)&&s.add(i.chunk[a])}return s}class aP{constructor(e,r,n,s=0){this.layer=e,this.skip=r,this.minPoint=n,this.rank=s}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,r=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,r,!1),this}gotoInner(e,r,n){for(;this.chunkIndex<this.layer.chunk.length;){let s=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(s)||this.layer.chunkEnd(this.chunkIndex)<e||s.maxPoint<this.minPoint))break;this.chunkIndex++,n=!1}if(this.chunkIndex<this.layer.chunk.length){let s=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],r,!0);(!n||this.rangeIndex<s)&&this.setRangeIndex(s)}this.next()}forward(e,r){(this.to-e||this.endSide-r)<0&&this.gotoInner(e,r,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],r=this.layer.chunk[this.chunkIndex],n=e+r.from[this.rangeIndex];if(this.from=n,this.to=e+r.to[this.rangeIndex],this.value=r.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}}class Td{constructor(e){this.heap=e}static from(e,r=null,n=-1){let s=[];for(let i=0;i<e.length;i++)for(let a=e[i];!a.isEmpty;a=a.nextLayer)a.maxPoint>=n&&s.push(new aP(a,r,n,i));return s.length==1?s[0]:new Td(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,r=-1e9){for(let n of this.heap)n.goto(e,r);for(let n=this.heap.length>>1;n>=0;n--)Vg(this.heap,n);return this.next(),this}forward(e,r){for(let n of this.heap)n.forward(e,r);for(let n=this.heap.length>>1;n>=0;n--)Vg(this.heap,n);(this.to-e||this.value.endSide-r)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Vg(this.heap,0)}}}function Vg(t,e){for(let r=t[e];;){let n=(e<<1)+1;if(n>=t.length)break;let s=t[n];if(n+1<t.length&&s.compare(t[n+1])>=0&&(s=t[n+1],n++),r.compare(s)<0)break;t[n]=r,t[e]=s,e=n}}class Fu{constructor(e,r,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Td.from(e,r,n)}goto(e,r=-1e9){return this.cursor.goto(e,r),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=r,this.openStart=-1,this.next(),this}forward(e,r){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-r)<0;)this.removeActive(this.minActive);this.cursor.forward(e,r)}removeActive(e){ef(this.active,e),ef(this.activeTo,e),ef(this.activeRank,e),this.minActive=Ow(this.active,this.activeTo)}addActive(e){let r=0,{value:n,to:s,rank:i}=this.cursor;for(;r<this.activeRank.length&&(i-this.activeRank[r]||s-this.activeTo[r])>0;)r++;tf(this.active,r,n),tf(this.activeTo,r,s),tf(this.activeRank,r,i),e&&tf(e,r,this.cursor.from),this.minActive=Ow(this.active,this.activeTo)}next(){let e=this.to,r=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),n&&ef(n,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let i=this.cursor.value;if(!i.point)this.addActive(n),this.cursor.next();else if(r&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=i,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=i.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(n){this.openStart=0;for(let s=n.length-1;s>=0&&n[s]<e;s--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let r=[];for(let n=this.active.length-1;n>=0&&!(this.activeRank[n]<this.pointRank);n--)(this.activeTo[n]>e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&r.push(this.active[n]);return r.reverse()}openEnd(e){let r=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)r++;return r}}function Mw(t,e,r,n,s,i){t.goto(e),r.goto(n);let a=n+s,o=n,l=n-e;for(;;){let c=t.to+l-r.to,u=c||t.endSide-r.endSide,d=u<0?t.to+l:r.to,h=Math.min(d,a);if(t.point||r.point?t.point&&r.point&&(t.point==r.point||t.point.eq(r.point))&&Bv(t.activeForPoint(t.to),r.activeForPoint(r.to))||i.comparePoint(o,h,t.point,r.point):h>o&&!Bv(t.active,r.active)&&i.compareRange(o,h,t.active,r.active),d>a)break;(c||t.openEnd!=r.openEnd)&&i.boundChange&&i.boundChange(d),o=d,u<=0&&t.next(),u>=0&&r.next()}}function Bv(t,e){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!=e[r]&&!t[r].eq(e[r]))return!1;return!0}function ef(t,e){for(let r=e,n=t.length-1;r<n;r++)t[r]=t[r+1];t.pop()}function tf(t,e,r){for(let n=t.length-1;n>=e;n--)t[n+1]=t[n];t[e]=r}function Ow(t,e){let r=-1,n=1e9;for(let s=0;s<e.length;s++)(e[s]-n||t[s].endSide-t[r].endSide)<0&&(r=s,n=e[s]);return r}function ym(t,e,r=t.length){let n=0;for(let s=0;s<r&&s<t.length;)t.charCodeAt(s)==9?(n+=e-n%e,s++):(n++,s=ts(t,s));return n}function G3(t,e,r,n){for(let s=0,i=0;;){if(i>=e)return s;if(s==t.length)break;i+=t.charCodeAt(s)==9?r-i%r:1,s=ts(t,s)}return t.length}const Fv="ͼ",jw=typeof Symbol>"u"?"__"+Fv:Symbol.for(Fv),Wv=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),$w=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class nl{constructor(e,r){this.rules=[];let{finish:n}=r||{};function s(a){return/^@/.test(a)?[a]:a.split(/,\s*/)}function i(a,o,l,c){let u=[],d=/^@(\w+)\b/.exec(a[0]),h=d&&d[1]=="keyframes";if(d&&o==null)return l.push(a[0]+";");for(let m in o){let b=o[m];if(/&/.test(m))i(m.split(/,\s*/).map(g=>a.map(p=>g.replace(/&/,p))).reduce((g,p)=>g.concat(p)),b,l);else if(b&&typeof b=="object"){if(!d)throw new RangeError("The value of a property ("+m+") should be a primitive value.");i(s(m),b,u,h)}else b!=null&&u.push(m.replace(/_.*/,"").replace(/[A-Z]/g,g=>"-"+g.toLowerCase())+": "+b+";")}(u.length||h)&&l.push((n&&!d&&!c?a.map(n):a).join(", ")+" {"+u.join(" ")+"}")}for(let a in e)i(s(a),e[a],this.rules)}getRules(){return this.rules.join(` 43`)}static newName(){let e=$w[jw]||1;return $w[jw]=e+1,Fv+e.toString(36)}static mount(e,r,n){let s=e[Wv],i=n&&n.nonce;s?i&&s.setNonce(i):s=new q3(e,i),s.mount(Array.isArray(r)?r:[r],e)}}let Bw=new Map;class q3{constructor(e,r){let n=e.ownerDocument||e,s=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let i=Bw.get(n);if(i)return e[Wv]=i;this.sheet=new s.CSSStyleSheet,Bw.set(n,this)}else this.styleTag=n.createElement("style"),r&&this.styleTag.setAttribute("nonce",r);this.modules=[],e[Wv]=this}mount(e,r){let n=this.sheet,s=0,i=0;for(let a=0;a<e.length;a++){let o=e[a],l=this.modules.indexOf(o);if(l<i&&l>-1&&(this.modules.splice(l,1),i--,l=-1),l==-1){if(this.modules.splice(i++,0,o),n)for(let c=0;c<o.rules.length;c++)n.insertRule(o.rules[c],s++)}else{for(;i<l;)s+=this.modules[i++].rules.length;s+=o.rules.length,i++}}if(n)r.adoptedStyleSheets.indexOf(this.sheet)<0&&(r.adoptedStyleSheets=[this.sheet,...r.adoptedStyleSheets]);else{let a="";for(let l=0;l<this.modules.length;l++)a+=this.modules[l].getRules()+` 44`;this.styleTag.textContent=a;let o=r.head||r;this.styleTag.parentNode!=o&&o.insertBefore(this.styleTag,o.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}}var sl={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Rd={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},K3=typeof navigator<"u"&&/Mac/.test(navigator.platform),Y3=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Ns=0;Ns<10;Ns++)sl[48+Ns]=sl[96+Ns]=String(Ns);for(var Ns=1;Ns<=24;Ns++)sl[Ns+111]="F"+Ns;for(var Ns=65;Ns<=90;Ns++)sl[Ns]=String.fromCharCode(Ns+32),Rd[Ns]=String.fromCharCode(Ns);for(var Gg in sl)Rd.hasOwnProperty(Gg)||(Rd[Gg]=sl[Gg]);function X3(t){var e=K3&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||Y3&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",r=!e&&t.key||(t.shiftKey?Rd:sl)[t.keyCode]||t.key||"Unidentified";return r=="Esc"&&(r="Escape"),r=="Del"&&(r="Delete"),r=="Left"&&(r="ArrowLeft"),r=="Up"&&(r="ArrowUp"),r=="Right"&&(r="ArrowRight"),r=="Down"&&(r="ArrowDown"),r}function Rs(){var t=arguments[0];typeof t=="string"&&(t=document.createElement(t));var e=1,r=arguments[1];if(r&&typeof r=="object"&&r.nodeType==null&&!Array.isArray(r)){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)){var s=r[n];typeof s=="string"?t.setAttribute(n,s):s!=null&&(t[n]=s)}e++}for(;e<arguments.length;e++)lP(t,arguments[e]);return t}function lP(t,e){if(typeof e=="string")t.appendChild(document.createTextNode(e));else if(e!=null)if(e.nodeType!=null)t.appendChild(e);else if(Array.isArray(e))for(var r=0;r<e.length;r++)lP(t,e[r]);else throw new RangeError("Unsupported child node: "+e)}let si=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Hv=typeof document<"u"?document:{documentElement:{style:{}}};const Uv=/Edge\/(\d+)/.exec(si.userAgent),cP=/MSIE \d/.test(si.userAgent),zv=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(si.userAgent),_m=!!(cP||zv||Uv),Fw=!_m&&/gecko\/(\d+)/i.test(si.userAgent),qg=!_m&&/Chrome\/(\d+)/.exec(si.userAgent),J3="webkitFontSmoothing"in Hv.documentElement.style,Vv=!_m&&/Apple Computer/.test(si.vendor),Ww=Vv&&(/Mobile\/\w+/.test(si.userAgent)||si.maxTouchPoints>2);var tt={mac:Ww||/Mac/.test(si.platform),windows:/Win/.test(si.platform),linux:/Linux|X11/.test(si.platform),ie:_m,ie_version:cP?Hv.documentMode||6:zv?+zv[1]:Uv?+Uv[1]:0,gecko:Fw,gecko_version:Fw?+(/Firefox\/(\d+)/.exec(si.userAgent)||[0,0])[1]:0,chrome:!!qg,chrome_version:qg?+qg[1]:0,ios:Ww,android:/Android\b/.test(si.userAgent),webkit_version:J3?+(/\bAppleWebKit\/(\d+)/.exec(si.userAgent)||[0,0])[1]:0,safari:Vv,safari_version:Vv?+(/\bVersion\/(\d+(\.\d+)?)/.exec(si.userAgent)||[0,0])[1]:0,tabSize:Hv.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function T_(t,e){for(let r in t)r=="class"&&e.class?e.class+=" "+t.class:r=="style"&&e.style?e.style+=";"+t.style:e[r]=t[r];return e}const yp=Object.create(null);function R_(t,e,r){if(t==e)return!0;t||(t=yp),e||(e=yp);let n=Object.keys(t),s=Object.keys(e);if(n.length-0!=s.length-0)return!1;for(let i of n)if(i!=r&&(s.indexOf(i)==-1||t[i]!==e[i]))return!1;return!0}function Q3(t,e){for(let r=t.attributes.length-1;r>=0;r--){let n=t.attributes[r].name;e[n]==null&&t.removeAttribute(n)}for(let r in e){let n=e[r];r=="style"?t.style.cssText=n:t.getAttribute(r)!=n&&t.setAttribute(r,n)}}function Hw(t,e,r){let n=!1;if(e)for(let s in e)r&&s in r||(n=!0,s=="style"?t.style.cssText="":t.removeAttribute(s));if(r)for(let s in r)e&&e[s]==r[s]||(n=!0,s=="style"?t.style.cssText=r[s]:t.setAttribute(s,r[s]));return n}function Z3(t){let e=Object.create(null);for(let r=0;r<t.attributes.length;r++){let n=t.attributes[r];e[n.name]=n.value}return e}class dl{eq(e){return!1}updateDOM(e,r){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,r,n){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}}var Ls=function(t){return t[t.Text=0]="Text",t[t.WidgetBefore=1]="WidgetBefore",t[t.WidgetAfter=2]="WidgetAfter",t[t.WidgetRange=3]="WidgetRange",t}(Ls||(Ls={}));class lr extends rl{constructor(e,r,n,s){super(),this.startSide=e,this.endSide=r,this.widget=n,this.spec=s}get heightRelevant(){return!1}static mark(e){return new fh(e)}static widget(e){let r=Math.max(-1e4,Math.min(1e4,e.side||0)),n=!!e.block;return r+=n&&!e.inlineOrder?r>0?3e8:-4e8:r>0?1e8:-1e8,new ac(e,r,r,n,e.widget||null,!1)}static replace(e){let r=!!e.block,n,s;if(e.isBlockGap)n=-5e8,s=4e8;else{let{start:i,end:a}=uP(e,r);n=(i?r?-3e8:-1:5e8)-1,s=(a?r?2e8:1:-6e8)+1}return new ac(e,n,s,r,e.widget||null,!0)}static line(e){return new ph(e)}static set(e,r=!1){return gr.of(e,r)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}lr.none=gr.empty;class fh extends lr{constructor(e){let{start:r,end:n}=uP(e);super(r?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?T_(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||yp}eq(e){return this==e||e instanceof fh&&this.tagName==e.tagName&&R_(this.attrs,e.attrs)}range(e,r=e){if(e>=r)throw new RangeError("Mark decorations may not be empty");return super.range(e,r)}}fh.prototype.point=!1;class ph extends lr{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof ph&&this.spec.class==e.spec.class&&R_(this.spec.attributes,e.spec.attributes)}range(e,r=e){if(r!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,r)}}ph.prototype.mapMode=Hs.TrackBefore;ph.prototype.point=!0;class ac extends lr{constructor(e,r,n,s,i,a){super(r,n,i,e),this.block=s,this.isReplace=a,this.mapMode=s?r<=0?Hs.TrackBefore:Hs.TrackAfter:Hs.TrackDel}get type(){return this.startSide!=this.endSide?Ls.WidgetRange:this.startSide<=0?Ls.WidgetBefore:Ls.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof ac&&e4(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,r=e){if(this.isReplace&&(e>r||e==r&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&r!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,r)}}ac.prototype.point=!0;function uP(t,e=!1){let{inclusiveStart:r,inclusiveEnd:n}=t;return r==null&&(r=t.inclusive),n==null&&(n=t.inclusive),{start:r??e,end:n??e}}function e4(t,e){return t==e||!!(t&&e&&t.compare(e))}function qc(t,e,r,n=0){let s=r.length-1;s>=0&&r[s]+n>=t?r[s]=Math.max(r[s],e):r.push(t,e)}class Id extends rl{constructor(e,r){super(),this.tagName=e,this.attributes=r}eq(e){return e==this||e instanceof Id&&this.tagName==e.tagName&&R_(this.attributes,e.attributes)}static create(e){return new Id(e.tagName,e.attributes||yp)}static set(e,r=!1){return gr.of(e,r)}}Id.prototype.startSide=Id.prototype.endSide=-1;function Nd(t){let e;return t.nodeType==11?e=t.getSelection?t:t.ownerDocument:e=t,e.getSelection()}function Gv(t,e){return e?t==e||t.contains(e.nodeType!=1?e.parentNode:e):!1}function Ff(t,e){if(!e.anchorNode)return!1;try{return Gv(t,e.anchorNode)}catch{return!1}}function Wf(t){return t.nodeType==3?Ld(t,0,t.nodeValue.length).getClientRects():t.nodeType==1?t.getClientRects():[]}function fd(t,e,r,n){return r?Uw(t,e,r,n,-1)||Uw(t,e,r,n,1):!1}function il(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e}function _p(t){return t.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(t.nodeName)}function Uw(t,e,r,n,s){for(;;){if(t==r&&e==n)return!0;if(e==(s<0?0:ga(t))){if(t.nodeName=="DIV")return!1;let i=t.parentNode;if(!i||i.nodeType!=1)return!1;e=il(t)+(s<0?0:1),t=i}else if(t.nodeType==1){if(t=t.childNodes[e+(s<0?-1:0)],t.nodeType==1&&t.contentEditable=="false")return!1;e=s<0?ga(t):0}else return!1}}function ga(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function xp(t,e){let r=e?t.left:t.right;return{left:r,right:r,top:t.top,bottom:t.bottom}}function t4(t){let e=t.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.innerWidth,top:0,bottom:t.innerHeight}}function dP(t,e){let r=e.width/t.offsetWidth,n=e.height/t.offsetHeight;return(r>.995&&r<1.005||!isFinite(r)||Math.abs(e.width-t.offsetWidth)<1)&&(r=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-t.offsetHeight)<1)&&(n=1),{scaleX:r,scaleY:n}}function r4(t,e,r,n,s,i,a,o){let l=t.ownerDocument,c=l.defaultView||window;for(let u=t,d=!1;u&&!d;)if(u.nodeType==1){let h,m=u==l.body,b=1,g=1;if(m)h=t4(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(u).position)&&(d=!0),u.scrollHeight<=u.clientHeight&&u.scrollWidth<=u.clientWidth){u=u.assignedSlot||u.parentNode;continue}let v=u.getBoundingClientRect();({scaleX:b,scaleY:g}=dP(u,v)),h={left:v.left,right:v.left+u.clientWidth*b,top:v.top,bottom:v.top+u.clientHeight*g}}let p=0,y=0;if(s=="nearest")e.top<h.top?(y=e.top-(h.top+a),r>0&&e.bottom>h.bottom+y&&(y=e.bottom-h.bottom+a)):e.bottom>h.bottom&&(y=e.bottom-h.bottom+a,r<0&&e.top-y<h.top&&(y=e.top-(h.top+a)));else{let v=e.bottom-e.top,_=h.bottom-h.top;y=(s=="center"&&v<=_?e.top+v/2-_/2:s=="start"||s=="center"&&r<0?e.top-a:e.bottom-_+a)-h.top}if(n=="nearest"?e.left<h.left?(p=e.left-(h.left+i),r>0&&e.right>h.right+p&&(p=e.right-h.right+i)):e.right>h.right&&(p=e.right-h.right+i,r<0&&e.left<h.left+p&&(p=e.left-(h.left+i))):p=(n=="center"?e.left+(e.right-e.left)/2-(h.right-h.left)/2:n=="start"==o?e.left-i:e.right-(h.right-h.left)+i)-h.left,p||y)if(m)c.scrollBy(p,y);else{let v=0,_=0;if(y){let w=u.scrollTop;u.scrollTop+=y/g,_=(u.scrollTop-w)*g}if(p){let w=u.scrollLeft;u.scrollLeft+=p/b,v=(u.scrollLeft-w)*b}e={left:e.left-v,top:e.top-_,right:e.right-v,bottom:e.bottom-_},v&&Math.abs(v-p)<1&&(n="nearest"),_&&Math.abs(_-y)<1&&(s="nearest")}if(m)break;(e.top<h.top||e.bottom>h.bottom||e.left<h.left||e.right>h.right)&&(e={left:Math.max(e.left,h.left),right:Math.min(e.right,h.right),top:Math.max(e.top,h.top),bottom:Math.min(e.bottom,h.bottom)}),u=u.assignedSlot||u.parentNode}else if(u.nodeType==11)u=u.host;else break}function n4(t){let e=t.ownerDocument,r,n;for(let s=t.parentNode;s&&!(s==e.body||r&&n);)if(s.nodeType==1)!n&&s.scrollHeight>s.clientHeight&&(n=s),!r&&s.scrollWidth>s.clientWidth&&(r=s),s=s.assignedSlot||s.parentNode;else if(s.nodeType==11)s=s.host;else break;return{x:r,y:n}}class s4{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:r,focusNode:n}=e;this.set(r,Math.min(e.anchorOffset,r?ga(r):0),n,Math.min(e.focusOffset,n?ga(n):0))}set(e,r,n,s){this.anchorNode=e,this.anchorOffset=r,this.focusNode=n,this.focusOffset=s}}let Ll=null;tt.safari&&tt.safari_version>=26&&(Ll=!1);function hP(t){if(t.setActive)return t.setActive();if(Ll)return t.focus(Ll);let e=[];for(let r=t;r&&(e.push(r,r.scrollTop,r.scrollLeft),r!=r.ownerDocument);r=r.parentNode);if(t.focus(Ll==null?{get preventScroll(){return Ll={preventScroll:!0},!0}}:void 0),!Ll){Ll=!1;for(let r=0;r<e.length;){let n=e[r++],s=e[r++],i=e[r++];n.scrollTop!=s&&(n.scrollTop=s),n.scrollLeft!=i&&(n.scrollLeft=i)}}}let zw;function Ld(t,e,r=e){let n=zw||(zw=document.createRange());return n.setEnd(t,r),n.setStart(t,e),n}function Kc(t,e,r,n){let s={key:e,code:e,keyCode:r,which:r,cancelable:!0};n&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=n);let i=new KeyboardEvent("keydown",s);i.synthetic=!0,t.dispatchEvent(i);let a=new KeyboardEvent("keyup",s);return a.synthetic=!0,t.dispatchEvent(a),i.defaultPrevented||a.defaultPrevented}function i4(t){for(;t;){if(t&&(t.nodeType==9||t.nodeType==11&&t.host))return t;t=t.assignedSlot||t.parentNode}return null}function o4(t,e){let r=e.focusNode,n=e.focusOffset;if(!r||e.anchorNode!=r||e.anchorOffset!=n)return!1;for(n=Math.min(n,ga(r));;)if(n){if(r.nodeType!=1)return!1;let s=r.childNodes[n-1];s.contentEditable=="false"?n--:(r=s,n=ga(r))}else{if(r==t)return!0;n=il(r),r=r.parentNode}}function fP(t){return t.scrollTop>Math.max(1,t.scrollHeight-t.clientHeight-4)}function pP(t,e){for(let r=t,n=e;;){if(r.nodeType==3&&n>0)return{node:r,offset:n};if(r.nodeType==1&&n>0){if(r.contentEditable=="false")return null;r=r.childNodes[n-1],n=ga(r)}else if(r.parentNode&&!_p(r))n=il(r),r=r.parentNode;else return null}}function mP(t,e){for(let r=t,n=e;;){if(r.nodeType==3&&n<r.nodeValue.length)return{node:r,offset:n};if(r.nodeType==1&&n<r.childNodes.length){if(r.contentEditable=="false")return null;r=r.childNodes[n],n=0}else if(r.parentNode&&!_p(r))n=il(r)+1,r=r.parentNode;else return null}}class ho{constructor(e,r,n=!0){this.node=e,this.offset=r,this.precise=n}static before(e,r){return new ho(e.parentNode,il(e),r)}static after(e,r){return new ho(e.parentNode,il(e)+1,r)}}var en=function(t){return t[t.LTR=0]="LTR",t[t.RTL=1]="RTL",t}(en||(en={}));const lc=en.LTR,I_=en.RTL;function gP(t){let e=[];for(let r=0;r<t.length;r++)e.push(1<<+t[r]);return e}const a4=gP("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),l4=gP("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),qv=Object.create(null),Co=[];for(let t of["()","[]","{}"]){let e=t.charCodeAt(0),r=t.charCodeAt(1);qv[e]=r,qv[r]=-e}function bP(t){return t<=247?a4[t]:1424<=t&&t<=1524?2:1536<=t&&t<=1785?l4[t-1536]:1774<=t&&t<=2220?4:8192<=t&&t<=8204?256:64336<=t&&t<=65023?4:1}const c4=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;class ca{get dir(){return this.level%2?I_:lc}constructor(e,r,n){this.from=e,this.to=r,this.level=n}side(e,r){return this.dir==r==e?this.to:this.from}forward(e,r){return e==(this.dir==r)}static find(e,r,n,s){let i=-1;for(let a=0;a<e.length;a++){let o=e[a];if(o.from<=r&&o.to>=r){if(o.level==n)return a;(i<0||(s!=0?s<0?o.from<r:o.to>r:e[i].level>o.level))&&(i=a)}}if(i<0)throw new RangeError("Index out of range");return i}}function vP(t,e){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],s=e[r];if(n.from!=s.from||n.to!=s.to||n.direction!=s.direction||!vP(n.inner,s.inner))return!1}return!0}const Xr=[];function u4(t,e,r,n,s){for(let i=0;i<=n.length;i++){let a=i?n[i-1].to:e,o=i<n.length?n[i].from:r,l=i?256:s;for(let c=a,u=l,d=l;c<o;c++){let h=bP(t.charCodeAt(c));h==512?h=u:h==8&&d==4&&(h=16),Xr[c]=h==4?2:h,h&7&&(d=h),u=h}for(let c=a,u=l,d=l;c<o;c++){let h=Xr[c];if(h==128)c<o-1&&u==Xr[c+1]&&u&24?h=Xr[c]=u:Xr[c]=256;else if(h==64){let m=c+1;for(;m<o&&Xr[m]==64;)m++;let b=c&&u==8||m<r&&Xr[m]==8?d==1?1:8:256;for(let g=c;g<m;g++)Xr[g]=b;c=m-1}else h==8&&d==1&&(Xr[c]=1);u=h,h&7&&(d=h)}}}function d4(t,e,r,n,s){let i=s==1?2:1;for(let a=0,o=0,l=0;a<=n.length;a++){let c=a?n[a-1].to:e,u=a<n.length?n[a].from:r;for(let d=c,h,m,b;d<u;d++)if(m=qv[h=t.charCodeAt(d)])if(m<0){for(let g=o-3;g>=0;g-=3)if(Co[g+1]==-m){let p=Co[g+2],y=p&2?s:p&4?p&1?i:s:0;y&&(Xr[d]=Xr[Co[g]]=y),o=g;break}}else{if(Co.length==189)break;Co[o++]=d,Co[o++]=h,Co[o++]=l}else if((b=Xr[d])==2||b==1){let g=b==s;l=g?0:1;for(let p=o-3;p>=0;p-=3){let y=Co[p+2];if(y&2)break;if(g)Co[p+2]|=2;else{if(y&4)break;Co[p+2]|=4}}}}}function h4(t,e,r,n){for(let s=0,i=n;s<=r.length;s++){let a=s?r[s-1].to:t,o=s<r.length?r[s].from:e;for(let l=a;l<o;){let c=Xr[l];if(c==256){let u=l+1;for(;;)if(u==o){if(s==r.length)break;u=r[s++].to,o=s<r.length?r[s].from:e}else if(Xr[u]==256)u++;else break;let d=i==1,h=(u<e?Xr[u]:n)==1,m=d==h?d?1:2:n;for(let b=u,g=s,p=g?r[g-1].to:t;b>l;)b==p&&(b=r[--g].from,p=g?r[g-1].to:t),Xr[--b]=m;l=u}else i=c,l++}}}function Kv(t,e,r,n,s,i,a){let o=n%2?2:1;if(n%2==s%2)for(let l=e,c=0;l<r;){let u=!0,d=!1;if(c==i.length||l<i[c].from){let g=Xr[l];g!=o&&(u=!1,d=g==16)}let h=!u&&o==1?[]:null,m=u?n:n+1,b=l;e:for(;;)if(c<i.length&&b==i[c].from){if(d)break e;let g=i[c];if(!u)for(let p=g.to,y=c+1;;){if(p==r)break e;if(y<i.length&&i[y].from==p)p=i[y++].to;else{if(Xr[p]==o)break e;break}}if(c++,h)h.push(g);else{g.from>l&&a.push(new ca(l,g.from,m));let p=g.direction==lc!=!(m%2);Yv(t,p?n+1:n,s,g.inner,g.from,g.to,a),l=g.to}b=g.to}else{if(b==r||(u?Xr[b]!=o:Xr[b]==o))break;b++}h?Kv(t,l,b,n+1,s,h,a):l<b&&a.push(new ca(l,b,m)),l=b}else for(let l=r,c=i.length;l>e;){let u=!0,d=!1;if(!c||l>i[c-1].to){let g=Xr[l-1];g!=o&&(u=!1,d=g==16)}let h=!u&&o==1?[]:null,m=u?n:n+1,b=l;e:for(;;)if(c&&b==i[c-1].to){if(d)break e;let g=i[--c];if(!u)for(let p=g.from,y=c;;){if(p==e)break e;if(y&&i[y-1].to==p)p=i[--y].from;else{if(Xr[p-1]==o)break e;break}}if(h)h.push(g);else{g.to<l&&a.push(new ca(g.to,l,m));let p=g.direction==lc!=!(m%2);Yv(t,p?n+1:n,s,g.inner,g.from,g.to,a),l=g.from}b=g.from}else{if(b==e||(u?Xr[b-1]!=o:Xr[b-1]==o))break;b--}h?Kv(t,b,l,n+1,s,h,a):b<l&&a.push(new ca(b,l,m)),l=b}}function Yv(t,e,r,n,s,i,a){let o=e%2?2:1;u4(t,s,i,n,o),d4(t,s,i,n,o),h4(s,i,n,o),Kv(t,s,i,e,r,n,a)}function f4(t,e,r){if(!t)return[new ca(0,0,e==I_?1:0)];if(e==lc&&!r.length&&!c4.test(t))return yP(t.length);if(r.length)for(;t.length>Xr.length;)Xr[Xr.length]=256;let n=[],s=e==lc?0:1;return Yv(t,s,s,r,0,t.length,n),n}function yP(t){return[new ca(0,t,0)]}let _P="";function p4(t,e,r,n,s){var i;let a=n.head-t.from,o=ca.find(e,a,(i=n.bidiLevel)!==null&&i!==void 0?i:-1,n.assoc),l=e[o],c=l.side(s,r);if(a==c){let h=o+=s?1:-1;if(h<0||h>=e.length)return null;l=e[o=h],a=l.side(!s,r),c=l.side(s,r)}let u=ts(t.text,a,l.forward(s,r));(u<l.from||u>l.to)&&(u=c),_P=t.text.slice(Math.min(a,u),Math.max(a,u));let d=o==(s?e.length-1:0)?null:e[o+(s?1:-1)];return d&&u==c&&d.level+(s?0:1)<l.level?ke.cursor(d.side(!s,r)+t.from,d.forward(s,r)?1:-1,d.level):ke.cursor(u+t.from,l.forward(s,r)?-1:1,l.level)}function m4(t,e,r){for(let n=e;n<r;n++){let s=bP(t.charCodeAt(n));if(s==1)return lc;if(s==2||s==4)return I_}return lc}const xP=it.define(),wP=it.define(),SP=it.define(),CP=it.define(),Xv=it.define(),AP=it.define(),EP=it.define(),N_=it.define(),L_=it.define(),kP=it.define({combine:t=>t.some(e=>e)}),PP=it.define({combine:t=>t.some(e=>e)}),TP=it.define();class Yc{constructor(e,r="nearest",n="nearest",s=5,i=5,a=!1){this.range=e,this.y=r,this.x=n,this.yMargin=s,this.xMargin=i,this.isSnapshot=a}map(e){return e.empty?this:new Yc(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Yc(ke.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const rf=sr.define({map:(t,e)=>t.map(e)}),RP=sr.define();function Oi(t,e,r){let n=t.facet(CP);n.length?n[0](e):window.onerror&&window.onerror(String(e),r,void 0,void 0,e)||(r?console.error(r+":",e):console.error(e))}const sa=it.define({combine:t=>t.length?t[0]:!0});let g4=0;const jc=it.define({combine(t){return t.filter((e,r)=>{for(let n=0;n<r;n++)if(t[n].plugin==e.plugin)return!1;return!0})}});class ms{constructor(e,r,n,s,i){this.id=e,this.create=r,this.domEventHandlers=n,this.domEventObservers=s,this.baseExtensions=i(this),this.extension=this.baseExtensions.concat(jc.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(jc.of({plugin:this,arg:e}))}static define(e,r){const{eventHandlers:n,eventObservers:s,provide:i,decorations:a}=r||{};return new ms(g4++,e,n,s,o=>{let l=[];return a&&l.push(Dd.of(c=>{let u=c.plugin(o);return u?a(u):lr.none})),i&&l.push(i(o)),l})}static fromClass(e,r){return ms.define((n,s)=>new e(n,s),r)}}class Kg{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let r=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(r)}catch(n){if(Oi(r.state,n,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(r){Oi(e.state,r,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var r;if(!((r=this.value)===null||r===void 0)&&r.destroy)try{this.value.destroy()}catch(n){Oi(e.state,n,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const IP=it.define(),xm=it.define(),Dd=it.define(),NP=it.define(),LP=it.define(),mh=it.define(),DP=it.define();function Vw(t,e){let r=t.state.facet(DP);if(!r.length)return r;let n=r.map(i=>i instanceof Function?i(t):i),s=[];return gr.spans(n,e.from,e.to,{point(){},span(i,a,o,l){let c=i-e.from,u=a-e.from,d=s;for(let h=o.length-1;h>=0;h--,l--){let m=o[h].spec.bidiIsolate,b;if(m==null&&(m=m4(e.text,c,u)),l>0&&d.length&&(b=d[d.length-1]).to==c&&b.direction==m)b.to=u,d=b.inner;else{let g={from:c,to:u,direction:m,inner:[]};
vendor: 7,691 bytes, line 44
44d.push(g),d=g.inner}}}}),s}const MP=it.define();function D_(t){let e=0,r=0,n=0,s=0;for(let i of t.state.facet(MP)){let a=i(t);a&&(a.left!=null&&(e=Math.max(e,a.left)),a.right!=null&&(r=Math.max(r,a.right)),a.top!=null&&(n=Math.max(n,a.top)),a.bottom!=null&&(s=Math.max(s,a.bottom)))}return{left:e,right:r,top:n,bottom:s}}const Qu=it.define();class Ki{constructor(e,r,n,s){this.fromA=e,this.toA=r,this.fromB=n,this.toB=s}join(e){return new Ki(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let r=e.length,n=this;for(;r>0;r--){let s=e[r-1];if(!(s.fromA>n.toA)){if(s.toA<n.fromA)break;n=n.join(s),e.splice(r-1,1)}}return e.splice(r,0,n),e}static extendWithRanges(e,r){if(r.length==0)return e;let n=[];for(let s=0,i=0,a=0;;){let o=s<e.length?e[s].fromB:1e9,l=i<r.length?r[i]:1e9,c=Math.min(o,l);if(c==1e9)break;let u=c+a,d=c,h=u;for(;;)if(i<r.length&&r[i]<=d){let m=r[i+1];i+=2,d=Math.max(d,m);for(let b=s;b<e.length&&e[b].fromB<=d;b++)a=e[b].toA-e[b].toB;h=Math.max(h,m+a)}else if(s<e.length&&e[s].fromB<=d){let m=e[s++];d=Math.max(d,m.toB),h=Math.max(h,m.toA),a=m.toA-m.toB}else break;n.push(new Ki(u,h,c,d))}return n}}class wp{constructor(e,r,n){this.view=e,this.state=r,this.transactions=n,this.flags=0,this.startState=e.state,this.changes=es.empty(this.startState.doc.length);for(let i of n)this.changes=this.changes.compose(i.changes);let s=[];this.changes.iterChangedRanges((i,a,o,l)=>s.push(new Ki(i,a,o,l))),this.changedRanges=s}static create(e,r,n){return new wp(e,r,n)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const b4=[];class ns{constructor(e,r,n=0){this.dom=e,this.length=r,this.flags=n,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return b4}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let r=this.domAttrs;r&&Q3(this.dom,r)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,r=this.posAtStart){let n=r;for(let s of this.children){if(s==e)return n;n+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,r){return null}domPosFor(e,r){let n=il(this.dom),s=this.length?e>0:r>0;return new ho(this.parent.dom,n+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Sm)return e;return null}static get(e){return e.cmTile}}class wm extends ns{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let r=this.dom,n=null,s,i=e?.node==r?e:null,a=0;for(let o of this.children){if(o.sync(e),a+=o.length+o.breakAfter,s=n?n.nextSibling:r.firstChild,i&&s!=o.dom&&(i.written=!0),o.dom.parentNode==r)for(;s&&s!=o.dom;)s=Gw(s);else r.insertBefore(o.dom,s);n=o.dom}for(s=n?n.nextSibling:r.firstChild,i&&s&&(i.written=!0);s;)s=Gw(s);this.length=a}}function Gw(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class Sm extends wm{constructor(e,r){super(r),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let r=ns.get(e);if(r&&this.owns(r))return r;e=e.parentNode}}blockTiles(e){for(let r=[],n=this,s=0,i=0;;)if(s==n.children.length){if(!r.length)return;n=n.parent,n.breakAfter&&i++,s=r.pop()}else{let a=n.children[s++];if(a instanceof Ja)r.push(s),n=a,s=0;else{let o=i+a.length,l=e(a,i);if(l!==void 0)return l;i=o+a.breakAfter}}}resolveBlock(e,r){let n,s=-1,i,a=-1;if(this.blockTiles((o,l)=>{let c=l+o.length;if(e>=l&&e<=c){if(o.isWidget()&&r>=-1&&r<=1){if(o.flags&32)return!0;o.flags&16&&(n=void 0)}(l<e||e==c&&(r<-1?o.length:o.covers(1)))&&(!n||!o.isWidget()&&n.isWidget())&&(n=o,s=e-l),(c>e||e==l&&(r>1?o.length:o.covers(-1)))&&(!i||!o.isWidget()&&i.isWidget())&&(i=o,a=e-l)}}),!n&&!i)throw new Error("No tile at position "+e);return n&&r<0||!i?{tile:n,offset:s}:{tile:i,offset:a}}}class Ja extends wm{constructor(e,r){super(e),this.wrapper=r}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,r){let n=new Ja(r||document.createElement(e.tagName),e);return r||(n.flags|=4),n}}class iu extends wm{constructor(e,r){super(e),this.attrs=r}isLine(){return!0}static start(e,r,n){let s=new iu(r||document.createElement("div"),e);return(!r||!n)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,r,n){let s=null,i=-1,a=null,o=-1;function l(u,d){for(let h=0,m=0;h<u.children.length&&m<=d;h++){let b=u.children[h],g=m+b.length;g>=d&&(b.isComposite()?l(b,d-m):(!a||a.isHidden&&(r>0||n&&y4(a,b)))&&(g>d||b.flags&32)?(a=b,o=d-m):(m<d||b.flags&16&&!b.isHidden)&&(s=b,i=d-m)),m=g}}l(this,e);let c=(r<0?s:a)||s||a;return c?{tile:c,offset:c==s?i:o}:null}coordsIn(e,r){let n=this.resolveInline(e,r,!0);return n?n.tile.coordsIn(Math.max(0,n.offset),r):v4(this)}domIn(e,r){let n=this.resolveInline(e,r);if(n){let{tile:s,offset:i}=n;if(this.dom.contains(s.dom))return s.isText()?new ho(s.dom,Math.min(s.dom.nodeValue.length,i)):s.domPosFor(i,s.flags&16?1:s.flags&32?-1:r);let a=n.tile.parent,o=!1;for(let l of a.children){if(o)return new ho(l.dom,0);l==n.tile&&(o=!0)}}return new ho(this.dom,0)}}function v4(t){let e=t.dom.lastChild;if(!e)return t.dom.getBoundingClientRect();let r=Wf(e);return r[r.length-1]||null}function y4(t,e){let r=t.coordsIn(0,1),n=e.coordsIn(0,1);return r&&n&&n.top<r.bottom}class xi extends wm{constructor(e,r){super(e),this.mark=r}get domAttrs(){return this.mark.attrs}static of(e,r){let n=new xi(r||document.createElement(e.tagName),e);return r||(n.flags|=4),n}}class Vl extends ns{constructor(e,r){super(e,r.length),this.text=r}sync(e){this.flags&2||(super.sync(e),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(e,r){let n=this.dom.nodeValue.length;e>n&&(e=n);let s=e,i=e,a=0;e==0&&r<0||e==n&&r>=0?tt.chrome||tt.gecko||(e?(s--,a=1):i<n&&(i++,a=-1)):r<0?s--:i<n&&i++;let o=Ld(this.dom,s,i).getClientRects();if(!o.length)return null;let l=o[(a?a<0:r>=0)?0:o.length-1];return tt.safari&&!a&&l.width==0&&(l=Array.prototype.find.call(o,c=>c.width)||l),a?xp(l,a<0):l||null}static of(e,r){let n=new Vl(r||document.createTextNode(e),e);return r||(n.flags|=2),n}}class ou extends ns{constructor(e,r,n,s){super(e,r,s),this.widget=n}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,r){return this.coordsInWidget(e,r,!1)}coordsInWidget(e,r,n){let s=this.widget.coordsAt(this.dom,e,r);
44if(s)return s;if(n)return xp(this.dom.getBoundingClientRect(),this.length?e==0:r<=0);{let i=this.dom.getClientRects(),a=null;if(!i.length)return null;let o=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=o?i.length-1:0;a=i[l],!(e>0?l==0:l==i.length-1||a.top<a.bottom);l+=o?-1:1);return xp(a,!o)}}get overrideDOMText(){if(!this.length)return Mr.empty;let{root:e}=this;if(!e)return Mr.empty;let r=this.posAtStart;return e.view.state.doc.slice(r,r+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(e,r,n,s,i){return i||(i=e.toDOM(r),e.editable||(i.contentEditable="false")),new ou(i,n,e,s)}}class Sp extends ns{constructor(e){let r=document.createElement("img");r.className="cm-widgetBuffer",r.setAttribute("aria-hidden","true"),super(r,0,e)}get isHidden(){return!1}get overrideDOMText(){return Mr.empty}coordsIn(e){return this.dom.getBoundingClientRect()}}class _4{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,r,n){let{tile:s,index:i,beforeBreak:a,parents:o}=this;for(;e||r>0;)if(s.isComposite())if(a){if(!e)break;n&&n.break(),e--,a=!1}else if(i==s.children.length){if(!e&&!o.length)break;n&&n.leave(s),a=!!s.breakAfter,{tile:s,index:i}=o.pop(),i++}else{let l=s.children[i],c=l.breakAfter;(r>0?l.length<=e:l.length<e)&&(!n||n.skip(l,0,l.length)!==!1||!l.isComposite)?(a=!!c,i++,e-=l.length):(o.push({tile:s,index:i}),s=l,i=0,n&&l.isComposite()&&n.enter(l))}else if(i==s.length)a=!!s.breakAfter,{tile:s,index:i}=o.pop(),i++;else if(e){let l=Math.min(e,s.length-i);n&&n.skip(s,i,i+l),e-=l,i+=l}else break;return this.tile=s,this.index=i,this.beforeBreak=a,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}}class x4{constructor(e,r,n,s){this.from=e,this.to=r,this.wrapper=n,this.rank=s}}class w4{constructor(e,r,n){this.cache=e,this.root=r,this.blockWrappers=n,this.curLine=null,this.lastBlock=null,this.afterWidget=null,this.pos=0,this.wrappers=[],this.wrapperPos=0}addText(e,r,n,s){var i;this.flushBuffer();let a=this.ensureMarks(r,n),o=a.lastChild;if(o&&o.isText()&&!(o.flags&8)){this.cache.reused.set(o,2);let l=a.children[a.children.length-1]=new Vl(o.dom,o.text+e);l.parent=a}else a.append(s||Vl.of(e,(i=this.cache.find(Vl))===null||i===void 0?void 0:i.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,r){let n=this.curLine;n.dom!=r.line.dom&&(n.setDOM(this.cache.reused.has(r.line)?Yg(r.line.dom):r.line.dom),this.cache.reused.set(r.line,2));let s=n;for(let a=r.marks.length-1;a>=0;a--){let o=r.marks[a],l=s.lastChild;if(l instanceof xi&&l.mark.eq(o.mark))l.dom!=o.dom&&l.setDOM(Yg(o.dom)),s=l;else{if(this.cache.reused.get(o)){let u=ns.get(o.dom);u&&u.setDOM(Yg(o.dom))}let c=xi.of(o.mark,o.dom);s.append(c),s=c}this.cache.reused.set(o,2)}let i=new Vl(e.text,e.text.nodeValue);i.flags|=8,s.append(i)}addInlineWidget(e,r,n){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let i=this.ensureMarks(r,n);!s&&!(e.flags&16)&&i.append(this.getBuffer(1)),i.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,r,n){this.flushBuffer(),this.ensureMarks(r,n).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let r=this.afterWidget||this.lastBlock;r.length+=e,this.pos+=e}addLineStart(e,r){var n;e||(e=OP);let s=iu.start(e,r||((n=this.cache.find(iu))===null||n===void 0?void 0:n.dom),!!r);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,r){var n;let s=this.curLine;for(let i=e.length-1;i>=0;i--){let a=e[i],o;if(r>0&&(o=s.lastChild)&&o instanceof xi&&o.mark.eq(a))s=o,r--;else{let l=xi.of(a,(n=this.cache.find(xi,c=>c.mark.eq(a)))===null||n===void 0?void 0:n.dom);s.append(l),s=l,r=0}}return s}endLine(){if(this.curLine){this.flushBuffer();
44let e=this.curLine.lastChild;(!e||!qw(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(tt.ios&&qw(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Xg,0,32)||new ou(Xg.toDOM(),0,Xg,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let r=new x4(e.from,e.to,e.value,e.rank),n=this.wrappers.length;for(;n>0&&(this.wrappers[n-1].rank-r.rank||this.wrappers[n-1].to-r.to)<0;)n--;this.wrappers.splice(n,0,r)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let r=this.root;for(let n of this.wrappers){let s=r.lastChild;if(n.from<this.pos&&s instanceof Ja&&s.wrapper.eq(n.wrapper))r=s;else{let i=Ja.of(n.wrapper,(e=this.cache.find(Ja,a=>a.wrapper.eq(n.wrapper)))===null||e===void 0?void 0:e.dom);r.append(i),r=i}}return r}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let r=2|(e<0?16:32),n=this.cache.find(Sp,void 0,1);return n&&(n.flags=r),n||new Sp(r)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class S4{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:i,done:a}=this.cursor.next(this.skipCount);if(this.skipCount=0,a)throw new Error("Ran out of text content when drawing inline views");this.text=s;let o=this.textOff=Math.min(e,s.length);return i?null:s.slice(0,o)}let r=Math.min(this.text.length,this.textOff+e),n=this.text.slice(this.textOff,r);return this.textOff=r,n}}const Cp=[ou,iu,Vl,xi,Sp,Ja,Sm];for(let t=0;t<Cp.length;t++)Cp[t].bucket=t;class C4{constructor(e){this.view=e,this.buckets=Cp.map(()=>[]),this.index=Cp.map(()=>0),this.reused=new Map}add(e){let r=e.constructor.bucket,n=this.buckets[r];n.length<6?n.push(e):n[this.index[r]=(this.index[r]+1)%6]=e}find(e,r,n=2){let s=e.bucket,i=this.buckets[s],a=this.index[s];for(let o=i.length-1;o>=0;o--){let l=(o+a)%i.length,c=i[l];if((!r||r(c))&&!this.reused.has(c))return i.splice(l,1),l<a&&this.index[s]--,this.reused.set(c,n),c}return null}findWidget(e,r,n){let s=this.buckets[0];if(s.length)for(let i=0,a=0;;i++){if(i==s.length){if(a)return null;a=1,i=0}let o=s[i];if(!this.reused.has(o)&&(a==0?o.widget.compare(e):o.widget.constructor==e.constructor&&e.updateDOM(o.dom,this.view)))return s.splice(i,1),i<this.index[0]&&this.index[0]--,this.reused.set(o,1),o.length=r,o.flags=o.flags&-498|n,o}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,r=2){if(!this.reused.has(e))return this.reused.set(e,r),e.dom}}class A4{constructor(e,r,n,s,i){this.view=e,this.decorations=s,this.disallowBlockEffectsFor=i,this.openWidget=!1,this.openMarks=0,this.cache=new C4(e),this.text=new S4(e.state.doc),this.builder=new w4(this.cache,new Sm(e,e.contentDOM),gr.iter(n)),this.cache.reused.set(r,2),this.old=new _4(r)}run(e,r){let n=r&&this.getCompositionContext(r.text);for(let s=0,i=0,a=0;;){let o=a<e.length?e[a++]:null,l=o?o.fromA:this.old.root.length;if(l>s){let c=l-s;this.preserve(c,!a,!o),s=l,i+=c}if(!o)break;this.forward(o.fromA,o.toA),r&&o.fromA<=r.range.fromA&&o.toA>=r.range.toA?(this.emit(i,r.range.fromB),this.builder.addComposition(r,n),this.emit(r.range.toB,o.toB)):this.emit(i,o.toB),i=o.toB,s=o.toA}return this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,r,n){let s=P4(this.old),i=this.openMarks;this.old.advance(e,n?1:-1,{skip:(a,o,l)=>{if(a.isWidget())if(this.openWidget)this.builder.continueWidget(l-o);else{let c=l>0||o<a.length?ou.of(a.widget,this.view,l-o,a.flags&496,this.cache.maybeReuse(a)):this.cache.reuse(a);c.flags&256?(c.flags&=-2,this.builder.addBlockWidget(c)):(this.builder.ensureLine(null),this.builder.addInlineWidget(c,s,i),i=s.length)}else if(a.isText())this.builder.ensureLine(null),!o&&l==a.length?this.builder.addText(a.text,s,i,this.cache.reuse(a)):(this.cache.add(a),this.builder.addText(a.text.slice(o,l),s,i)),i=s.length;else if(a.isLine())a.flags&=-2,this.cache.reused.set(a,1),this.builder.addLine(a);else if(a instanceof Sp)this.cache.add(a);else if(a instanceof xi)this.builder.ensureLine(null),this.builder.addMark(a,s,i),this.cache.reused.set(a,1),i=s.length;else return!1;this.openWidget=!1},enter:a=>{a.isLine()?this.builder.addLineStart(a.attrs,this.cache.maybeReuse(a)):(this.cache.add(a),a instanceof xi&&s.unshift(a.mark)),this.openWidget=!1},leave:a=>{a.isLine()?s.length&&(s.length=i=0):a instanceof xi&&(s.shift(),i=Math.min(i,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,r){let n=null,s=this.builder,i=0,a=gr.spans(this.decorations,e,r,{point:(o,l,c,u,d,h)=>{if(c instanceof ac){if(this.disallowBlockEffectsFor[h]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");
44if(l>this.view.state.doc.lineAt(o).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(i=u.length,d>u.length)s.continueWidget(l-o);else{let m=c.widget||(c.block?au.block:au.inline),b=E4(c),g=this.cache.findWidget(m,l-o,b)||ou.of(m,this.view,l-o,b);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(n),s.addBlockWidget(g)):(s.ensureLine(n),s.addInlineWidget(g,u,d))}n=null}else n=k4(n,c);l>o&&this.text.skip(l-o)},span:(o,l,c,u)=>{for(let d=o;d<l;){let h=this.text.next(Math.min(512,l-d));h==null?(s.addLineStartIfNotCovered(n),s.addBreak(),d++):(s.ensureLine(n),s.addText(h,c,u),d+=h.length),n=null}}});s.addLineStartIfNotCovered(n),this.openWidget=a>i,this.openMarks=a}forward(e,r){this.old.advance(r-e,1,{skip:(n,s,i)=>{(n.isText()||i==n.length)&&this.cache.add(n)},enter:n=>this.cache.add(n),leave:()=>{},break:()=>{}})}getCompositionContext(e){let r=[],n=null;for(let s=e.parentNode;;s=s.parentNode){let i=ns.get(s);if(s==this.view.contentDOM)break;i instanceof xi?r.push(i):i?.isLine()?n=i:s.nodeName=="DIV"&&!n&&s!=this.view.contentDOM?n=new iu(s,OP):r.push(xi.of(new fh({tagName:s.nodeName.toLowerCase(),attributes:Z3(s)}),s))}return{line:n,marks:r}}}function qw(t,e){let r=n=>{for(let s of n.children)if((e?s.isText():s.length)||r(s))return!0;return!1};return r(t)}function E4(t){let e=t.isReplace?(t.startSide<0?64:0)|(t.endSide>0?128:0):t.startSide>0?32:16;return t.block&&(e|=256),e}const OP={class:"cm-line"};function k4(t,e){let r=e.spec.attributes,n=e.spec.class;return!r&&!n||(t||(t={class:"cm-line"}),r&&T_(r,t),n&&(t.class+=" "+n)),t}function P4(t){let e=[];for(let r=t.parents.length;r>1;r--){let n=r==t.parents.length?t.tile:t.parents[r].tile;n instanceof xi&&e.push(n.mark)}return e}function Yg(t){let e=ns.get(t);return e&&e.setDOM(t.cloneNode()),t}class au extends dl{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}au.inline=new au("span");au.block=new au("div");const Xg=new class extends dl{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Kw{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=lr.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new Sm(e,e.contentDOM),this.updateInner([new Ki(0,0,0,e.state.doc.length)],null)}update(e){var r;let n=e.changedRanges;this.minWidth>0&&n.length&&(n.every(({fromA:u,toA:d})=>d<this.minWidthFrom||u>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((r=this.domChanged)===null||r===void 0)&&r.newSel?s=this.domChanged.newSel.head:!j4(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let i=s>-1?R4(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:u,to:d}=this.hasComposition;n=new Ki(u,d,e.changes.mapPos(u,-1),e.changes.mapPos(d,1)).addToSet(n.slice())}this.hasComposition=i?{from:i.range.fromB,to:i.range.toB}:null,(tt.ie||tt.chrome)&&!i&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let a=this.decorations,o=this.blockWrappers;this.updateDeco();let l=L4(a,this.decorations,e.changes);l.length&&(n=Ki.extendWithRanges(n,l));let c=M4(o,this.blockWrappers,e.changes);return c.length&&(n=Ki.extendWithRanges(n,c)),i&&!n.some(u=>u.fromA<=i.range.fromA&&u.toA>=i.range.toA)&&(n=i.range.addToSet(n.slice())),this.tile.flags&2&&n.length==0?!1:(this.updateInner(n,i),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,r){this.view.viewState.mustMeasureContent=!0;let{observer:n}=this.view;n.ignore(()=>{if(r||e.length){let a=this.tile,o=new A4(this.view,a,this.blockWrappers,this.decorations,this.dynamicDecorationMap);this.tile=o.run(e,r),Jv(a,o.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let i=tt.chrome||tt.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(i),i&&(i.written||n.selectionRange.focusNode!=i.node||!this.tile.dom.contains(i.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let i of this.tile.children)i.isWidget()&&i.widget instanceof Jg&&s.push(i.dom);n.updateGaps(s)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let r of e.transactions)for(let n of r.effects)n.is(RP)&&(this.editContextFormatting=n.value)}updateSelection(e=!1,r=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:n}=this.tile,s=this.view.root.activeElement,i=s==n,a=!i&&!(this.view.state.facet(sa)||n.tabIndex>-1)&&Ff(n,this.view.observer.selectionRange)&&!(s&&n.contains(s));if(!(i||r||a))return;let o=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,u;
vendor: 10,746 bytes, line 44
44if(l.empty?u=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(u=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),tt.gecko&&l.empty&&!this.hasComposition&&T4(c)){let h=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(h,c.node.childNodes[c.offset]||null)),c=u=new ho(h,0),o=!0}let d=this.view.observer.selectionRange;(o||!d.focusNode||(!fd(c.node,c.offset,d.anchorNode,d.anchorOffset)||!fd(u.node,u.offset,d.focusNode,d.focusOffset))&&!this.suppressWidgetCursorChange(d,l))&&(this.view.observer.ignore(()=>{tt.android&&tt.chrome&&n.contains(d.focusNode)&&O4(d.focusNode,n)&&(n.blur(),n.focus({preventScroll:!0}));let h=Nd(this.view.root);if(h)if(l.empty){if(tt.gecko){let m=I4(c.node,c.offset);if(m&&m!=3){let b=(m==1?pP:mP)(c.node,c.offset);b&&(c=new ho(b.node,b.offset))}}h.collapse(c.node,c.offset),l.bidiLevel!=null&&h.caretBidiLevel!==void 0&&(h.caretBidiLevel=l.bidiLevel)}else if(h.extend){h.collapse(c.node,c.offset);try{h.extend(u.node,u.offset)}catch{}}else{let m=document.createRange();l.anchor>l.head&&([c,u]=[u,c]),m.setEnd(u.node,u.offset),m.setStart(c.node,c.offset),h.removeAllRanges(),h.addRange(m)}a&&this.view.root.activeElement==n&&(n.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,u)),this.impreciseAnchor=c.precise?null:new ho(d.anchorNode,d.anchorOffset),this.impreciseHead=u.precise?null:new ho(d.focusNode,d.focusOffset)}suppressWidgetCursorChange(e,r){return this.hasComposition&&r.empty&&fd(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==r.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,r=e.state.selection.main,n=Nd(e.root),{anchorNode:s,anchorOffset:i}=e.observer.selectionRange;if(!n||!r.empty||!r.assoc||!n.modify)return;let a=this.lineAt(r.head,r.assoc);if(!a)return;let o=a.posAtStart;if(r.head==o||r.head==o+a.length)return;let l=this.coordsAt(r.head,-1),c=this.coordsAt(r.head,1);if(!l||!c||l.bottom>c.top)return;let u=this.domAtPos(r.head+r.assoc,r.assoc);n.collapse(u.node,u.offset),n.modify("move",r.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let d=e.observer.selectionRange;e.docView.posFromDOM(d.anchorNode,d.anchorOffset)!=r.from&&n.collapse(s,i)}posFromDOM(e,r){let n=this.tile.nearest(e);if(!n)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=n.posAtStart;if(n.isComposite()){let i;if(e==n.dom)i=n.dom.childNodes[r];else{let a=ga(e)==0?0:r==0?-1:1;for(;;){let o=e.parentNode;if(o==n.dom)break;a==0&&o.firstChild!=o.lastChild&&(e==o.firstChild?a=-1:a=1),e=o}a<0?i=e:i=e.nextSibling}if(i==n.dom.firstChild)return s;for(;i&&!ns.get(i);)i=i.nextSibling;if(!i)return s+n.length;for(let a=0,o=s;;a++){let l=n.children[a];if(l.dom==i)return o;o+=l.length+l.breakAfter}}else return n.isText()?e==n.dom?s+r:s+(r?n.length:0):s}domAtPos(e,r){let{tile:n,offset:s}=this.tile.resolveBlock(e,r);return n.isWidget()?n.domPosFor(e,r):n.domIn(s,r)}inlineDOMNearPos(e,r){let n,s=-1,i=!1,a,o=-1,l=!1;return this.tile.blockTiles((c,u)=>{if(c.isWidget()){if(c.flags&32&&u>=e)return!0;c.flags&16&&(i=!0)}else{let d=u+c.length;if(u<=e&&(n=c,s=e-u,i=d<e),d>=e&&!a&&(a=c,o=e-u,l=u>e),u>e&&a)return!0}}),!n&&!a?this.domAtPos(e,r):(i&&a?n=null:l&&n&&(a=null),n&&r<0||!a?n.domIn(s,r):a.domIn(o,r))}coordsAt(e,r){let{tile:n,offset:s}=this.tile.resolveBlock(e,r);return n.isWidget()?n.widget instanceof Jg?null:n.coordsInWidget(s,r,!0):n.coordsIn(s,r)}lineAt(e,r){let{tile:n}=this.tile.resolveBlock(e,r);return n.isLine()?n:null}coordsForChar(e){let{tile:r,offset:n}=this.tile.resolveBlock(e,1);if(!r.isLine())return null;function s(i,a){if(i.isComposite())for(let o of i.children){if(o.length>=a){let l=s(o,a);if(l)return l}if(a-=o.length,a<0)break}else if(i.isText()&&a<i.length){let o=ts(i.text,a);if(o==a)return null;let l=Ld(i.dom,a,o).getClientRects();for(let c=0;c<l.length;c++){let u=l[c];if(c==l.length-1||u.top<u.bottom&&u.left<u.right)return u}}return null}return s(r,n)}measureVisibleLineHeights(e){let r=[],{from:n,to:s}=e,i=this.view.contentDOM.clientWidth,a=i>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,o=-1,l=this.view.textDirection==en.LTR,c=0,u=(d,h,m)=>{for(let b=0;b<d.children.length&&!(h>s);b++){let g=d.children[b],p=h+g.length,y=g.dom.getBoundingClientRect(),{height:v}=y;if(m&&!b&&(c+=y.top-m.top),g instanceof Ja)p>n&&u(g,h,y);else if(h>=n&&(c>0&&r.push(-c),r.push(v+c),c=0,a)){let _=g.dom.lastChild,w=_?Wf(_):[];if(w.length){let C=w[w.length-1],A=l?C.right-y.left:y.right-C.left;A>o&&(o=A,this.minWidth=i,this.minWidthFrom=h,this.minWidthTo=p)}}m&&b==d.children.length-1&&(c+=m.bottom-y.bottom),h=p+g.breakAfter}};return u(this.tile,0,null),r}textDirectionAt(e){let{tile:r}=this.tile.resolveBlock(e,1);return getComputedStyle(r.dom).direction=="rtl"?en.RTL:en.LTR}measureTextSize(){let e=this.tile.blockTiles(a=>{if(a.isLine()&&a.children.length&&a.length<=20){let o=0,l;for(let c of a.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let u=Wf(c.dom);if(u.length!=1)return;o+=u[0].width,l=u[0].height}if(o)return{lineHeight:a.dom.getBoundingClientRect().height,charWidth:o/a.length,textHeight:l}}});if(e)return e;let r=document.createElement("div"),n,s,i;return r.className="cm-line",r.style.width="99999px",r.style.position="absolute",r.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(r);let a=Wf(r.firstChild)[0];n=r.getBoundingClientRect().height,s=a&&a.width?a.width/27:7,i=a&&a.height?a.height:n,r.remove()}),{lineHeight:n,charWidth:s,textHeight:i}}computeBlockGapDeco(){let e=[],r=this.view.viewState;for(let n=0,s=0;;s++){let i=s==r.viewports.length?null:r.viewports[s],a=i?i.from-1:this.view.state.doc.length;if(a>n){let o=(r.lineBlockAt(a).bottom-r.lineBlockAt(n).top)/this.view.scaleY;e.push(lr.replace({widget:new Jg(o),block:!0,inclusive:!0,isBlockGap:!0}).range(n,a))}if(!i)break;n=i.to+1}return lr.set(e)}updateDeco(){let e=1,r=this.view.state.facet(Dd).map(i=>(this.dynamicDecorationMap[e++]=typeof i=="function")?i(this.view):i),n=!1,s=this.view.state.facet(LP).map((i,a)=>{let o=typeof i=="function";return o&&(n=!0),o?i(this.view):i});for(s.length&&(this.dynamicDecorationMap[e++]=n,r.push(gr.join(s))),this.decorations=[this.editContextFormatting,...r,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(NP).map(i=>typeof i=="function"?i(this.view):i)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(TP))try{if(c(this.view,e.range,e))return!0}catch(u){Oi(this.view.state,u,"scroll handler")}let{range:r}=e,n=this.coordsAt(r.head,r.empty?r.assoc:r.head>r.anchor?-1:1),s;if(!n)return;!r.empty&&(s=this.coordsAt(r.anchor,r.anchor>r.head?-1:1))&&(n={left:Math.min(n.left,s.left),top:Math.min(n.top,s.top),right:Math.max(n.right,s.right),bottom:Math.max(n.bottom,s.bottom)});let i=D_(this.view),a={left:n.left-i.left,top:n.top-i.top,right:n.right+i.right,bottom:n.bottom+i.bottom},{offsetWidth:o,offsetHeight:l}=this.view.scrollDOM;r4(this.view.scrollDOM,a,r.head<r.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,o),-o),Math.max(Math.min(e.yMargin,l),-l),this.view.textDirection==en.LTR)}lineHasWidget(e){let r=n=>n.isWidget()||n.children.some(r);return r(this.tile.resolveBlock(e,1).tile)}destroy(){Jv(this.tile)}}function Jv(t,e){let r=e?.get(t);if(r!=1){r==null&&t.destroy();for(let n of t.children)Jv(n,e)}}function T4(t){return t.node.nodeType==1&&t.node.firstChild&&(t.offset==0||t.node.childNodes[t.offset-1].contentEditable=="false")&&(t.offset==t.node.childNodes.length||t.node.childNodes[t.offset].contentEditable=="false")}function jP(t,e){let r=t.observer.selectionRange;if(!r.focusNode)return null;let n=pP(r.focusNode,r.focusOffset),s=mP(r.focusNode,r.focusOffset),i=n||s;if(s&&n&&s.node!=n.node){let o=ns.get(s.node);if(!o||o.isText()&&o.text!=s.node.nodeValue)i=s;else if(t.docView.lastCompositionAfterCursor){let l=ns.get(n.node);!l||l.isText()&&l.text!=n.node.nodeValue||(i=s)}}if(t.docView.lastCompositionAfterCursor=i!=n,!i)return null;let a=e-i.offset;return{from:a,to:a+i.node.nodeValue.length,node:i.node}}function R4(t,e,r){let n=jP(t,r);if(!n)return null;let{node:s,from:i,to:a}=n,o=s.nodeValue;if(/[\n\r]/.test(o)||t.state.doc.sliceString(n.from,n.to)!=o)return null;let l=e.invertedDesc;return{range:new Ki(l.mapPos(i),l.mapPos(a),i,a),text:s}}function I4(t,e){return t.nodeType!=1?0:(e&&t.childNodes[e-1].contentEditable=="false"?1:0)|(e<t.childNodes.length&&t.childNodes[e].contentEditable=="false"?2:0)}let N4=class{constructor(){this.changes=[]}compareRange(e,r){qc(e,r,this.changes)}comparePoint(e,r){qc(e,r,this.changes)}boundChange(e){qc(e,e,this.changes)}};function L4(t,e,r){let n=new N4;return gr.compare(t,e,r,n),n.changes}class D4{constructor(){this.changes=[]}compareRange(e,r){qc(e,r,this.changes)}comparePoint(){}boundChange(e){qc(e,e,this.changes)}}function M4(t,e,r){let n=new D4;return gr.compare(t,e,r,n),n.changes}function O4(t,e){for(let r=t;r&&r!=e;r=r.assignedSlot||r.parentNode)if(r.nodeType==1&&r.contentEditable=="false")return!0;return!1}function j4(t,e){let r=!1;return e&&t.iterChangedRanges((n,s)=>{n<e.to&&s>e.from&&(r=!0)}),r}class Jg extends dl{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function $4(t,e,r=1){let n=t.charCategorizer(e),s=t.doc.lineAt(e),i=e-s.from;if(s.length==0)return ke.cursor(e);i==0?r=1:i==s.length&&(r=-1);let a=i,o=i;r<0?a=ts(s.text,i,!1):o=ts(s.text,i);let l=n(s.text.slice(a,o));for(;a>0;){let c=ts(s.text,a,!1);if(n(s.text.slice(c,a))!=l)break;a=c}for(;o<s.length;){let c=ts(s.text,o);if(n(s.text.slice(o,c))!=l)break;o=c}return ke.range(a+s.from,o+s.from)}function B4(t,e,r,n,s){let i=Math.round((n-e.left)*t.defaultCharacterWidth);if(t.lineWrapping&&r.height>t.defaultLineHeight*1.5){let o=t.viewState.heightOracle.textHeight,l=Math.floor((s-r.top-(t.defaultLineHeight-o)*.5)/o);i+=l*t.viewState.heightOracle.lineLength}let a=t.state.sliceDoc(r.from,r.to);return r.from+G3(a,i,t.state.tabSize)}function Qv(t,e,r){let n=t.lineBlockAt(e);if(Array.isArray(n.type)){let s;for(let i of n.type){if(i.from>e)break;if(!(i.to<e)){if(i.from<e&&i.to>e)return i;(!s||i.type==Ls.Text&&(s.type!=i.type||(r<0?i.from<e:i.to>e)))&&(s=i)}}return s||n}return n}
44function F4(t,e,r,n){let s=Qv(t,e.head,e.assoc||-1),i=!n||s.type!=Ls.Text||!(t.lineWrapping||s.widgetLineBreaks)?null:t.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(i){let a=t.dom.getBoundingClientRect(),o=t.textDirectionAt(s.from),l=t.posAtCoords({x:r==(o==en.LTR)?a.right-1:a.left+1,y:(i.top+i.bottom)/2});if(l!=null)return ke.cursor(l,r?-1:1)}return ke.cursor(r?s.to:s.from,r?-1:1)}function Yw(t,e,r,n){let s=t.state.doc.lineAt(e.head),i=t.bidiSpans(s),a=t.textDirectionAt(s.from);for(let o=e,l=null;;){let c=p4(s,i,a,o,r),u=_P;if(!c){if(s.number==(r?t.state.doc.lines:1))return o;u=` 45`,s=t.state.doc.line(s.number+(r?1:-1)),i=t.bidiSpans(s),c=t.visualLineSide(s,!r)}if(l){if(!l(u))return o}else{if(!n)return c;l=n(u)}o=c}}function W4(t,e,r){let n=t.state.charCategorizer(e),s=n(r);return i=>{let a=n(i);return s==Kn.Space&&(s=a),s==a}}function H4(t,e,r,n){let s=e.head,i=r?1:-1;if(s==(r?t.state.doc.length:0))return ke.cursor(s,e.assoc);let a=e.goalColumn,o,l=t.contentDOM.getBoundingClientRect(),c=t.coordsAtPos(s,e.assoc||-1),u=t.documentTop;if(c)a==null&&(a=c.left-l.left),o=i<0?c.top:c.bottom;else{let m=t.viewState.lineBlockAt(s);a==null&&(a=Math.min(l.right-l.left,t.defaultCharacterWidth*(s-m.from))),o=(i<0?m.top:m.bottom)+u}let d=l.left+a,h=n??t.viewState.heightOracle.textHeight>>1;for(let m=0;;m+=10){let b=o+(h+m)*i,g=Zv(t,{x:d,y:b},!1,i);return ke.cursor(g.pos,g.assoc,void 0,a)}}function pd(t,e,r){for(;;){let n=0;for(let s of t)s.between(e-1,e+1,(i,a,o)=>{if(e>i&&e<a){let l=n||r||(e-i<a-e?-1:1);e=l<0?i:a,n=l}});if(!n)return e}}function $P(t,e){let r=null;for(let n=0;n<e.ranges.length;n++){let s=e.ranges[n],i=null;if(s.empty){let a=pd(t,s.from,0);a!=s.from&&(i=ke.cursor(a,-1))}else{let a=pd(t,s.from,-1),o=pd(t,s.to,1);(a!=s.from||o!=s.to)&&(i=ke.range(s.from==s.anchor?a:o,s.from==s.head?a:o))}i&&(r||(r=e.ranges.slice()),r[n]=i)}return r?ke.create(r,e.mainIndex):e}function Qg(t,e,r){let n=pd(t.state.facet(mh).map(s=>s(t)),r.from,e.head>r.from?-1:1);return n==r.from?r:ke.cursor(n,n<r.from?1:-1)}class Oo{constructor(e,r){this.pos=e,this.assoc=r}}function Zv(t,e,r,n){let s=t.contentDOM.getBoundingClientRect(),i=s.top+t.viewState.paddingTop,{x:a,y:o}=e,l=o-i,c;for(;;){if(l<0)return new Oo(0,1);if(l>t.viewState.docHeight)return new Oo(t.state.doc.length,-1);if(c=t.elementAtHeight(l),n==null)break;if(c.type==Ls.Text){let h=t.docView.coordsAt(n<0?c.from:c.to,n);if(h&&(n<0?h.top<=l+i:h.bottom>=l+i))break}let d=t.viewState.heightOracle.textHeight/2;l=n>0?c.bottom+d:c.top-d}if(t.viewport.from>=c.to||t.viewport.to<=c.from){if(r)return null;if(c.type==Ls.Text){let d=B4(t,s,c,a,o);return new Oo(d,d==c.from?1:-1)}}if(c.type!=Ls.Text)return l<(c.top+c.bottom)/2?new Oo(c.from,1):new Oo(c.to,-1);let u=t.docView.lineAt(c.from,2);return(!u||u.length!=c.length)&&(u=t.docView.lineAt(c.from,-2)),BP(t,u,c.from,a,o)}function BP(t,e,r,n,s){let i=-1,a=null,o=1e9,l=1e9,c=s,u=s,d=(h,m)=>{for(let b=0;b<h.length;b++){let g=h[b];if(g.top==g.bottom)continue;let p=g.left>n?g.left-n:g.right<n?n-g.right:0,y=g.top>s?g.top-s:g.bottom<s?s-g.bottom:0;g.top<=u&&g.bottom>=c&&(c=Math.min(g.top,c),u=Math.max(g.bottom,u),y=0),(i<0||(y-l||p-o)<0)&&(i>=0&&l&&o<p&&a.top<=u-2&&a.bottom>=c+2?l=0:(i=m,o=p,l=y,a=g))}};if(e.isText()){for(let m=0;m<e.length;){let b=ts(e.text,m);if(d(Ld(e.dom,m,b).getClientRects(),m),!o&&!l)break;m=b}return n>(a.left+a.right)/2==(Xw(t,i+r)==en.LTR)?new Oo(r+ts(e.text,i),-1):new Oo(r+i,1)}else{if(!e.length)return new Oo(r,1);for(let g=0;g<e.children.length;g++){let p=e.children[g];if(p.flags&48)continue;let y=(p.dom.nodeType==1?p.dom:Ld(p.dom,0,p.length)).getClientRects();if(d(y,g),!o&&!l)break}let h=e.children[i],m=e.posBefore(h,r);return h.isComposite()||h.isText()?BP(t,h,m,Math.max(a.left,Math.min(a.right,n)),s):n>(a.left+a.right)/2==(Xw(t,i+r)==en.LTR)?new Oo(m+h.length,-1):new Oo(m,1)}}function Xw(t,e){let r=t.state.doc.lineAt(e);return t.bidiSpans(r)[ca.find(t.bidiSpans(r),e-r.from,-1,1)].dir}const Zu="ï¿¿";class U4{constructor(e,r){this.points=e,this.text="",this.lineSeparator=r.facet(Cr.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Zu}readRange(e,r){if(!e)return this;let n=e.parentNode;for(let s=e;;){this.findPointBefore(n,s);let i=this.text.length;this.readNode(s);let a=ns.get(s),o=s.nextSibling;if(o==r){a?.breakAfter&&!o&&this.lineBreak();break}let l=ns.get(o);(a&&l?a.breakAfter:(a?a.breakAfter:_p(s))||_p(o)&&(s.nodeName!="BR"||a?.isWidget())&&this.text.length>i)&&!V4(o,r)&&this.lineBreak(),s=o}return this.findPointBefore(n,r),this}readTextNode(e){let r=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,r.length));for(let n=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let i=-1,a=1,o;if(this.lineSeparator?(i=r.indexOf(this.lineSeparator,n),a=this.lineSeparator.length):(o=s.exec(r))&&(i=o.index,a=o[0].length),this.append(r.slice(n,i<0?r.length:i)),i<0)break;if(this.lineBreak(),a>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=a-1);n=i+a}}readNode(e){let r=ns.get(e),n=r&&r.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let s=n.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,r){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==r&&(n.pos=this.text.length)}findPointInside(e,r){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(z4(e,n.node,n.offset)?r:0))}}function z4(t,e,r){for(;;){if(!e||r<ga(e))return!1;if(e==t)return!0;r=il(e)+1,e=e.parentNode}}function V4(t,e){let r;for(;!(t==e||!t);t=t.nextSibling){let n=ns.get(t);if(!n?.isWidget())return!1;
45n&&(r||(r=[])).push(n)}if(r)for(let n of r){let s=n.overrideDOMText;if(s?.length)return!1}return!0}class Jw{constructor(e,r){this.node=e,this.offset=r,this.pos=-1}}class G4{constructor(e,r,n,s){this.typeOver=s,this.bounds=null,this.text="",this.domChanged=r>-1;let{impreciseHead:i,impreciseAnchor:a}=e.docView;if(e.state.readOnly&&r>-1)this.newSel=null;else if(r>-1&&(this.bounds=FP(e.docView.tile,r,n,0))){let o=i||a?[]:K4(e),l=new U4(o,e.state);l.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=l.text,this.newSel=Y4(o,this.bounds.from)}else{let o=e.observer.selectionRange,l=i&&i.node==o.focusNode&&i.offset==o.focusOffset||!Gv(e.contentDOM,o.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(o.focusNode,o.focusOffset),c=a&&a.node==o.anchorNode&&a.offset==o.anchorOffset||!Gv(e.contentDOM,o.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(o.anchorNode,o.anchorOffset),u=e.viewport;if((tt.ios||tt.chrome)&&e.state.selection.main.empty&&l!=c&&(u.from>0||u.to<e.state.doc.length)){let d=Math.min(l,c),h=Math.max(l,c),m=u.from-d,b=u.to-h;(m==0||m==1||d==0)&&(b==0||b==-1||h==e.state.doc.length)&&(l=0,c=e.state.doc.length)}e.inputState.composing>-1&&e.state.selection.ranges.length>1?this.newSel=e.state.selection.replaceRange(ke.range(c,l)):this.newSel=ke.single(c,l)}}}function FP(t,e,r,n){if(t.isComposite()){let s=-1,i=-1,a=-1,o=-1;for(let l=0,c=n,u=n;l<t.children.length;l++){let d=t.children[l],h=c+d.length;if(c<e&&h>r)return FP(d,e,r,c);if(h>=e&&s==-1&&(s=l,i=c),c>r&&d.dom.parentNode==t.dom){a=l,o=u;break}u=h,c=h+d.breakAfter}return{from:i,to:o<0?n+t.length:o,startDOM:(s?t.children[s-1].dom.nextSibling:null)||t.dom.firstChild,endDOM:a<t.children.length&&a>=0?t.children[a].dom:null}}else return t.isText()?{from:n,to:n+t.length,startDOM:t.dom,endDOM:t.dom.nextSibling}:null}function WP(t,e){let r,{newSel:n}=e,s=t.state.selection.main,i=t.inputState.lastKeyTime>Date.now()-100?t.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:o}=e.bounds,l=s.from,c=null;(i===8||tt.android&&e.text.length<o-a)&&(l=s.to,c="end");let u=HP(t.state.doc.sliceString(a,o,Zu),e.text,l-a,c);u&&(tt.chrome&&i==13&&u.toB==u.from+2&&e.text.slice(u.from,u.toB)==Zu+Zu&&u.toB--,r={from:a+u.from,to:a+u.toA,insert:Mr.of(e.text.slice(u.from,u.toB).split(Zu))})}else n&&(!t.hasFocus&&t.state.facet(sa)||n.main.eq(s))&&(n=null);if(!r&&!n)return!1;if(!r&&e.typeOver&&!s.empty&&n&&n.main.empty?r={from:s.from,to:s.to,insert:t.state.doc.slice(s.from,s.to)}:(tt.mac||tt.android)&&r&&r.from==r.to&&r.from==s.head-1&&/^\. ?$/.test(r.insert.toString())&&t.contentDOM.getAttribute("autocorrect")=="off"?(n&&r.insert.length==2&&(n=ke.single(n.main.anchor-1,n.main.head-1)),r={from:r.from,to:r.to,insert:Mr.of([r.insert.toString().replace("."," ")])}):r&&r.from>=s.from&&r.to<=s.to&&(r.from!=s.from||r.to!=s.to)&&s.to-s.from-(r.to-r.from)<=4?r={from:s.from,to:s.to,insert:t.state.doc.slice(s.from,r.from).append(r.insert).append(t.state.doc.slice(r.to,s.to))}:t.state.doc.lineAt(s.from).to<s.to&&t.docView.lineHasWidget(s.to)&&t.inputState.insertingTextAt>Date.now()-50?r={from:s.from,to:s.to,insert:t.state.toText(t.inputState.insertingText)}:tt.chrome&&r&&r.from==r.to&&r.from==s.head&&r.insert.toString()==` 46 `&&t.lineWrapping&&(n&&(n=ke.single(n.main.anchor-1,n.main.head-1)),r={from:s.from,to:s.to,insert:Mr.of([" "])}),r)return M_(t,r,n,i);if(n&&!n.main.eq(s)){let a=!1,o="select";return t.inputState.lastSelectionTime>Date.now()-50&&(t.inputState.lastSelectionOrigin=="select"&&(a=!0),o=t.inputState.lastSelectionOrigin,o=="select.pointer"&&(n=$P(t.state.facet(mh).map(l=>
vendor: 2,896 bytes, line 46
46l(t)),n))),t.dispatch({selection:n,scrollIntoView:a,userEvent:o}),!0}else return!1}function M_(t,e,r,n=-1){if(tt.ios&&t.inputState.flushIOSKey(e))return!0;let s=t.state.selection.main;if(tt.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&t.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Kc(t.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||n==8&&e.insert.length<e.to-e.from&&e.to>s.head)&&Kc(t.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Kc(t.contentDOM,"Delete",46)))return!0;let i=e.insert.toString();t.inputState.composing>=0&&t.inputState.composing++;let a,o=()=>a||(a=q4(t,e,r));return t.state.facet(AP).some(l=>l(t,e.from,e.to,i,o))||t.dispatch(o()),!0}function q4(t,e,r){let n,s=t.state,i=s.selection.main,a=-1;if(e.from==e.to&&e.from<i.from||e.from>i.to){let l=e.from<i.from?-1:1,c=l<0?i.from:i.to,u=pd(s.facet(mh).map(d=>d(t)),c,l);e.from==u&&(a=u)}if(a>-1)n={changes:e,selection:ke.cursor(e.from+e.insert.length,-1)};else if(e.from>=i.from&&e.to<=i.to&&e.to-e.from>=(i.to-i.from)/3&&(!r||r.main.empty&&r.main.from==e.from+e.insert.length)&&t.inputState.composing<0){let l=i.from<e.from?s.sliceDoc(i.from,e.from):"",c=i.to>e.to?s.sliceDoc(e.to,i.to):"";n=s.replaceSelection(t.state.toText(l+e.insert.sliceString(0,void 0,t.state.lineBreak)+c))}else{let l=s.changes(e),c=r&&r.main.to<=l.newLength?r.main:void 0;if(s.selection.ranges.length>1&&(t.inputState.composing>=0||t.inputState.compositionPendingChange)&&e.to<=i.to+10&&e.to>=i.to-10){let u=t.state.sliceDoc(e.from,e.to),d,h=r&&jP(t,r.main.head);if(h){let b=e.insert.length-(e.to-e.from);d={from:h.from,to:h.to-b}}else d=t.state.doc.lineAt(i.head);let m=i.to-e.to;n=s.changeByRange(b=>{if(b.from==i.from&&b.to==i.to)return{changes:l,range:c||b.map(l)};let g=b.to-m,p=g-u.length;if(t.state.sliceDoc(p,g)!=u||g>=d.from&&p<=d.to)return{range:b};let y=s.changes({from:p,to:g,insert:e.insert}),v=b.to-i.to;return{changes:y,range:c?ke.range(Math.max(0,c.anchor+v),Math.max(0,c.head+v)):b.map(y)}})}else n={changes:l,selection:c&&s.selection.replaceRange(c)}}let o="input.type";return(t.composing||t.inputState.compositionPendingChange&&t.inputState.compositionEndedAt>Date.now()-50)&&(t.inputState.compositionPendingChange=!1,o+=".compose",t.inputState.compositionFirstChange&&(o+=".start",t.inputState.compositionFirstChange=!1)),s.update(n,{userEvent:o,scrollIntoView:!0})}function HP(t,e,r,n){let s=Math.min(t.length,e.length),i=0;for(;i<s&&t.charCodeAt(i)==e.charCodeAt(i);)i++;if(i==s&&t.length==e.length)return null;let a=t.length,o=e.length;for(;a>0&&o>0&&t.charCodeAt(a-1)==e.charCodeAt(o-1);)a--,o--;if(n=="end"){let l=Math.max(0,i-Math.min(a,o));r-=a+l-i}if(a<i&&t.length<e.length){let l=r<=i&&r>=a?i-r:0;i-=l,o=i+(o-a),a=i}else if(o<i){let l=r<=i&&r>=o?i-r:0;i-=l,a=i+(a-o),o=i}return{from:i,toA:a,toB:o}}function K4(t){let e=[];
vendor: 17,999 bytes, line 46
46if(t.root.activeElement!=t.contentDOM)return e;let{anchorNode:r,anchorOffset:n,focusNode:s,focusOffset:i}=t.observer.selectionRange;return r&&(e.push(new Jw(r,n)),(s!=r||i!=n)&&e.push(new Jw(s,i))),e}function Y4(t,e){if(t.length==0)return null;let r=t[0].pos,n=t.length==2?t[1].pos:r;return r>-1&&n>-1?ke.single(r+e,n+e):null}class X4{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,tt.safari&&e.contentDOM.addEventListener("input",()=>null),tt.gecko&&dW(e.contentDOM.ownerDocument)}handleEvent(e){!sW(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,r){let n=this.handlers[e];if(n){for(let s of n.observers)s(this.view,r);for(let s of n.handlers){if(r.defaultPrevented)break;if(s(this.view,r)){r.preventDefault();break}}}}ensureHandlers(e){let r=J4(e),n=this.handlers,s=this.view.contentDOM;for(let i in r)if(i!="scroll"){let a=!r[i].handlers.length,o=n[i];o&&a!=!o.handlers.length&&(s.removeEventListener(i,this.handleEvent),o=null),o||s.addEventListener(i,this.handleEvent,{passive:a})}for(let i in n)i!="scroll"&&!r[i]&&s.removeEventListener(i,this.handleEvent);this.handlers=r}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&zP.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),tt.android&&tt.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let r;return tt.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&((r=UP.find(n=>n.keyCode==e.keyCode))&&!e.ctrlKey||Q4.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=r||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let r=this.pendingIOSKey;return!r||r.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,Kc(this.view.contentDOM,r.key,r.keyCode,r instanceof KeyboardEvent?r:void 0))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:tt.safari&&!tt.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Qw(t,e){return(r,n)=>{try{return e.call(t,n,r)}catch(s){Oi(r.state,s)}}}function J4(t){let e=Object.create(null);function r(n){return e[n]||(e[n]={observers:[],handlers:[]})}for(let n of t){let s=n.spec,i=s&&s.plugin.domEventHandlers,a=s&&s.plugin.domEventObservers;if(i)for(let o in i){let l=i[o];l&&r(o).handlers.push(Qw(n.value,l))}if(a)for(let o in a){let l=a[o];l&&r(o).observers.push(Qw(n.value,l))}}for(let n in go)r(n).handlers.push(go[n]);for(let n in eo)r(n).observers.push(eo[n]);return e}const UP=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Q4="dthko",zP=[16,17,18,20,91,92,224,225],nf=6;function sf(t){return Math.max(0,t)*.7+8}function Z4(t,e){return Math.max(Math.abs(t.clientX-e.clientX),Math.abs(t.clientY-e.clientY))}class eW{constructor(e,r,n,s){this.view=e,this.startEvent=r,this.style=n,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=r,this.scrollParents=n4(e.contentDOM),this.atoms=e.state.facet(mh).map(a=>a(e));let i=e.contentDOM.ownerDocument;i.addEventListener("mousemove",this.move=this.move.bind(this)),i.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=r.shiftKey,this.multiple=e.state.facet(Cr.allowMultipleSelections)&&tW(e,r),this.dragging=nW(e,r)&&qP(r)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Z4(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let r=0,n=0,s=0,i=0,a=this.view.win.innerWidth,o=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:a}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:i,bottom:o}=this.scrollParents.y.getBoundingClientRect());let l=D_(this.view);e.clientX-l.left<=s+nf?r=-sf(s-e.clientX):e.clientX+l.right>=a-nf&&(r=sf(e.clientX-a)),e.clientY-l.top<=i+nf?n=-sf(i-e.clientY):e.clientY+l.bottom>=o-nf&&(n=sf(e.clientY-o)),this.setScrollSpeed(r,n)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,r){this.scrollSpeed={x:e,y:r},e||r?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:r}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),r&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=r,r=0),(e||r)&&this.view.win.scrollBy(e,r),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:r}=this,n=$P(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!n.eq(r.state.selection,this.dragging===!1))&&this.view.dispatch({selection:n,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(r=>r.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function tW(t,e){let r=t.state.facet(xP);return r.length?r[0](e):tt.mac?e.metaKey:e.ctrlKey}function rW(t,e){let r=t.state.facet(wP);return r.length?r[0](e):tt.mac?!e.altKey:!e.ctrlKey}function nW(t,e){let{main:r}=t.state.selection;if(r.empty)return!1;let n=Nd(t.root);if(!n||n.rangeCount==0)return!0;let s=n.getRangeAt(0).getClientRects();for(let i=0;i<s.length;i++){let a=s[i];if(a.left<=e.clientX&&a.right>=e.clientX&&a.top<=e.clientY&&a.bottom>=e.clientY)return!0}return!1}function sW(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let r=e.target,n;r!=t.contentDOM;r=r.parentNode)if(!r||r.nodeType==11||(n=ns.get(r))&&n.isWidget()&&!n.isHidden&&n.widget.ignoreEvent(e))return!1;return!0}const go=Object.create(null),eo=Object.create(null),VP=tt.ie&&tt.ie_version<15||tt.ios&&tt.webkit_version<604;function iW(t){let e=t.dom.parentNode;if(!e)return;let r=e.appendChild(document.createElement("textarea"));r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus(),setTimeout(()=>{t.focus(),r.remove(),GP(t,r.value)},50)}function Cm(t,e,r){for(let n of t.facet(e))r=n(r,t);return r}function GP(t,e){e=Cm(t.state,N_,e);let{state:r}=t,n,s=1,i=r.toText(e),a=i.lines==r.selection.ranges.length;if(ey!=null&&r.selection.ranges.every(l=>l.empty)&&ey==i.toString()){let l=-1;n=r.changeByRange(c=>{let u=r.doc.lineAt(c.from);if(u.from==l)return{range:c};l=u.from;let d=r.toText((a?i.line(s++).text:e)+r.lineBreak);return{changes:{from:u.from,insert:d},range:ke.cursor(c.from+d.length)}})}else a?n=r.changeByRange(l=>{let c=i.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:ke.cursor(l.from+c.length)}}):n=r.replaceSelection(i);t.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}eo.scroll=t=>{t.inputState.lastScrollTop=t.scrollDOM.scrollTop,t.inputState.lastScrollLeft=t.scrollDOM.scrollLeft};go.keydown=(t,e)=>(t.inputState.setSelectionOrigin("select"),e.keyCode==27&&t.inputState.tabFocusMode!=0&&(t.inputState.tabFocusMode=Date.now()+2e3),!1);eo.touchstart=(t,e)=>{t.inputState.lastTouchTime=Date.now(),t.inputState.setSelectionOrigin("select.pointer")};eo.touchmove=t=>{t.inputState.setSelectionOrigin("select.pointer")};go.mousedown=(t,e)=>{if(t.observer.flush(),t.inputState.lastTouchTime>Date.now()-2e3)return!1;let r=null;for(let n of t.state.facet(SP))if(r=n(t,e),r)break;if(!r&&e.button==0&&(r=aW(t,e)),r){let n=!t.hasFocus;t.inputState.startMouseSelection(new eW(t,e,r,n)),n&&t.observer.ignore(()=>{hP(t.contentDOM);let i=t.root.activeElement;i&&!i.contains(t.contentDOM)&&i.blur()});let s=t.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else t.inputState.setSelectionOrigin("select.pointer");return!1};function Zw(t,e,r,n){if(n==1)return ke.cursor(e,r);if(n==2)return $4(t.state,e,r);{let s=t.docView.lineAt(e,r),i=t.state.doc.lineAt(s?s.posAtEnd:e),a=s?s.posAtStart:i.from,o=s?s.posAtEnd:i.to;return o<t.state.doc.length&&o==i.to&&o++,ke.range(a,o)}}const oW=tt.ie&&tt.ie_version<=11;let eS=null,tS=0,rS=0;function qP(t){if(!oW)return t.detail;let e=eS,r=rS;return eS=t,rS=Date.now(),tS=!e||r>Date.now()-400&&Math.abs(e.clientX-t.clientX)<2&&Math.abs(e.clientY-t.clientY)<2?(tS+1)%3:1}function aW(t,e){let r=t.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),n=qP(e),s=t.state.selection;return{update(i){i.docChanged&&(r.pos=i.changes.mapPos(r.pos),s=s.map(i.changes))},get(i,a,o){let l=t.posAndSideAtCoords({x:i.clientX,y:i.clientY},!1),c,u=Zw(t,l.pos,l.assoc,n);if(r.pos!=l.pos&&!a){let d=Zw(t,r.pos,r.assoc,n),h=Math.min(d.from,u.from),m=Math.max(d.to,u.to);u=h<u.from?ke.range(h,m):ke.range(m,h)}return a?s.replaceRange(s.main.extend(u.from,u.to)):o&&n==1&&s.ranges.length>1&&(c=lW(s,l.pos))?c:o?s.addRange(u):ke.create([u])}}}function lW(t,e){for(let r=0;r<t.ranges.length;r++){let{from:n,to:s}=t.ranges[r];if(n<=e&&s>=e)return ke.create(t.ranges.slice(0,r).concat(t.ranges.slice(r+1)),t.mainIndex==r?0:t.mainIndex-(t.mainIndex>r?1:0))}return null}go.dragstart=(t,e)=>{let{selection:{main:r}}=t.state;if(e.target.draggable){let s=t.docView.tile.nearest(e.target);if(s&&s.isWidget()){let i=s.posAtStart,a=i+s.length;(i>=r.to||a<=r.from)&&(r=ke.range(i,a))}}let{inputState:n}=t;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=r,e.dataTransfer&&(e.dataTransfer.setData("Text",Cm(t.state,L_,t.state.sliceDoc(r.from,r.to))),e.dataTransfer.effectAllowed="copyMove"),!1};go.dragend=t=>(t.inputState.draggedContent=null,!1);function nS(t,e,r,n){if(r=Cm(t.state,N_,r),!r)return;let s=t.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:i}=t.inputState,a=n&&i&&rW(t,e)?{from:i.from,to:i.to}:null,o={from:s,insert:r},l=t.state.changes(a?[a,o]:o);t.focus(),t.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:a?"move.drop":"input.drop"}),t.inputState.draggedContent=null}go.drop=(t,e)=>{if(!e.dataTransfer)return!1;if(t.state.readOnly)return!0;let r=e.dataTransfer.files;if(r&&r.length){let n=Array(r.length),s=0,i=()=>{++s==r.length&&nS(t,e,n.filter(a=>a!=null).join(t.state.lineBreak),!1)};for(let a=0;a<r.length;a++){let o=new FileReader;o.onerror=i,o.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(o.result)||(n[a]=o.result),i()},o.readAsText(r[a])}return!0}else{let n=e.dataTransfer.getData("Text");if(n)return nS(t,e,n,!0),!0}return!1};go.paste=(t,e)=>{if(t.state.readOnly)return!0;t.observer.flush();let r=VP?null:e.clipboardData;return r?(GP(t,r.getData("text/plain")||r.getData("text/uri-list")),!0):(iW(t),!1)};function cW(t,e){let r=t.dom.parentNode;if(!r)return;let n=r.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout(()=>{n.remove(),t.focus()},50)}function uW(t){let e=[],r=[],n=!1;for(let s of t.selection.ranges)s.empty||(e.push(t.sliceDoc(s.from,s.to)),r.push(s));if(!e.length){let s=-1;for(let{from:i}of t.selection.ranges){let a=t.doc.lineAt(i);a.number>s&&(e.push(a.text),r.push({from:a.from,to:Math.min(t.doc.length,a.to+1)})),s=a.number}n=!0}return{text:Cm(t,L_,e.join(t.lineBreak)),ranges:r,linewise:n}}let ey=null;go.copy=go.cut=(t,e)=>{let{text:r,ranges:n,linewise:s}=uW(t.state);if(!r&&!s)return!1;ey=s?r:null,e.type=="cut"&&!t.state.readOnly&&t.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let i=VP?null:e.clipboardData;return i?(i.clearData(),i.setData("text/plain",r),!0):(cW(t,r),!1)};const KP=xa.define();function YP(t,e){let r=[];for(let n of t.facet(EP)){let s=n(t,e);s&&r.push(s)}return r.length?t.update({effects:r,annotations:KP.of(!0)}):null}function XP(t){setTimeout(()=>{let e=t.hasFocus;if(e!=t.inputState.notifiedFocused){let r=YP(t.state,e);r?t.dispatch(r):t.update([])}},10)}eo.focus=t=>{t.inputState.lastFocusTime=Date.now(),!t.scrollDOM.scrollTop&&(t.inputState.lastScrollTop||t.inputState.lastScrollLeft)&&(t.scrollDOM.scrollTop=t.inputState.lastScrollTop,t.scrollDOM.scrollLeft=t.inputState.lastScrollLeft),XP(t)};eo.blur=t=>{t.observer.clearSelectionRange(),XP(t)};eo.compositionstart=eo.compositionupdate=t=>{t.observer.editContext||(t.inputState.compositionFirstChange==null&&(t.inputState.compositionFirstChange=!0),t.inputState.composing<0&&(t.inputState.composing=0))};eo.compositionend=t=>{t.observer.editContext||(t.inputState.composing=-1,t.inputState.compositionEndedAt=Date.now(),t.inputState.compositionPendingKey=!0,t.inputState.compositionPendingChange=t.observer.pendingRecords().length>0,t.inputState.compositionFirstChange=null,tt.chrome&&tt.android?t.observer.flushSoon():t.inputState.compositionPendingChange?Promise.resolve().then(()=>t.observer.flush()):setTimeout(()=>{t.inputState.composing<0&&t.docView.hasComposition&&t.update([])},50))};eo.contextmenu=t=>{t.inputState.lastContextMenu=Date.now()};go.beforeinput=(t,e)=>{var r,n;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(t.inputState.insertingText=e.data,t.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&t.observer.editContext){let i=(r=e.dataTransfer)===null||r===void 0?void 0:r.getData("text/plain"),a=e.getTargetRanges();if(i&&a.length){let o=a[0],l=t.posAtDOM(o.startContainer,o.startOffset),c=t.posAtDOM(o.endContainer,o.endOffset);return M_(t,{from:l,to:c,insert:t.state.toText(i)},null),!0}}let s;if(tt.chrome&&tt.android&&(s=UP.find(i=>i.inputType==e.inputType))&&(t.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let i=((n=window.visualViewport)===null||n===void 0?void 0:n.height)||0;setTimeout(()=>{var a;(((a=window.visualViewport)===null||a===void 0?void 0:a.height)||0)>i+10&&t.hasFocus&&(t.contentDOM.blur(),t.focus())},100)}return tt.ios&&e.inputType=="deleteContentForward"&&t.observer.flushSoon(),tt.safari&&e.inputType=="insertText"&&t.inputState.composing>=0&&setTimeout(()=>eo.compositionend(t,e),20),!1};const sS=new Set;function dW(t){sS.has(t)||(sS.add(t),t.addEventListener("copy",()=>{}),t.addEventListener("cut",()=>{}))}const iS=["pre-wrap","normal","pre-line","break-spaces"];let lu=!1;function oS(){lu=!1}class hW{constructor(e){this.lineWrapping=e,this.doc=Mr.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,r){let n=this.doc.lineAt(r).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((r-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return iS.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let r=!1;for(let n=0;n<e.length;n++){let s=e[n];s<0?n++:this.heightSamples[Math.floor(s*10)]||(r=!0,this.heightSamples[Math.floor(s*10)]=!0)}return r}refresh(e,r,n,s,i,a){let o=iS.indexOf(e)>-1,l=Math.round(r)!=Math.round(this.lineHeight)||this.lineWrapping!=o;if(this.lineWrapping=o,this.lineHeight=r,this.charWidth=n,this.textHeight=s,this.lineLength=i,l){this.heightSamples={};for(let c=0;c<a.length;c++){let u=a[c];u<0?c++:this.heightSamples[Math.floor(u*10)]=!0}}return l}}class fW{constructor(e,r){this.from=e,this.heights=r,this.index=0}get more(){return this.index<this.heights.length}}class co{constructor(e,r,n,s,i){this.from=e,this.length=r,this.top=n,this.height=s,this._content=i}get type(){return typeof this._content=="number"?Ls.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof ac?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(e){let r=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(e._content)?e._content:[e]);return new co(this.from,this.length+e.length,this.top,this.height+e.height,r)}}var Zr=function(t){return t[t.ByPos=0]="ByPos",t[t.ByHeight=1]="ByHeight",t[t.ByPosNoHeight=2]="ByPosNoHeight",t}(Zr||(Zr={}));const Hf=.001;class oi{constructor(e,r,n=2){this.length=e,this.height=r,this.flags=n}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Hf&&(lu=!0),this.height=e)}replace(e,r,n){return oi.of(n)}
vendor: 6,134 bytes, line 46
46decomposeLeft(e,r){r.push(this)}decomposeRight(e,r){r.push(this)}applyChanges(e,r,n,s){let i=this,a=n.doc;for(let o=s.length-1;o>=0;o--){let{fromA:l,toA:c,fromB:u,toB:d}=s[o],h=i.lineAt(l,Zr.ByPosNoHeight,n.setDoc(r),0,0),m=h.to>=c?h:i.lineAt(c,Zr.ByPosNoHeight,n,0,0);for(d+=m.to-c,c=m.to;o>0&&h.from<=s[o-1].toA;)l=s[o-1].fromA,u=s[o-1].fromB,o--,l<h.from&&(h=i.lineAt(l,Zr.ByPosNoHeight,n,0,0));u+=h.from-l,l=h.from;let b=O_.build(n.setDoc(a),e,u,d);i=Ap(i,i.replace(l,c,b))}return i.updateHeight(n,0)}static empty(){return new Li(0,0,0)}static of(e){if(e.length==1)return e[0];let r=0,n=e.length,s=0,i=0;for(;;)if(r==n)if(s>i*2){let o=e[r-1];o.break?e.splice(--r,1,o.left,null,o.right):e.splice(--r,1,o.left,o.right),n+=1+o.break,s-=o.size}else if(i>s*2){let o=e[n];o.break?e.splice(n,1,o.left,null,o.right):e.splice(n,1,o.left,o.right),n+=2+o.break,i-=o.size}else break;else if(s<i){let o=e[r++];o&&(s+=o.size)}else{let o=e[--n];o&&(i+=o.size)}let a=0;return e[r-1]==null?(a=1,r--):e[r]==null&&(a=1,n++),new mW(oi.of(e.slice(0,r)),a,oi.of(e.slice(n)))}}function Ap(t,e){return t==e?t:(t.constructor!=e.constructor&&(lu=!0),e)}oi.prototype.size=1;const pW=lr.replace({});class JP extends oi{constructor(e,r,n){super(e,r),this.deco=n,this.spaceAbove=0}mainBlock(e,r){return new co(r,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(e,r,n,s){return this.spaceAbove&&e<n+this.spaceAbove?new co(s,0,n,this.spaceAbove,pW):this.mainBlock(n,s)}lineAt(e,r,n,s,i){let a=this.mainBlock(s,i);return this.spaceAbove?this.blockAt(0,n,s,i).join(a):a}forEachLine(e,r,n,s,i,a){e<=i+this.length&&r>=i&&a(this.lineAt(0,Zr.ByPos,n,s,i))}setMeasuredHeight(e){let r=e.heights[e.index++];r<0?(this.spaceAbove=-r,r=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(r)}updateHeight(e,r=0,n=!1,s){return s&&s.from<=r&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class Li extends JP{constructor(e,r,n){super(e,r,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=n}mainBlock(e,r){return new co(r,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,r,n){let s=n[0];return n.length==1&&(s instanceof Li||s instanceof Is&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof Is?s=new Li(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):oi.of(n)}updateHeight(e,r=0,n=!1,s){return s&&s.from<=r&&s.more?this.setMeasuredHeight(s):(n||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class Is extends oi{constructor(e){super(e,0)}heightMetrics(e,r){let n=e.doc.lineAt(r).number,s=e.doc.lineAt(r+this.length).number,i=s-n+1,a,o=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*i);a=l/i,this.length>i+1&&(o=(this.height-l)/(this.length-i-1))}else a=this.height/i;return{firstLine:n,lastLine:s,perLine:a,perChar:o}}blockAt(e,r,n,s){let{firstLine:i,lastLine:a,perLine:o,perChar:l}=this.heightMetrics(r,s);if(r.lineWrapping){let c=s+(e<r.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-n)/this.height))*this.length)),u=r.doc.lineAt(c),d=o+u.length*l,h=Math.max(n,e-d/2);return new co(u.from,u.length,h,d,0)}else{let c=Math.max(0,Math.min(a-i,Math.floor((e-n)/o))),{from:u,length:d}=r.doc.line(i+c);return new co(u,d,n+o*c,o,0)}}lineAt(e,r,n,s,i){if(r==Zr.ByHeight)return this.blockAt(e,n,s,i);if(r==Zr.ByPosNoHeight){let{from:m,to:b}=n.doc.lineAt(e);return new co(m,b-m,0,0,0)}let{firstLine:a,perLine:o,perChar:l}=this.heightMetrics(n,i),c=n.doc.lineAt(e),u=o+c.length*l,d=c.number-a,h=s+o*d+l*(c.from-i-d);return new co(c.from,c.length,Math.max(s,Math.min(h,s+this.height-u)),u,0)}forEachLine(e,r,n,s,i,a){e=Math.max(e,i),r=Math.min(r,i+this.length);let{firstLine:o,perLine:l,perChar:c}=this.heightMetrics(n,i);for(let u=e,d=s;u<=r;){let h=n.doc.lineAt(u);if(u==e){let b=h.number-o;d+=l*b+c*(e-i-b)}let m=l+c*h.length;a(new co(h.from,h.length,d,m,0)),d+=m,u=h.to+1}}replace(e,r,n){let s=this.length-r;if(s>0){let i=n[n.length-1];i instanceof Is?n[n.length-1]=new Is(i.length+s):n.push(null,new Is(s-1))}if(e>0){let i=n[0];i instanceof Is?n[0]=new Is(e+i.length):n.unshift(new Is(e-1),null)}return oi.of(n)}decomposeLeft(e,r){r.push(new Is(e-1),null)}decomposeRight(e,r){r.push(null,new Is(this.length-e-1))}updateHeight(e,r=0,n=!1,s){let i=r+this.length;if(s&&s.from<=r+this.length&&s.more){let a=[],o=Math.max(r,s.from),l=-1;for(s.from>r&&a.push(new Is(s.from-r-1).updateHeight(e,r));o<=i&&s.more;){let u=e.doc.lineAt(o).length;a.length&&a.push(null);let d=s.heights[s.index++],h=0;d<0&&(h=-d,d=s.heights[s.index++]),l==-1?l=d:Math.abs(d-l)>=Hf&&(l=-2);let m=new Li(u,d,h);m.outdated=!1,a.push(m),o+=u+1}o<=i&&a.push(null,new Is(i-o).updateHeight(e,o));let c=oi.of(a);return(l<0||Math.abs(c.height-this.height)>=Hf||Math.abs(l-this.heightMetrics(e,r).perLine)>=Hf)&&(lu=!0),Ap(this,c)}else(n||this.outdated)&&(this.setHeight(e.heightForGap(r,r+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class mW extends oi{constructor(e,r,n){super(e.length+r+n.length,e.height+n.height,r|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return this.flags&1}blockAt(e,r,n,s){let i=n+this.left.height;return e<i?this.left.blockAt(e,r,n,s):this.right.blockAt(e,r,i,s+this.left.length+this.break)}lineAt(e,r,n,s,i){let a=s+this.left.height,o=i+this.left.length+this.break,l=r==Zr.ByHeight?e<a:e<o,c=l?this.left.lineAt(e,r,n,s,i):this.right.lineAt(e,r,n,a,o);if(this.break||(l?c.to<o:c.from>o))return c;let u=r==Zr.ByPosNoHeight?Zr.ByPosNoHeight:Zr.ByPos;return l?c.join(this.right.lineAt(o,u,n,a,o)):this.left.lineAt(o,u,n,s,i).join(c)}forEachLine(e,r,n,s,i,a){let o=s+this.left.height,l=i+this.left.length+this.break;if(this.break)e<l&&this.left.forEachLine(e,r,n,s,i,a),r>=l&&this.right.forEachLine(e,r,n,o,l,a);else{let c=this.lineAt(l,Zr.ByPos,n,s,i);
vendor: 30,107 bytes, line 46
46e<c.from&&this.left.forEachLine(e,c.from-1,n,s,i,a),c.to>=e&&c.from<=r&&a(c),r>c.to&&this.right.forEachLine(c.to+1,r,n,o,l,a)}}replace(e,r,n){let s=this.left.length+this.break;if(r<s)return this.balanced(this.left.replace(e,r,n),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-s,r-s,n));let i=[];e>0&&this.decomposeLeft(e,i);let a=i.length;for(let o of n)i.push(o);if(e>0&&aS(i,a-1),r<this.length){let o=i.length;this.decomposeRight(r,i),aS(i,o)}return oi.of(i)}decomposeLeft(e,r){let n=this.left.length;if(e<=n)return this.left.decomposeLeft(e,r);r.push(this.left),this.break&&(n++,e>=n&&r.push(null)),e>n&&this.right.decomposeLeft(e-n,r)}decomposeRight(e,r){let n=this.left.length,s=n+this.break;if(e>=s)return this.right.decomposeRight(e-s,r);e<n&&this.left.decomposeRight(e,r),this.break&&e<s&&r.push(null),r.push(this.right)}balanced(e,r){return e.size>2*r.size||r.size>2*e.size?oi.of(this.break?[e,null,r]:[e,r]):(this.left=Ap(this.left,e),this.right=Ap(this.right,r),this.setHeight(e.height+r.height),this.outdated=e.outdated||r.outdated,this.size=e.size+r.size,this.length=e.length+this.break+r.length,this)}updateHeight(e,r=0,n=!1,s){let{left:i,right:a}=this,o=r+i.length+this.break,l=null;return s&&s.from<=r+i.length&&s.more?l=i=i.updateHeight(e,r,n,s):i.updateHeight(e,r,n),s&&s.from<=o+a.length&&s.more?l=a=a.updateHeight(e,o,n,s):a.updateHeight(e,o,n),l?this.balanced(i,a):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function aS(t,e){let r,n;t[e]==null&&(r=t[e-1])instanceof Is&&(n=t[e+1])instanceof Is&&t.splice(e-1,3,new Is(r.length+1+n.length))}const gW=5;class O_{constructor(e,r){this.pos=e,this.oracle=r,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,r){if(this.lineStart>-1){let n=Math.min(r,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof Li?s.length+=n-this.pos:(n>this.pos||!this.isCovered)&&this.nodes.push(new Li(n-this.pos,-1,0)),this.writtenTo=n,r>n&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=r}point(e,r,n){if(e<r||n.heightRelevant){let s=n.widget?n.widget.estimatedHeight:0,i=n.widget?n.widget.lineBreaks:0;s<0&&(s=this.oracle.lineHeight);let a=r-e;n.block?this.addBlock(new JP(a,s,n)):(a||i||s>=gW)&&this.addLineDeco(s,i,a)}else r>e&&this.span(e,r);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:r}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=r,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new Li(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,r){let n=new Is(r-e);return this.oracle.doc.lineAt(e).to==r&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Li)return e;let r=new Li(0,-1,0);return this.nodes.push(r),r}addBlock(e){this.enterLine();let r=e.deco;r&&r.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,r&&r.endSide>0&&(this.covering=e)}addLineDeco(e,r,n){let s=this.ensureLine();s.length+=n,s.collapsed+=n,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=r,this.writtenTo=this.pos=this.pos+n}finish(e){let r=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(r instanceof Li)&&!this.isCovered?this.nodes.push(new Li(0,-1,0)):(this.writtenTo<this.pos||r==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let n=e;for(let s of this.nodes)s instanceof Li&&s.updateHeight(this.oracle,n),n+=s?s.length:1;return this.nodes}static build(e,r,n,s){let i=new O_(n,e);return gr.spans(r,n,s,i,0),i.finish(n)}}function bW(t,e,r){let n=new vW;return gr.compare(t,e,r,n,0),n.changes}class vW{constructor(){this.changes=[]}compareRange(){}comparePoint(e,r,n,s){(e<r||n&&n.heightRelevant||s&&s.heightRelevant)&&qc(e,r,this.changes,5)}}function yW(t,e){let r=t.getBoundingClientRect(),n=t.ownerDocument,s=n.defaultView||window,i=Math.max(0,r.left),a=Math.min(s.innerWidth,r.right),o=Math.max(0,r.top),l=Math.min(s.innerHeight,r.bottom);for(let c=t.parentNode;c&&c!=n.body;)if(c.nodeType==1){let u=c,d=window.getComputedStyle(u);if((u.scrollHeight>u.clientHeight||u.scrollWidth>u.clientWidth)&&d.overflow!="visible"){let h=u.getBoundingClientRect();i=Math.max(i,h.left),a=Math.min(a,h.right),o=Math.max(o,h.top),l=Math.min(c==t.parentNode?s.innerHeight:l,h.bottom)}c=d.position=="absolute"||d.position=="fixed"?u.offsetParent:u.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:i-r.left,right:Math.max(i,a)-r.left,top:o-(r.top+e),bottom:Math.max(o,l)-(r.top+e)}}function _W(t){let e=t.getBoundingClientRect(),r=t.ownerDocument.defaultView||window;return e.left<r.innerWidth&&e.right>0&&e.top<r.innerHeight&&e.bottom>0}function xW(t,e){let r=t.getBoundingClientRect();return{left:0,right:r.right-r.left,top:e,bottom:r.bottom-(r.top+e)}}class Zg{constructor(e,r,n,s){this.from=e,this.to=r,this.size=n,this.displaySize=s}static same(e,r){if(e.length!=r.length)return!1;for(let n=0;n<e.length;n++){let s=e[n],i=r[n];if(s.from!=i.from||s.to!=i.to||s.size!=i.size)return!1}return!0}draw(e,r){return lr.replace({widget:new wW(this.displaySize*(r?e.scaleY:e.scaleX),r)}).range(this.from,this.to)}}class wW extends dl{constructor(e,r){super(),this.size=e,this.vertical=r}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement("div");return this.vertical?e.style.height=this.size+"px":(e.style.width=this.size+"px",e.style.height="2px",e.style.display="inline-block"),e}get estimatedHeight(){return this.vertical?this.size:-1}}class lS{constructor(e){this.state=e,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scrollTop=0,this.scrolledToBottom=!1,this.scaleX=1,this.scaleY=1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=cS,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=en.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let r=e.facet(xm).some(n=>typeof n!="function"&&n.class=="cm-lineWrapping");this.heightOracle=new hW(r),this.stateDeco=e.facet(Dd).filter(n=>typeof n!="function"),this.heightMap=oi.empty().applyChanges(this.stateDeco,Mr.empty,this.heightOracle.setDoc(e.doc),[new Ki(0,0,0,e.doc.length)]);for(let n=0;n<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());n++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=lr.set(this.lineGaps.map(n=>n.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:r}=this.state.selection;for(let n=0;n<=1;n++){let s=n?r.head:r.anchor;if(!e.some(({from:i,to:a})=>s>=i&&s<=a)){let{from:i,to:a}=this.lineBlockAt(s);e.push(new of(i,a))}}return this.viewports=e.sort((n,s)=>n.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?cS:new j_(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(ed(e,this.scaler))})}update(e,r=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=this.state.facet(Dd).filter(u=>typeof u!="function");let s=e.changedRanges,i=Ki.extendWithRanges(s,bW(n,this.stateDeco,e?e.changes:es.empty(this.state.doc.length))),a=this.heightMap.height,o=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);oS(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),i),(this.heightMap.height!=a||lu)&&(e.flags|=2),o?(this.scrollAnchorPos=e.changes.mapPos(o.from,-1),this.scrollAnchorHeight=o.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=a);let l=i.length?this.mapViewport(this.viewport,e.changes):this.viewport;(r&&(r.range.head<l.from||r.range.head>l.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,r));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),r&&(this.scrollTarget=r),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(PP)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let r=e.contentDOM,n=window.getComputedStyle(r),s=this.heightOracle,i=n.whiteSpace;this.defaultTextDirection=n.direction=="rtl"?en.RTL:en.LTR;let a=this.heightOracle.mustRefreshForWrapping(i),o=r.getBoundingClientRect(),l=a||this.mustMeasureContent||this.contentDOMHeight!=o.height;this.contentDOMHeight=o.height,this.mustMeasureContent=!1;let c=0,u=0;if(o.width&&o.height){let{scaleX:w,scaleY:C}=dP(r,o);(w>.005&&Math.abs(this.scaleX-w)>.005||C>.005&&Math.abs(this.scaleY-C)>.005)&&(this.scaleX=w,this.scaleY=C,c|=16,a=l=!0)}let d=(parseInt(n.paddingTop)||0)*this.scaleY,h=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=d||this.paddingBottom!=h)&&(this.paddingTop=d,this.paddingBottom=h,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let m=e.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=m&&(this.scrollAnchorHeight=-1,this.scrollTop=m),this.scrolledToBottom=fP(e.scrollDOM);let b=(this.printing?xW:yW)(r,this.paddingTop),g=b.top-this.pixelViewport.top,p=b.bottom-this.pixelViewport.bottom;this.pixelViewport=b;let y=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(y!=this.inView&&(this.inView=y,y&&(l=!0)),!this.inView&&!this.scrollTarget&&!_W(e.dom))return 0;let v=o.width;if((this.contentDOMWidth!=v||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=o.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let w=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(w)&&(a=!0),a||s.lineWrapping&&Math.abs(v-this.contentDOMWidth)>s.charWidth){let{lineHeight:C,charWidth:A,textHeight:E}=e.docView.measureTextSize();a=C>0&&s.refresh(i,C,A,E,Math.max(5,v/A),w),a&&(e.docView.minWidth=0,c|=16)}g>0&&p>0?u=Math.max(g,p):g<0&&p<0&&(u=Math.min(g,p)),oS();for(let C of this.viewports){let A=C.from==this.viewport.from?w:e.docView.measureVisibleLineHeights(C);this.heightMap=(a?oi.empty().applyChanges(this.stateDeco,Mr.empty,this.heightOracle,[new Ki(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,a,new fW(C.from,A))}lu&&(c|=2)}let _=!this.viewportIsAppropriate(this.viewport,u)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return _&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(u,this.scrollTarget),c|=this.updateForViewport()),(c&2||_)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(a?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,r){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,i=this.heightOracle,{visibleTop:a,visibleBottom:o}=this,l=new of(s.lineAt(a-n*1e3,Zr.ByHeight,i,0,0).from,s.lineAt(o+(1-n)*1e3,Zr.ByHeight,i,0,0).to);if(r){let{head:c}=r.range;if(c<l.from||c>l.to){let u=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),d=s.lineAt(c,Zr.ByPos,i,0,0),h;r.y=="center"?h=(d.top+d.bottom)/2-u/2:r.y=="start"||r.y=="nearest"&&c<l.from?h=d.top:h=d.bottom-u,l=new of(s.lineAt(h-1e3/2,Zr.ByHeight,i,0,0).from,s.lineAt(h+u+1e3/2,Zr.ByHeight,i,0,0).to)}}return l}mapViewport(e,r){let n=r.mapPos(e.from,-1),s=r.mapPos(e.to,1);return new of(this.heightMap.lineAt(n,Zr.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(s,Zr.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:r},n=0){if(!this.inView)return!0;let{top:s}=this.heightMap.lineAt(e,Zr.ByPos,this.heightOracle,0,0),{bottom:i}=this.heightMap.lineAt(r,Zr.ByPos,this.heightOracle,0,0),{visibleTop:a,visibleBottom:o}=this;return(e==0||s<=a-Math.max(10,Math.min(-n,250)))&&(r==this.state.doc.length||i>=o+Math.max(10,Math.min(n,250)))&&s>a-2*1e3&&i<o+2*1e3}mapLineGaps(e,r){if(!e.length||r.empty)return e;let n=[];for(let s of e)r.touchesRange(s.from,s.to)||n.push(new Zg(r.mapPos(s.from),r.mapPos(s.to),s.size,s.displaySize));return n}ensureLineGaps(e,r){let n=this.heightOracle.lineWrapping,s=n?1e4:2e3,i=s>>1,a=s<<1;if(this.defaultTextDirection!=en.LTR&&!n)return[];let o=[],l=(u,d,h,m)=>{if(d-u<i)return;let b=this.state.selection.main,g=[b.from];b.empty||g.push(b.to);for(let y of g)if(y>u&&y<d){l(u,y-10,h,m),l(y+10,d,h,m);return}let p=CW(e,y=>y.from>=h.from&&y.to<=h.to&&Math.abs(y.from-u)<i&&Math.abs(y.to-d)<i&&!g.some(v=>y.from<v&&y.to>v));if(!p){if(d<h.to&&r&&n&&r.visibleRanges.some(_=>_.from<=d&&_.to>=d)){let _=r.moveToLineBoundary(ke.cursor(d),!1,!0).head;_>u&&(d=_)}let y=this.gapSize(h,u,d,m),v=n||y<2e6?y:2e6;p=new Zg(u,d,y,v)}o.push(p)},c=u=>{if(u.length<a||u.type!=Ls.Text)return;let d=SW(u.from,u.to,this.stateDeco);if(d.total<a)return;let h=this.scrollTarget?this.scrollTarget.range.head:null,m,b;if(n){let g=s/this.heightOracle.lineLength*this.heightOracle.lineHeight,p,y;if(h!=null){let v=lf(d,h),_=((this.visibleBottom-this.visibleTop)/2+g)/u.height;p=v-_,y=v+_}else p=(this.visibleTop-u.top-g)/u.height,y=(this.visibleBottom-u.top+g)/u.height;m=af(d,p),b=af(d,y)}else{let g=d.total*this.heightOracle.charWidth,p=s*this.heightOracle.charWidth,y=0;if(g>2e6)for(let A of e)A.from>=u.from&&A.from<u.to&&A.size!=A.displaySize&&A.from*this.heightOracle.charWidth+y<this.pixelViewport.left&&(y=A.size-A.displaySize);let v=this.pixelViewport.left+y,_=this.pixelViewport.right+y,w,C;if(h!=null){let A=lf(d,h),E=((_-v)/2+p)/g;w=A-E,C=A+E}else w=(v-p)/g,C=(_+p)/g;m=af(d,w),b=af(d,C)}m>u.from&&l(u.from,m,u,d),b<u.to&&l(b,u.to,u,d)};for(let u of this.viewportLines)Array.isArray(u.type)?u.type.forEach(c):c(u);return o}gapSize(e,r,n,s){let i=lf(s,n)-lf(s,r);return this.heightOracle.lineWrapping?e.height*i:s.total*this.heightOracle.charWidth*i}updateLineGaps(e){Zg.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=lr.set(e.map(r=>r.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let r=this.stateDeco;this.lineGaps.length&&(r=r.concat(this.lineGapDeco));let n=[];gr.spans(r,this.viewport.from,this.viewport.to,{span(i,a){n.push({from:i,to:a})},point(){}},20);let s=0;if(n.length!=this.visibleRanges.length)s=12;else for(let i=0;i<n.length&&!(s&8);i++){let a=this.visibleRanges[i],o=n[i];(a.from!=o.from||a.to!=o.to)&&(s|=4,e&&e.mapPos(a.from,-1)==o.from&&e.mapPos(a.to,1)==o.to||(s|=8))}return this.visibleRanges=n,s}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(r=>r.from<=e&&r.to>=e)||ed(this.heightMap.lineAt(e,Zr.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(r=>r.top<=e&&r.bottom>=e)||ed(this.heightMap.lineAt(this.scaler.fromDOM(e),Zr.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(e){let r=this.lineBlockAtHeight(e+8);return r.from>=this.viewport.from||this.viewportLines[0].top-e>200?r:this.viewportLines[0]}elementAtHeight(e){return ed(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class of{constructor(e,r){this.from=e,this.to=r}}function SW(t,e,r){let n=[],s=t,i=0;return gr.spans(r,t,e,{span(){},point(a,o){a>s&&(n.push({from:s,to:a}),i+=a-s),s=o}},20),s<e&&(n.push({from:s,to:e}),i+=e-s),{total:i,ranges:n}}function af({total:t,ranges:e},r){if(r<=0)return e[0].from;if(r>=1)return e[e.length-1].to;let n=Math.floor(t*r);for(let s=0;;s++){let{from:i,to:a}=e[s],o=a-i;if(n<=o)return i+n;n-=o}}function lf(t,e){let r=0;for(let{from:n,to:s}of t.ranges){if(e<=s){r+=e-n;break}r+=s-n}return r/t.total}function CW(t,e){for(let r of t)if(e(r))return r}const cS={toDOM(t){return t},fromDOM(t){return t},scale:1,eq(t){return t==this}};class j_{constructor(e,r,n){let s=0,i=0,a=0;this.viewports=n.map(({from:o,to:l})=>{let c=r.lineAt(o,Zr.ByPos,e,0,0).top,u=r.lineAt(l,Zr.ByPos,e,0,0).bottom;return s+=u-c,{from:o,to:l,top:c,bottom:u,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(r.height-s);for(let o of this.viewports)o.domTop=a+(o.top-i)*this.scale,a=o.domBottom=o.domTop+(o.bottom-o.top),i=o.bottom}toDOM(e){for(let r=0,n=0,s=0;;r++){let i=r<this.viewports.length?this.viewports[r]:null;if(!i||e<i.top)return s+(e-n)*this.scale;if(e<=i.bottom)return i.domTop+(e-i.top);n=i.bottom,s=i.domBottom}}fromDOM(e){for(let r=0,n=0,s=0;;r++){let i=r<this.viewports.length?this.viewports[r]:null;if(!i||e<i.domTop)return n+(e-s)/this.scale;if(e<=i.domBottom)return i.top+(e-i.domTop);n=i.bottom,s=i.domBottom}}eq(e){return e instanceof j_?this.scale==e.scale&&this.viewports.length==e.viewports.length&&this.viewports.every((r,n)=>r.from==e.viewports[n].from&&r.to==e.viewports[n].to):!1}}function ed(t,e){if(e.scale==1)return t;let r=e.toDOM(t.top),n=e.toDOM(t.bottom);return new co(t.from,t.length,r,n-r,Array.isArray(t._content)?t._content.map(s=>ed(s,e)):t._content)}const cf=it.define({combine:t=>t.join(" ")}),ty=it.define({combine:t=>t.indexOf(!0)>-1}),ry=nl.newName(),QP=nl.newName(),ZP=nl.newName(),eT={"&light":"."+QP,"&dark":"."+ZP};function ny(t,e,r){return new nl(e,{finish(n){return/&/.test(n)?n.replace(/&\w*/,s=>{if(s=="&")return t;if(!r||!r[s])throw new RangeError(`Unsupported selector: ${s}`);return r[s]}):t+" "+n}})}const AW=ny("."+ry,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},eT),EW={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},eb=tt.ie&&tt.ie_version<=11;class kW{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new s4,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(r=>{for(let n of r)this.queue.push(n);(tt.ie&&tt.ie_version<=11||tt.ios&&e.composing)&&r.some(n=>n.type=="childList"&&n.removedNodes.length||n.type=="characterData"&&n.oldValue.length>n.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&tt.android&&e.constructor.EDIT_CONTEXT!==!1&&!(tt.chrome&&tt.chrome_version<126)&&(this.editContext=new TW(e),e.state.facet(sa)&&(e.contentDOM.editContext=this.editContext.editContext)),eb&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var r;((r=this.view.docView)===null||r===void 0?void 0:r.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(r=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),r.length>0&&r[r.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(r=>{r.length>0&&r[r.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((r,n)=>r!=e[n]))){this.gapIntersection.disconnect();for(let r of e)this.gapIntersection.observe(r);this.gaps=e}}onSelectionChange(e){let r=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,s=this.selectionRange;if(n.state.facet(sa)?n.root.activeElement!=this.dom:!Ff(this.dom,s))return;let i=s.anchorNode&&n.docView.tile.nearest(s.anchorNode);if(i&&i.isWidget()&&i.widget.ignoreEvent(e)){r||(this.selectionChanged=!1);return}(tt.ie&&tt.ie_version<=11||tt.android&&tt.chrome)&&!n.state.selection.main.empty&&s.focusNode&&fd(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,r=Nd(e.root);if(!r)return!1;let n=tt.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&PW(this.view,r)||r;if(!n||this.selectionRange.eq(n))return!1;let s=Ff(this.dom,n);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&o4(this.dom,n)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(n),s&&(this.selectionChanged=!0),!0)}setSelectionRange(e,r){this.selectionRange.set(e.node,e.offset,r.node,r.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,r=null;for(let n=this.dom;n;)if(n.nodeType==1)!r&&e<this.scrollTargets.length&&this.scrollTargets[e]==n?e++:r||(r=this.scrollTargets.slice(0,e)),r&&r.push(n),n=n.assignedSlot||n.parentNode;else if(n.nodeType==11)n=n.host;else break;if(e<this.scrollTargets.length&&!r&&(r=this.scrollTargets.slice(0,e)),r){for(let n of this.scrollTargets)n.removeEventListener("scroll",this.onScroll);for(let n of this.scrollTargets=r)n.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,EW),eb&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),eb&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,r){var n;if(!this.delayedAndroidKey){let s=()=>{let i=this.delayedAndroidKey;i&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=i.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&i.force&&Kc(this.dom,i.key,i.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:r,force:this.lastChange<Date.now()-50||!!(!((n=this.delayedAndroidKey)===null||n===void 0)&&n.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let r=-1,n=-1,s=!1;for(let i of e){let a=this.readMutation(i);a&&(a.typeOver&&(s=!0),r==-1?{from:r,to:n}=a:(r=Math.min(a.from,r),n=Math.max(a.to,n)))}return{from:r,to:n,typeOver:s}}readChange(){let{from:e,to:r,typeOver:n}=this.processRecords(),s=this.selectionChanged&&Ff(this.dom,this.selectionRange);
vendor: 5,166 bytes, lines 46-47
46if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let i=new G4(this.view,e,r,n);return this.view.docView.domChanged={newSel:i.newSel?i.newSel.main:null},i}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let r=this.readChange();if(!r)return this.view.requestMeasure(),!1;let n=this.view.state,s=WP(this.view,r);return this.view.state==n&&(r.domChanged||r.newSel&&!r.newSel.main.eq(this.view.state.selection.main))&&this.view.update([]),s}readMutation(e){let r=this.view.docView.tile.nearest(e.target);if(!r||r.isWidget())return null;if(r.markDirty(e.type=="attributes"),e.type=="childList"){let n=uS(r,e.previousSibling||e.target.previousSibling,-1),s=uS(r,e.nextSibling||e.target.nextSibling,1);return{from:n?r.posAfter(n):r.posAtStart,to:s?r.posBefore(s):r.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(sa)!=e.state.facet(sa)&&(e.view.contentDOM.editContext=e.state.facet(sa)?this.editContext.editContext:null))}destroy(){var e,r,n;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(r=this.gapIntersection)===null||r===void 0||r.disconnect(),(n=this.resizeScroll)===null||n===void 0||n.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function uS(t,e,r){for(;e;){let n=ns.get(e);if(n&&n.parent==t)return n;let s=e.parentNode;e=s!=t.dom?s:r>0?e.nextSibling:e.previousSibling}return null}function dS(t,e){let r=e.startContainer,n=e.startOffset,s=e.endContainer,i=e.endOffset,a=t.docView.domAtPos(t.state.selection.main.anchor,1);return fd(a.node,a.offset,s,i)&&([r,n,s,i]=[s,i,r,n]),{anchorNode:r,anchorOffset:n,focusNode:s,focusOffset:i}}function PW(t,e){if(e.getComposedRanges){let s=e.getComposedRanges(t.root)[0];if(s)return dS(t,s)}let r=null;function n(s){s.preventDefault(),s.stopImmediatePropagation(),r=s.getTargetRanges()[0]}return t.contentDOM.addEventListener("beforeinput",n,!0),t.dom.ownerDocument.execCommand("indent"),t.contentDOM.removeEventListener("beforeinput",n,!0),r?dS(t,r):null}class TW{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let r=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=n=>{let s=e.state.selection.main,{anchor:i,head:a}=s,o=this.toEditorPos(n.updateRangeStart),l=this.toEditorPos(n.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:n.updateRangeStart,editorBase:o,drifted:!1});let c=l-o>n.text.length;o==this.from&&i<this.from?o=i:l==this.to&&i>this.to&&(l=i);let u=HP(e.state.sliceDoc(o,l),n.text,(c?s.from:s.to)-o,c?"end":null);if(!u){let h=ke.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd));h.main.eq(s)||e.dispatch({selection:h,userEvent:"select"});return}let d={from:u.from+o,to:u.toA+o,insert:Mr.of(n.text.slice(u.from,u.toB).split(` 47`))};if((tt.mac||tt.android)&&d.from==a-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(d={from:o,to:l,insert:Mr.of([n.text.replace("."," ")])}),this.pendingContextChange=d,!e.state.readOnly){let h=this.to-this.from+(d.to-d.from+d.insert.length);M_(e,d,ke.single(this.toEditorPos(n.selectionStart,h),this.toEditorPos(n.selectionEnd,h)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),d.from<d.to&&!d.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(r.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(r.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)}
vendor: 4,486 bytes, line 47
47,this.handlers.characterboundsupdate=n=>{let s=[],i=null;for(let a=this.toEditorPos(n.rangeStart),o=this.toEditorPos(n.rangeEnd);a<o;a++){let l=e.coordsForChar(a);i=l&&new DOMRect(l.left,l.top,l.right-l.left,l.bottom-l.top)||i||new DOMRect,s.push(i)}r.updateCharacterBounds(n.rangeStart,s)},this.handlers.textformatupdate=n=>{let s=[];for(let i of n.getTextFormats()){let a=i.underlineStyle,o=i.underlineThickness;if(!/none/i.test(a)&&!/none/i.test(o)){let l=this.toEditorPos(i.rangeStart),c=this.toEditorPos(i.rangeEnd);if(l<c){let u=`text-decoration: underline ${/^[a-z]/.test(a)?a+" ":a=="Dashed"?"dashed ":a=="Squiggle"?"wavy ":""}${/thin/i.test(o)?1:2}px`;s.push(lr.mark({attributes:{style:u}}).range(l,c))}}}e.dispatch({effects:RP.of(lr.set(s))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:n}=this.composing;this.composing=null,n&&this.reset(e.state)}};for(let n in this.handlers)r.addEventListener(n,this.handlers[n]);this.measureReq={read:n=>{this.editContext.updateControlBounds(n.contentDOM.getBoundingClientRect());let s=Nd(n.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let r=0,n=!1,s=this.pendingContextChange;return e.changes.iterChanges((i,a,o,l,c)=>{if(n)return;let u=c.length-(a-i);if(s&&a>=s.to)if(s.from==i&&s.to==a&&s.insert.eq(c)){s=this.pendingContextChange=null,r+=u,this.to+=u;return}else s=null,this.revertPending(e.state);if(i+=r,a+=r,a<=this.from)this.from+=u,this.to+=u;else if(i<this.to){if(i<this.from||a>this.to||this.to-this.from+c.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(i),this.toContextPos(a),c.toString()),this.to+=u}r+=u}),s&&!n&&this.revertPending(e.state),!n}update(e){let r=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||r)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:r}=e.selection.main;this.from=Math.max(0,r-1e4),this.to=Math.min(e.doc.length,r+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let r=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(r.from),this.toContextPos(r.from+r.insert.length),e.doc.sliceString(r.from,r.to))}setSelection(e){let{main:r}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,r.anchor))),s=this.toContextPos(r.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(n,s)}rangeIsValid(e){let{head:r}=e.selection.main;return!(this.from>0&&r-this.from<500||this.to<e.doc.length&&this.to-r<500||this.to-this.from>1e4*3)}toEditorPos(e,r=this.to-this.from){e=Math.min(e,r);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let r=this.composing;return r&&r.drifted?r.contextBase+(e-r.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class st{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var r;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="
47cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:n}=e;this.dispatchTransactions=e.dispatchTransactions||n&&(s=>s.forEach(i=>n(i,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||i4(e.parent)||document,this.viewState=new lS(e.state||Cr.create(e)),e.scrollTo&&e.scrollTo.is(rf)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(jc).map(s=>new Kg(s));for(let s of this.plugins)s.update(this);this.observer=new kW(this),this.inputState=new X4(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Kw(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((r=document.fonts)===null||r===void 0)&&r.ready&&document.fonts.ready.then(()=>this.requestMeasure())}dispatch(...e){let r=e.length==1&&e[0]instanceof qn?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(r,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let r=!1,n=!1,s,i=this.state;for(let h of e){if(h.startState!=i)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");i=h.state}if(this.destroyed){this.viewState.state=i;return}let a=this.hasFocus,o=0,l=null;e.some(h=>h.annotation(KP))?(this.inputState.notifiedFocused=a,o=1):a!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=a,l=YP(i,a),l||(o=1));let c=this.observer.delayedAndroidKey,u=null;if(c?(this.observer.clearDelayedAndroidKey(),u=this.observer.readChange(),(u&&!this.state.doc.eq(i.doc)||!this.state.selection.eq(i.selection))&&(u=null)):this.observer.clear(),i.facet(Cr.phrases)!=this.state.facet(Cr.phrases))return this.setState(i);s=wp.create(this,i,e),s.flags|=o;let d=this.viewState.scrollTarget;try{this.updateState=2;for(let h of e){if(d&&(d=d.map(h.changes)),h.scrollIntoView){let{main:m}=h.state.selection;d=new Yc(m.empty?m:ke.cursor(m.head,m.head>m.anchor?-1:1))}for(let m of h.effects)m.is(rf)&&(d=m.value.clip(this.state))}this.viewState.update(s,d),this.bidiCache=Ep.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),r=this.docView.update(s),this.state.facet(Qu)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(r,e.some(h=>h.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(cf)!=s.state.facet(cf)&&(this.viewState.mustMeasureContent=!0),(r||n||d||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),r&&this.docViewUpdate(),!s.empty)for(let h of this.state.facet(Xv))try{h(s)}catch(m){Oi(this.state,m,"update listener")}(l||u)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),u&&!WP(this,u)&&c.force&&Kc(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let r=this.hasFocus;try{for(let n of this.plugins)n.destroy(this);this.viewState=new lS(e),this.plugins=e.facet(jc).map(n=>new Kg(n)),this.pluginMap.clear();for(let n of this.plugins)n.update(this);this.docView.destroy(),this.docView=new Kw(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}r&&this.focus(),this.requestMeasure()}updatePlugins(e){let r=e.startState.facet(jc),n=e.state.facet(jc);if(r!=n){let s=[];for(let i of n){let a=r.indexOf(i);if(a<0)s.push(new Kg(i));else{let o=this.plugins[a];o.mustUpdate=e,s.push(o)}}for(let i of this.plugins)i.mustUpdate!=e&&i.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s<this.plugins.length;s++)this.plugins[s].update(this);r!=n&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let r=e.value;if(r&&r.docViewUpdate)try{r.docViewUpdate(this)}catch(n){Oi(this.state,n,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let r=null,n=this.scrollDOM,s=n.scrollTop*this.scaleY,{scrollAnchorPos:i,scrollAnchorHeight:a}=this.viewState;Math.abs(s-this.viewState.scrollTop)>1&&(a=-1),this.viewState.scrollAnchorHeight=-1;try{for(let o=0;;o++){if(a<0)if(fP(n))i=-1,a=this.viewState.heightMap.height;else{let m=this.viewState.scrollAnchorAt(s);i=m.from,a=m.top}this.updateState=1;let l=this.viewState.measure(this);if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;
vendor: 13,562 bytes, line 47
47if(o>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let u=c.map(m=>{try{return m.read(this)}catch(b){return Oi(this.state,b),hS}}),d=wp.create(this,this.state,[]),h=!1;d.flags|=l,r?r.flags|=l:r=d,this.updateState=2,d.empty||(this.updatePlugins(d),this.inputState.update(d),this.updateAttrs(),h=this.docView.update(d),h&&this.docViewUpdate());for(let m=0;m<c.length;m++)if(u[m]!=hS)try{let b=c[m];b.write&&b.write(u[m],this)}catch(b){Oi(this.state,b)}if(h&&this.docView.updateSelection(!0),!d.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,a=-1;continue}else{let b=(i<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(i).top)-a;if(b>1||b<-1){s=s+b,n.scrollTop=s/this.scaleY,a=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(r&&!r.empty)for(let o of this.state.facet(Xv))o(r)}get themeClasses(){return ry+" "+(this.state.facet(ty)?ZP:QP)+" "+this.state.facet(cf)}updateAttrs(){let e=fS(this,IP,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),r={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(sa)?"true":"false",class:"cm-content",style:`${tt.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(r["aria-readonly"]="true"),fS(this,xm,r);let n=this.observer.ignore(()=>{let s=Hw(this.contentDOM,this.contentAttrs,r),i=Hw(this.dom,this.editorAttrs,e);return s||i});return this.editorAttrs=e,this.contentAttrs=r,n}showAnnouncements(e){let r=!0;for(let n of e)for(let s of n.effects)if(s.is(st.announce)){r&&(this.announceDOM.textContent=""),r=!1;let i=this.announceDOM.appendChild(document.createElement("div"));i.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(Qu);let e=this.state.facet(st.cspNonce);nl.mount(this.root,this.styleModules.concat(AW).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let r=0;r<this.measureRequests.length;r++)if(this.measureRequests[r].key===e.key){this.measureRequests[r]=e;return}}this.measureRequests.push(e)}}plugin(e){let r=this.pluginMap.get(e);return(r===void 0||r&&r.plugin!=e)&&this.pluginMap.set(e,r=this.plugins.find(n=>n.plugin==e)||null),r&&r.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,r,n){return Qg(this,e,Yw(this,e,r,n))}moveByGroup(e,r){return Qg(this,e,Yw(this,e,r,n=>W4(this,e.head,n)))}visualLineSide(e,r){let n=this.bidiSpans(e),s=this.textDirectionAt(e.from),i=n[r?n.length-1:0];return ke.cursor(i.side(r,s)+e.from,i.forward(!r,s)?1:-1)}moveToLineBoundary(e,r,n=!0){return F4(this,e,r,n)}moveVertically(e,r,n){return Qg(this,e,H4(this,e,r,n))}domAtPos(e,r=1){return this.docView.domAtPos(e,r)}posAtDOM(e,r=0){return this.docView.posFromDOM(e,r)}posAtCoords(e,r=!0){this.readMeasured();let n=Zv(this,e,r);return n&&n.pos}posAndSideAtCoords(e,r=!0){return this.readMeasured(),Zv(this,e,r)}coordsAtPos(e,r=1){this.readMeasured();let n=this.docView.coordsAt(e,r);if(!n||n.left==n.right)return n;let s=this.state.doc.lineAt(e),i=this.bidiSpans(s),a=i[ca.find(i,e-s.from,-1,r)];return xp(n,a.dir==en.LTR==r>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(kP)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>RW)return yP(e.length);let r=this.textDirectionAt(e.from),n;for(let i of this.bidiCache)if(i.from==e.from&&i.dir==r&&(i.fresh||vP(i.isolates,n=Vw(this,e))))return i.order;n||(n=Vw(this,e));let s=f4(e.text,r,n);return this.bidiCache.push(new Ep(e.from,e.to,r,n,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||tt.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{hP(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,r={}){return rf.of(new Yc(typeof e=="number"?ke.cursor(e):e,r.y,r.x,r.yMargin,r.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:r}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return rf.of(new Yc(ke.cursor(n.from),"start","start",n.top-e,r,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return ms.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ms.define(()=>({}),{eventObservers:e})}static theme(e,r){let n=nl.newName(),s=[cf.of(n),Qu.of(ny(`.${n}`,e))];return r&&r.dark&&s.push(ty.of(!0)),s}static baseTheme(e){return ul.lowest(Qu.of(ny("."+ry,e,eT)))}static findFromDOM(e){var r;let n=e.querySelector(".cm-content"),s=n&&ns.get(n)||ns.get(e);return((r=s?.root)===null||r===void 0?void 0:r.view)||null}}st.styleModule=Qu;st.inputHandler=AP;st.clipboardInputFilter=N_;st.clipboardOutputFilter=L_;st.scrollHandler=TP;st.focusChangeEffect=EP;st.perLineTextDirection=kP;st.exceptionSink=CP;st.updateListener=Xv;st.editable=sa;st.mouseSelectionStyle=SP;st.dragMovesSelection=wP;st.clickAddsSelectionRange=xP;st.decorations=Dd;st.blockWrappers=NP;st.outerDecorations=LP;st.atomicRanges=mh;st.bidiIsolatedRanges=DP;st.scrollMargins=MP;st.darkTheme=ty;st.cspNonce=it.define({combine:t=>t.length?t[0]:""});st.contentAttributes=xm;st.editorAttributes=IP;st.lineWrapping=st.contentAttributes.of({class:"cm-lineWrapping"});st.announce=sr.define();const RW=4096,hS={};class Ep{constructor(e,r,n,s,i,a){this.from=e,this.to=r,this.dir=n,this.isolates=s,this.fresh=i,this.order=a}static update(e,r){if(r.empty&&!e.some(i=>i.fresh))return e;let n=[],s=e.length?e[e.length-1].dir:en.LTR;for(let i=Math.max(0,e.length-10);i<e.length;i++){let a=e[i];a.dir==s&&!r.touchesRange(a.from,a.to)&&n.push(new Ep(r.mapPos(a.from,1),r.mapPos(a.to,-1),a.dir,a.isolates,!1,a.order))}return n}}function fS(t,e,r){for(let n=t.state.facet(e),s=n.length-1;s>=0;s--){let i=n[s],a=typeof i=="function"?i(t):i;a&&T_(a,r)}return r}const IW=tt.mac?"mac":tt.windows?"win":tt.linux?"linux":"key";function NW(t,e){const r=t.split(/-(?!$)/);let n=r[r.length-1];n=="Space"&&(n=" ");let s,i,a,o;for(let l=0;l<r.length-1;++l){const c=r[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))s=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))a=!0;else if(/^mod$/i.test(c))e=="mac"?o=!0:i=!0;else throw new Error("Unrecognized modifier name: "+c)}return s&&(n="Alt-"+n),i&&(n="Ctrl-"+n),o&&(n="Meta-"+n),a&&(n="Shift-"+n),n}function uf(t,e,r){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),r!==!1&&e.shiftKey&&(t="Shift-"+t),t}const LW=ul.default(st.domEventHandlers({keydown(t,e){return rT(tT(e.state),t,e,"editor")}})),Am=it.define({enables:LW}),pS=new WeakMap;function tT(t){let e=t.facet(Am),r=pS.get(e);return r||pS.set(e,r=OW(e.reduce((n,s)=>n.concat(s),[]))),r}function DW(t,e,r){return rT(tT(t.state),e,t,r)}let Ga=null;const MW=4e3;function OW(t,e=IW){let r=Object.create(null),n=Object.create(null),s=(a,o)=>{let l=n[a];if(l==null)n[a]=o;else if(l!=o)throw new Error("Key binding "+a+" is used both as a regular binding and as a multi-stroke prefix")},i=(a,o,l,c,u)=>{var d,h;let m=r[a]||(r[a]=Object.create(null)),b=o.split(/ (?!$)/).map(y=>NW(y,e));for(let y=1;y<b.length;y++){let v=b.slice(0,y).join(" ");s(v,!0),m[v]||(m[v]={preventDefault:!0,stopPropagation:!1,run:[_=>{let w=Ga={view:_,prefix:v,scope:a};return setTimeout(()=>{Ga==w&&(Ga=null)},MW),!0}]})}let g=b.join(" ");s(g,!1);let p=m[g]||(m[g]={preventDefault:!1,stopPropagation:!1,run:((h=(d=m._any)===null||d===void 0?void 0:d.run)===null||h===void 0?void 0:h.slice())||[]});l&&p.run.push(l),c&&(p.preventDefault=!0),u&&(p.stopPropagation=!0)};for(let a of t){let o=a.scope?a.scope.split(" "):["editor"];if(a.any)for(let c of o){let u=r[c]||(r[c]=Object.create(null));u._any||(u._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:d}=a;for(let h in u)u[h].run.push(m=>d(m,sy))}let l=a[e]||a.key;if(l)for(let c of o)i(c,l,a.run,a.preventDefault,a.stopPropagation),a.shift&&i(c,"Shift-"+l,a.shift,a.preventDefault,a.stopPropagation)}return r}let sy=null;function rT(t,e,r,n){sy=e;let s=X3(e),i=lo(s,0),a=na(i)==s.length&&s!=" ",o="",l=!1,c=!1,u=!1;Ga&&Ga.view==r&&Ga.scope==n&&(o=Ga.prefix+" ",zP.indexOf(e.keyCode)<0&&(c=!0,Ga=null));let d=new Set,h=p=>{if(p){for(let y of p.run)if(!d.has(y)&&(d.add(y),y(r)))return p.stopPropagation&&(u=!0),!0;p.preventDefault&&(p.stopPropagation&&(u=!0),c=!0)}return!1},m=t[n],b,g;return m&&(h(m[o+uf(s,e,!a)])?l=!0:a&&(e.altKey||e.metaKey||e.ctrlKey)&&!(tt.windows&&e.ctrlKey&&e.altKey)&&!(tt.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(b=sl[e.keyCode])&&b!=s?(h(m[o+uf(b,e,!0)])||e.shiftKey&&(g=Rd[e.keyCode])!=s&&g!=b&&h(m[o+uf(g,e,!1)]))&&(l=!0):a&&e.shiftKey&&h(m[o+uf(s,e,!0)])&&(l=!0),!l&&h(m._any)&&(l=!0)),c&&(l=!0),l&&u&&e.stopPropagation(),sy=null,l}class gh{constructor(e,r,n,s,i){this.className=e,this.left=r,this.top=n,this.width=s,this.height=i}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,r){return r.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,r,n){if(n.empty){let s=e.coordsAtPos(n.head,n.assoc||1);if(!s)return[];let i=nT(e);return[new gh(r,s.left-i.left,s.top-i.top,null,s.bottom-s.top)]}else return jW(e,r,n)}}function nT(t){let e=t.scrollDOM.getBoundingClientRect();return{left:(t.textDirection==en.LTR?e.left:e.right-t.scrollDOM.clientWidth*t.scaleX)-t.scrollDOM.scrollLeft*t.scaleX,top:e.top-t.scrollDOM.scrollTop*t.scaleY}}function mS(t,e,r,n){let s=t.coordsAtPos(e,r*2);if(!s)return n;let i=t.dom.getBoundingClientRect(),a=(s.top+s.bottom)/2,o=t.posAtCoords({x:i.left+1,y:a}),l=t.posAtCoords({x:i.right-1,y:a});return o==null||l==null?n:{from:Math.max(n.from,Math.min(o,l)),to:Math.min(n.to,Math.max(o,l))}}function jW(t,e,r){if(r.to<=t.viewport.from||r.from>=t.viewport.to)return[];let n=Math.max(r.from,t.viewport.from),s=Math.min(r.to,t.viewport.to),i=t.textDirection==en.LTR,a=t.contentDOM,o=a.getBoundingClientRect(),l=nT(t),c=a.querySelector(".cm-line"),u=c&&window.getComputedStyle(c),d=o.left+(u?parseInt(u.paddingLeft)+Math.min(0,parseInt(u.textIndent)):0),h=o.right-(u?parseInt(u.paddingRight):0),m=Qv(t,n,1),b=Qv(t,s,-1),g=m.type==Ls.Text?m:null,p=b.type==Ls.Text?b:null;if(g&&(t.lineWrapping||m.widgetLineBreaks)&&(g=mS(t,n,1,g)),p&&(t.lineWrapping||b.widgetLineBreaks)&&(p=mS(t,s,-1,p)),g&&p&&g.from==p.from&&g.to==p.to)return v(_(r.from,r.to,g));{let C=g?_(r.from,null,g):w(m,!1),A=p?_(null,r.to,p):w(b,!0),E=[];return(g||m).to<(p||b).from-(g&&p?1:0)||m.widgetLineBreaks>1&&C.bottom+t.defaultLineHeight/2<A.top?E.push(y(d,C.bottom,h,A.top)):C.bottom<A.top&&t.elementAtHeight((C.bottom+A.top)/2).type==Ls.Text&&(C.bottom=A.top=(C.bottom+A.top)/2),v(C).concat(E).concat(v(A))}function y(C,A,E,S){return new gh(e,C-l.left,A-l.top,E-C,S-A)}function v({top:C,bottom:A,horizontal:E}){let S=[];for(let k=0;k<E.length;k+=2)S.push(y(E[k],C,E[k+1],A));return S}function _(C,A,E){let S=1e9,k=-1e9,O=[];function T(M,B,U,X,oe){let L=t.coordsAtPos(M,M==E.to?-2:2),F=t.coordsAtPos(U,U==E.from?2:-2);!L||!F||(S=Math.min(L.top,F.top,S),k=Math.max(L.bottom,F.bottom,k),oe==en.LTR?O.push(i&&B?d:L.left,i&&X?h:F.right):O.push(!i&&
47X?d:F.left,!i&&B?h:L.right))}let R=C??E.from,N=A??E.to;for(let M of t.visibleRanges)if(M.to>R&&M.from<N)for(let B=Math.max(M.from,R),U=Math.min(M.to,N);;){let X=t.state.doc.lineAt(B);for(let oe of t.bidiSpans(X)){let L=oe.from+X.from,F=oe.to+X.from;if(L>=U)break;F>B&&T(Math.max(L,B),C==null&&L<=R,Math.min(F,U),A==null&&F>=N,oe.dir)}if(B=X.to+1,B>=U)break}return O.length==0&&T(R,C==null,N,A==null,t.textDirection),{top:S,bottom:k,horizontal:O}}function w(C,A){let E=o.top+(A?C.top:C.bottom);return{top:E,bottom:E,horizontal:[]}}}function $W(t,e){return t.constructor==e.constructor&&t.eq(e)}class BW{constructor(e,r){this.view=e,this.layer=r,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),r.above&&this.dom.classList.add("cm-layer-above"),r.class&&this.dom.classList.add(r.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),r.mount&&r.mount(this.dom,e)}update(e){e.startState.facet(Uf)!=e.state.facet(Uf)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let r=0,n=e.facet(Uf);for(;r<n.length&&n[r]!=this.layer;)r++;this.dom.style.zIndex=String((this.layer.above?150:-1)-r)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:r}=this.view;(e!=this.scaleX||r!=this.scaleY)&&(this.scaleX=e,this.scaleY=r,this.dom.style.transform=`scale(${1/e}, ${1/r})`)}draw(e){if(e.length!=this.drawn.length||e.some((r,n)=>!$W(r,this.drawn[n]))){let r=this.dom.firstChild,n=0;for(let s of e)s.update&&r&&s.constructor&&this.drawn[n].constructor&&s.update(r,this.drawn[n])?(r=r.nextSibling,n++):this.dom.insertBefore(s.draw(),r);for(;r;){let s=r.nextSibling;r.remove(),r=s}this.drawn=e,tt.safari&&tt.safari_version>=26&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Uf=it.define();function sT(t){return[ms.define(e=>new BW(e,t)),Uf.of(t)]}const Md=it.define({combine(t){return uc(t,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,r)=>Math.min(e,r),drawRangeCursor:(e,r)=>e||r})}});function FW(t={}){return[Md.of(t),WW,HW,UW,PP.of(!0)]}function iT(t){return t.startState.facet(Md)!=t.state.facet(Md)}const WW=sT({above:!0,markers(t){let{state:e}=t,r=e.facet(Md),n=[];for(let s of e.selection.ranges){let i=s==e.selection.main;if(s.empty||r.drawRangeCursor){let a=i?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",o=s.empty?s:ke.cursor(s.head,s.head>s.anchor?-1:1);for(let l of gh.forRange(t,a,o))n.push(l)}}return n},update(t,e){t.transactions.some(n=>n.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let r=iT(t);return r&&gS(t.state,e),t.docChanged||t.selectionSet||r},mount(t,e){gS(e.state,t)},class:"cm-cursorLayer"});function gS(t,e){e.style.animationDuration=t.facet(Md).cursorBlinkRate+"ms"}const HW=sT({above:!1,markers(t){return t.state.selection.ranges.map(e=>e.empty?[]:gh.forRange(t,"cm-selectionBackground",e)).reduce((e,r)=>e.concat(r))},update(t,e){return t.docChanged||t.selectionSet||t.viewportChanged||iT(t)},class:"cm-selectionLayer"}),UW=ul.highest(st.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),oT=sr.define({map(t,e){return t==null?null:e.mapPos(t)}}),td=gs.define({create(){return null},update(t,e){return t!=null&&(t=e.changes.mapPos(t)),e.effects.reduce((r,n)=>n.is(oT)?n.value:r,t)}}),zW=ms.fromClass(class{constructor(t){this.view=t,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(t){var e;let r=t.state.field(td);r==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="
47cm-dropCursor"),(t.startState.field(td)!=r||t.docChanged||t.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:t}=this,e=t.state.field(td),r=e!=null&&t.coordsAtPos(e);if(!r)return null;let n=t.scrollDOM.getBoundingClientRect();return{left:r.left-n.left+t.scrollDOM.scrollLeft*t.scaleX,top:r.top-n.top+t.scrollDOM.scrollTop*t.scaleY,height:r.bottom-r.top}}drawCursor(t){if(this.cursor){let{scaleX:e,scaleY:r}=this.view;t?(this.cursor.style.left=t.left/e+"px",this.cursor.style.top=t.top/r+"px",this.cursor.style.height=t.height/r+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(t){this.view.state.field(td)!=t&&this.view.dispatch({effects:oT.of(t)})}},{eventObservers:{dragover(t){this.setDropPos(this.view.posAtCoords({x:t.clientX,y:t.clientY}))},dragleave(t){(t.target==this.view.contentDOM||!this.view.contentDOM.contains(t.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function VW(){return[td,zW]}const bS=ms.fromClass(class{constructor(){this.height=1e3,this.attrs={style:"padding-bottom: 1000px"}}update(t){let{view:e}=t,r=e.viewState.editorHeight-e.defaultLineHeight-e.documentPadding.top-.5;r>=0&&r!=this.height&&(this.height=r,this.attrs={style:`padding-bottom: ${r}px`})}});function GW(){return[bS,xm.of(t=>{var e;return((e=t.plugin(bS))===null||e===void 0?void 0:e.attrs)||null})]}function qW(){return YW}const KW=lr.line({class:"cm-activeLine"}),YW=ms.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.docChanged||t.selectionSet)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=-1,r=[];for(let n of t.state.selection.ranges){let s=t.lineBlockAt(n.head);s.from>e&&(r.push(KW.range(s.from)),e=s.from)}return lr.set(r)}},{decorations:t=>t.decorations}),df="-10000px";class XW{constructor(e,r,n,s){this.facet=r,this.createTooltipView=n,this.removeTooltipView=s,this.input=e.state.facet(r),this.tooltips=this.input.filter(a=>a);let i=null;this.tooltipViews=this.tooltips.map(a=>i=n(a,i))}update(e,r){var n;let s=e.state.facet(this.facet),i=s.filter(l=>l);if(s===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let a=[],o=r?[]:null;for(let l=0;l<i.length;l++){let c=i[l],u=-1;if(c){for(let d=0;d<this.tooltips.length;d++){let h=this.tooltips[d];h&&h.create==c.create&&(u=d)}if(u<0)a[l]=this.createTooltipView(c,l?a[l-1]:null),o&&(o[l]=!!c.above);else{let d=a[l]=this.tooltipViews[u];o&&(o[l]=r[u]),d.update&&d.update(e)}}}for(let l of this.tooltipViews)a.indexOf(l)<0&&(this.removeTooltipView(l),(n=l.destroy)===null||n===void 0||n.call(l));return r&&(o.forEach((l,c)=>r[c]=l),r.length=o.length),this.input=s,this.tooltips=i,this.tooltipViews=a,!0}}function JW(t={}){return zf.of(t)}function QW(t){let e=t.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const zf=it.define({combine:t=>{var e,r,n;return{position:tt.ios?"absolute":((e=t.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((r=t.find(s=>s.parent))===null||r===void 0?void 0:r.parent)||null,tooltipSpace:((n=t.find(s=>
vendor: 9,505 bytes, line 47
47s.tooltipSpace))===null||n===void 0?void 0:n.tooltipSpace)||QW}}}),vS=new WeakMap,aT=ms.fromClass(class{constructor(t){this.view=t,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=t.state.facet(zf);this.position=e.position,this.parent=e.parent,this.classes=t.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new XW(t,$_,(r,n)=>this.createTooltip(r,n),r=>{this.resizeObserver&&this.resizeObserver.unobserve(r.dom),r.dom.remove()}),this.above=this.manager.tooltips.map(r=>!!r.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(r=>{Date.now()>this.lastTransaction-50&&r.length>0&&r[r.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),t.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let t of this.manager.tooltipViews)this.intersectionObserver.observe(t.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(t){t.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(t,this.above);e&&this.observeIntersection();let r=e||t.geometryChanged,n=t.state.facet(zf);if(n.position!=this.position&&!this.madeAbsolute){this.position=n.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;r=!0}if(n.parent!=this.parent){this.parent&&this.container.remove(),this.parent=n.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);r=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);r&&this.maybeMeasure()}createTooltip(t,e){let r=t.create(this.view),n=e?e.dom:null;if(r.dom.classList.add("cm-tooltip"),t.arrow&&!r.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",r.dom.appendChild(s)}return r.dom.style.position=this.position,r.dom.style.top=df,r.dom.style.left="0px",this.container.insertBefore(r.dom,n),r.mount&&r.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(r.dom),r}destroy(){var t,e,r;this.view.win.removeEventListener("resize",this.measureSoon);for(let n of this.manager.tooltipViews)n.dom.remove(),(t=n.destroy)===null||t===void 0||t.call(n);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(r=this.intersectionObserver)===null||r===void 0||r.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let t=1,e=1,r=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:i}=this.manager.tooltipViews[0];if(tt.safari){let a=i.getBoundingClientRect();r=Math.abs(a.top+1e4)>1||Math.abs(a.left)>1}else r=!!i.offsetParent&&i.offsetParent!=this.container.ownerDocument.body}if(r||this.position=="absolute")if(this.parent){let i=this.parent.getBoundingClientRect();i.width&&i.height&&(t=i.width/this.parent.offsetWidth,e=i.height/this.parent.offsetHeight)}else({scaleX:t,scaleY:e}=this.view.viewState);let n=this.view.scrollDOM.getBoundingClientRect(),s=D_(this.view);return{visible:{left:n.left+s.left,top:n.top+s.top,right:n.right-s.right,bottom:n.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((i,a)=>{let o=this.manager.tooltipViews[a];return o.getCoords?o.getCoords(i.pos):this.view.coordsAtPos(i.pos)}),size:this.manager.tooltipViews.map(({dom:i})=>i.getBoundingClientRect()),space:this.view.state.facet(zf).tooltipSpace(this.view),scaleX:t,scaleY:e,makeAbsolute:r}}writeMeasure(t){var e;if(t.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let o of this.manager.tooltipViews)o.dom.style.position="absolute"}let{visible:r,space:n,scaleX:s,scaleY:i}=t,a=[];for(let o=0;o<this.manager.tooltips.length;o++){let l=this.manager.tooltips[o],c=this.manager.tooltipViews[o],{dom:u}=c,d=t.pos[o],h=t.size[o];if(!d||l.clip!==!1&&(d.bottom<=Math.max(r.top,n.top)||d.top>=Math.min(r.bottom,n.bottom)||d.right<Math.max(r.left,n.left)-.1||d.left>Math.min(r.right,n.right)+.1)){u.style.top=df;continue}let m=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,b=m?7:0,g=h.right-h.left,p=(e=vS.get(c))!==null&&e!==void 0?e:h.bottom-h.top,y=c.offset||eH,v=this.view.textDirection==en.LTR,_=h.width>n.right-n.left?v?n.left:n.right-h.width:v?Math.max(n.left,Math.min(d.left-(m?14:0)+y.x,n.right-g)):Math.min(Math.max(n.left,d.left-g+(m?14:0)-y.x),n.right-g),w=this.above[o];!l.strictSide&&(w?d.top-p-b-y.y<n.top:d.bottom+p+b+y.y>n.bottom)&&w==n.bottom-d.bottom>d.top-n.top&&(w=this.above[o]=!w);let C=(w?d.top-n.top:n.bottom-d.bottom)-b;if(C<p&&c.resize!==!1){if(C<this.view.defaultLineHeight){u.style.top=df;continue}vS.set(c,p),u.style.height=(p=C)/i+"px"}else u.style.height&&(u.style.height="");let A=w?d.top-p-b-y.y:d.bottom+b+y.y,E=_+g;if(c.overlap!==!0)for(let S of a)S.left<E&&S.right>_&&S.top<A+p&&S.bottom>A&&(A=w?S.top-p-2-b:S.bottom+b+2);if(this.position=="absolute"?(u.style.top=(A-t.parent.top)/i+"px",yS(u,(_-t.parent.left)/s)):(u.style.top=A/i+"px",yS(u,_/s)),m){let S=d.left+(v?y.x:-y.x)-(_+14-7);m.style.left=S/s+"px"}c.overlap!==!0&&a.push({left:_,top:A,right:E,bottom:A+p}),u.classList.toggle("cm-tooltip-above",w),u.classList.toggle("cm-tooltip-below",!w),c.positioned&&c.positioned(t.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let t of this.manager.tooltipViews)t.dom.style.top=df}},{eventObservers:{scroll(){this.maybeMeasure()}}});function yS(t,e){let r=parseInt(t.style.left,10);(isNaN(r)||Math.abs(e-r)>1)&&(t.style.left=e+"px")}const ZW=st.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),eH={x:0,y:0},$_=it.define({enables:[aT,ZW]});function lT(t,e){let r=t.plugin(aT);if(!r)return null;let n=r.manager.tooltips.indexOf(e);return n<0?null:r.manager.tooltipViews[n]}const _S=it.define({combine(t){let e,r;for(let n of t)e=e||n.topContainer,r=r||n.bottomContainer;return{topContainer:e,bottomContainer:r}}});function kp(t,e){let r=t.plugin(cT),n=r?r.specs.indexOf(e):-1;return n>-1?r.panels[n]:null}const cT=ms.fromClass(class{constructor(t){this.input=t.state.facet(Pp),this.specs=this.input.filter(r=>r),this.panels=this.specs.map(r=>r(t));let e=t.state.facet(_S);this.top=new hf(t,!0,e.topContainer),this.bottom=new hf(t,!1,e.bottomContainer),this.top.sync(this.panels.filter(r=>r.top)),this.bottom.sync(this.panels.filter(r=>!r.top));for(let r of this.panels)r.dom.classList.add("cm-panel"),r.mount&&r.mount()}update(t){let e=t.state.facet(_S);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new hf(t.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new hf(t.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let r=t.state.facet(Pp);if(r!=this.input){let n=r.filter(l=>l),s=[],i=[],a=[],o=[];for(let l of n){let c=this.specs.indexOf(l),u;c<0?(u=l(t.view),o.push(u)):(u=this.panels[c],u.update&&u.update(t)),s.push(u),(u.top?i:a).push(u)}this.specs=n,this.panels=s,this.top.sync(i),this.bottom.sync(a);for(let l of o)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let n of this.panels)n.update&&n.update(t)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:t=>st.scrollMargins.of(e=>{let r=e.plugin(t);return r&&{top:r.top.scrollMargin(),bottom:r.bottom.scrollMargin()}})});let hf=class{constructor(e,r,n){this.view=e,this.top=r,this.container=n,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let r of this.panels)r.destroy&&e.indexOf(r)<0&&r.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"to
47p":"bottom"]="0";let r=this.container||this.view.dom;r.insertBefore(this.dom,this.top?r.firstChild:null)}let e=this.dom.firstChild;for(let r of this.panels)if(r.dom.parentNode==this.dom){for(;e!=r.dom;)e=xS(e);e=e.nextSibling}else this.dom.insertBefore(r.dom,e);for(;e;)e=xS(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}};function xS(t){let e=t.nextSibling;return t.remove(),e}const Pp=it.define({enables:cT});class ba extends rl{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}ba.prototype.elementClass="";ba.prototype.toDOM=void 0;ba.prototype.mapMode=Hs.TrackBefore;ba.prototype.startSide=ba.prototype.endSide=-1;ba.prototype.point=!0;const Vf=it.define(),tH=it.define(),rH={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>gr.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},md=it.define();function nH(t){return[uT(),md.of({...rH,...t})]}const wS=it.define({combine:t=>t.some(e=>e)});function uT(t){return[sH]}const sH=ms.fromClass(class{constructor(t){this.view=t,this.domAfter=null,this.prevViewport=t.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=t.state.facet(md).map(e=>new CS(t,e)),this.fixed=!t.state.facet(wS);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),t.scrollDOM.insertBefore(this.dom,t.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(t){if(this.updateGutters(t)){let e=this.prevViewport,r=t.view.viewport,n=Math.min(e.to,r.to)-Math.max(e.from,r.from);this.syncGutters(n<(r.to-r.from)*.8)}if(t.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(wS)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=t.view.viewport}syncGutters(t){let e=this.dom.nextSibling;t&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let r=gr.iter(this.view.state.facet(Vf),this.view.viewport.from),n=[],s=this.gutters.map(i=>new iH(i,this.view.viewport,-this.view.documentPadding.top));for(let i of this.view.viewportLineBlocks)if(n.length&&(n=[]),Array.isArray(i.type)){let a=!0;for(let o of i.type)if(o.type==Ls.Text&&a){iy(r,n,o.from);for(let l of s)l.line(this.view,o,n);a=!1}else if(o.widget)for(let l of s)l.widget(this.view,o)}else if(i.type==Ls.Text){iy(r,n,i.from);for(let a of s)a.line(this.view,i,n)}else if(i.widget)for(let a of s)a.widget(this.view,i);for(let i of s)i.finish();t&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(t){let e=t.startState.facet(md),r=t.state.facet(md),n=t.docChanged||t.heightChanged||t.viewportChanged||!gr.eq(t.startState.facet(Vf),t.state.facet(Vf),t.view.viewport.from,t.view.viewport.to);if(e==r)for(let s of this.gutters)s.update(t)&&(n=!0);else{n=!0;let s=[];for(let i of r){let a=e.indexOf(i);a<0?s.push(new CS(this.view,i)):(this.gutters[a].update(t),s.push(this.gutters[a]))}for(let i of this.gutters)i.dom.remove(),s.indexOf(i)<0&&i.destroy();for(let i of s)i.config.side=="after"?this.getDOMAfter().appendChild(i.dom):this.dom.appendChild(i.dom);this.gutters=s}return n}destroy(){for(let t of this.gutters)t.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:t=>st.scrollMargins.of(e=>{let r=e.plugin(t);
vendor: 4,753 bytes, line 47
47if(!r||r.gutters.length==0||!r.fixed)return null;let n=r.dom.offsetWidth*e.scaleX,s=r.domAfter?r.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==en.LTR?{left:n,right:s}:{right:n,left:s}})});function SS(t){return Array.isArray(t)?t:[t]}function iy(t,e,r){for(;t.value&&t.from<=r;)t.from==r&&e.push(t.value),t.next()}class iH{constructor(e,r,n){this.gutter=e,this.height=n,this.i=0,this.cursor=gr.iter(e.markers,r.from)}addElement(e,r,n){let{gutter:s}=this,i=(r.top-this.height)/e.scaleY,a=r.height/e.scaleY;if(this.i==s.elements.length){let o=new dT(e,a,i,n);s.elements.push(o),s.dom.appendChild(o.dom)}else s.elements[this.i].update(e,a,i,n);this.height=r.bottom,this.i++}line(e,r,n){let s=[];iy(this.cursor,s,r.from),n.length&&(s=s.concat(n));let i=this.gutter.config.lineMarker(e,r,s);i&&s.unshift(i);let a=this.gutter;s.length==0&&!a.config.renderEmptyElements||this.addElement(e,r,s)}widget(e,r){let n=this.gutter.config.widgetMarker(e,r.widget,r),s=n?[n]:null;for(let i of e.state.facet(tH)){let a=i(e,r.widget,r);a&&(s||(s=[])).push(a)}s&&this.addElement(e,r,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let r=e.elements.pop();e.dom.removeChild(r.dom),r.destroy()}}}class CS{constructor(e,r){this.view=e,this.config=r,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let n in r.domEventHandlers)this.dom.addEventListener(n,s=>{let i=s.target,a;if(i!=this.dom&&this.dom.contains(i)){for(;i.parentNode!=this.dom;)i=i.parentNode;let l=i.getBoundingClientRect();a=(l.top+l.bottom)/2}else a=s.clientY;let o=e.lineBlockAtHeight(a-e.documentTop);r.domEventHandlers[n](e,o,s)&&s.preventDefault()});this.markers=SS(r.markers(e)),r.initialSpacer&&(this.spacer=new dT(e,0,0,[r.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let r=this.markers;if(this.markers=SS(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let n=e.view.viewport;return!gr.eq(this.markers,r,n.from,n.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class dT{constructor(e,r,n,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,r,n,s)}update(e,r,n,s){this.height!=r&&(this.height=r,this.dom.style.height=r+"px"),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+"px":""),oH(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,r){let n="cm-gutterElement",s=this.dom.firstChild;for(let i=0,a=0;;){let o=a,l=i<r.length?r[i++]:null,c=!1;if(l){let u=l.elementClass;u&&(n+=" "+u);for(let d=a;d<this.markers.length;d++)if(this.markers[d].compare(l)){o=d,c=!0;break}}else o=this.markers.length;for(;a<o;){let u=this.markers[a++];if(u.toDOM){u.destroy(s);let d=s.nextSibling;s.remove(),s=d}}if(!l)break;l.toDOM&&(c?s=s.nextSibling:this.dom.insertBefore(l.toDOM(e),s)),c&&a++}this.dom.className=n,this.markers=r}destroy(){this.setMarkers(null,[])}}function oH(t,e){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!t[r].compare(e[r]))return!1;return!0}const aH=it.define(),lH=it.define(),$c=it.define({combine(t){return uc(t,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,r){let n=Object.assign({},e);for(let s in r){let i=n[s],a=r[s];n[s]=i?(o,l,c)=>i(o,l,c)||a(o,l,c):a}return n}})}});class tb extends ba{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function rb(t,e){return t.state.facet($c).formatNumber(e,t.state)}const cH=md.compute([$c],t=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(aH)},lineMarker(e,r,n){return n.some(s=>s.toDOM)?null:new tb(rb(e,e.state.doc.lineAt(r.from).number))},widgetMarker:(e,r,n)=>{for(let s of e.state.facet(lH)){let i=s(e,r,n);if(i)return i}return null},lineMarkerChange:e=>e.startState.facet($c)!=e.state.facet($c),initialSpacer(e){return new tb(rb(e,AS(e.state.doc.lines)))},updateSpacer(e,r){let n=rb(r.view,AS(r.view.state.doc.lines));return n==e.number?e:new tb(n)},domEventHandlers:t.facet($c).domEventHandlers,side:"before"}));function uH(t={}){return[$c.of(t),uT(),cH]}function AS(t){let e=9;for(;e<t;)e=e*10+9;return e}const dH=new class extends ba{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},hH=Vf.compute(["selection"],t=>{let e=[],r=-1;for(let n of t.selection.ranges){let s=t.doc.lineAt(n.head).from;s>r&&(r=s,e.push(dH.range(s)))}return gr.of(e)}
vendor: 50,708 bytes, line 47
47);function fH(){return hH}const pH=1024;let mH=0;class Yi{constructor(e,r){this.from=e,this.to=r}}class hr{constructor(e={}){this.id=mH++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Ci.match(e)),r=>{let n=e(r);return n===void 0?null:[this,n]}}}hr.closedBy=new hr({deserialize:t=>t.split(" ")});hr.openedBy=new hr({deserialize:t=>t.split(" ")});hr.group=new hr({deserialize:t=>t.split(" ")});hr.isolate=new hr({deserialize:t=>{if(t&&t!="rtl"&&t!="ltr"&&t!="auto")throw new RangeError("Invalid value for isolate: "+t);return t||"auto"}});hr.contextHash=new hr({perNode:!0});hr.lookAhead=new hr({perNode:!0});hr.mounted=new hr({perNode:!0});class Od{constructor(e,r,n){this.tree=e,this.overlay=r,this.parser=n}static get(e){return e&&e.props&&e.props[hr.mounted.id]}}const gH=Object.create(null);class Ci{constructor(e,r,n,s=0){this.name=e,this.props=r,this.id=n,this.flags=s}static define(e){let r=e.props&&e.props.length?Object.create(null):gH,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new Ci(e.name||"",r,e.id,n);if(e.props){for(let i of e.props)if(Array.isArray(i)||(i=i(s)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");r[i[0].id]=i[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let r=this.prop(hr.group);return r?r.indexOf(e)>-1:!1}return this.id==e}static match(e){let r=Object.create(null);for(let n in e)for(let s of n.split(" "))r[s]=e[n];return n=>{for(let s=n.prop(hr.group),i=-1;i<(s?s.length:0);i++){let a=r[i<0?n.name:s[i]];if(a)return a}}}}Ci.none=new Ci("",Object.create(null),0,8);class hT{constructor(e){this.types=e;for(let r=0;r<e.length;r++)if(e[r].id!=r)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let r=[];for(let n of this.types){let s=null;for(let i of e){let a=i(n);if(a){s||(s=Object.assign({},n.props));let o=a[1],l=a[0];l.combine&&l.id in s&&(o=l.combine(s[l.id],o)),s[l.id]=o}}r.push(s?new Ci(n.name,s,n.id,n.flags):n)}return new hT(r)}}const ff=new WeakMap,ES=new WeakMap;var _n;(function(t){t[t.ExcludeBuffers=1]="ExcludeBuffers",t[t.IncludeAnonymous=2]="IncludeAnonymous",t[t.IgnoreMounts=4]="IgnoreMounts",t[t.IgnoreOverlays=8]="IgnoreOverlays"})(_n||(_n={}));class rs{constructor(e,r,n,s,i){if(this.type=e,this.children=r,this.positions=n,this.length=s,this.props=null,i&&i.length){this.props=Object.create(null);for(let[a,o]of i)this.props[typeof a=="number"?a:a.id]=o}}toString(){let e=Od.get(this);if(e&&!e.overlay)return e.tree.toString();let r="";for(let n of this.children){let s=n.toString();s&&(r&&(r+=","),r+=s)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(r.length?"("+r+")":""):r}cursor(e=0){return new Tp(this.topNode,e)}cursorAt(e,r=0,n=0){let s=ff.get(this)||this.topNode,i=new Tp(s);return i.moveTo(e,r),ff.set(this,i._tree),i}get topNode(){return new zs(this,0,0,null)}resolve(e,r=0){let n=jd(ff.get(this)||this.topNode,e,r,!1);return ff.set(this,n),n}resolveInner(e,r=0){let n=jd(ES.get(this)||this.topNode,e,r,!0);return ES.set(this,n),n}resolveStack(e,r=0){return yH(this,e,r)}iterate(e){let{enter:r,leave:n,from:s=0,to:i=this.length}=e,a=e.mode||0,o=(a&_n.IncludeAnonymous)>0;for(let l=this.cursor(a|_n.IncludeAnonymous);;){let c=!1;if(l.from<=i&&l.to>=s&&(!o&&l.type.isAnonymous||r(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&n&&(o||!l.type.isAnonymous)&&n(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let r in this.props)e.push([+r,this.props[r]]);return e}balance(e={}){return this.children.length<=8?this:W_(Ci.none,this.children,this.positions,0,this.children.length,0,this.length,(r,n,s)=>new rs(this.type,r,n,s,this.propValues),e.makeTree||((r,n,s)=>new rs(Ci.none,r,n,s)))}static build(e){return _H(e)}}rs.empty=new rs(Ci.none,[],[],0);class B_{constructor(e,r){this.buffer=e,this.index=r}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new B_(this.buffer,this.index)}}class ol{constructor(e,r,n){this.buffer=e,this.length=r,this.set=n}get type(){return Ci.none}toString(){let e=[];for(let r=0;r<this.buffer.length;)e.push(this.childString(r)),r=this.buffer[r+3];return e.join(",")}childString(e){let r=this.buffer[e],n=this.buffer[e+3],s=this.set.types[r],i=s.name;if(/\W/.test(i)&&!s.isError&&(i=JSON.stringify(i)),e+=4,n==e)return i;let a=[];for(;e<n;)a.push(this.childString(e)),e=this.buffer[e+3];return i+"("+a.join(",")+")"}findChild(e,r,n,s,i){let{buffer:a}=this,o=-1;for(let l=e;l!=r&&!(fT(i,s,a[l+1],a[l+2])&&(o=l,n>0));l=a[l+3]);return o}slice(e,r,n){let s=this.buffer,i=new Uint16Array(r-e),a=0;for(let o=e,l=0;o<r;){i[l++]=s[o++],i[l++]=s[o++]-n;let c=i[l++]=s[o++]-n;i[l++]=s[o++]-e,a=Math.max(a,c)}return new ol(i,a,this.set)}}function fT(t,e,r,n){switch(t){case-2:return r<e;case-1:return n>=e&&r<e;case 0:return r<e&&n>e;case 1:return r<=e&&n>e;case 2:return n>e;case 4:return!0}}function jd(t,e,r,n){for(var s;t.from==t.to||(r<1?t.from>=e:t.from>e)||(r>-1?t.to<=e:t.to<e);){let a=!n&&t instanceof zs&&t.index<0?null:t.parent;if(!a)return t;t=a}let i=n?0:_n.IgnoreOverlays;if(n)for(let a=t,o=a.parent;o;a=o,o=a.parent)a instanceof zs&&a.index<0&&((s=o.enter(e,r,i))===null||s===void 0?void 0:s.from)!=a.from&&(t=o);for(;;){let a=t.enter(e,r,i);if(!a)return t;t=a}}class pT{cursor(e=0){return new Tp(this,e)}getChild(e,r=null,n=null){let s=kS(this,e,r,n);return s.length?s[0]:null}getChildren(e,r=null,n=null){return kS(this,e,r,n)}resolve(e,r=0){return jd(this,e,r,!1)}resolveInner(e,r=0){return jd(this,e,r,!0)}matchContext(e){return oy(this.parent,e)}enterUnfinishedNodesBefore(e){let r=this.childBefore(e),n=this;for(;r;){let s=r.lastChild;if(!s||s.to!=r.to)break;s.type.isError&&s.from==s.to?(n=r,r=s.prevSibling):r=s}return n}get node(){return this}get next(){return this.parent}}class zs extends pT{constructor(e,r,n,s){super(),this._tree=e,this.from=r,this.index=n,this._parent=s}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,r,n,s,i=0){for(let a=this;;){for(let{children:o,positions:l}=a._tree,c=r>0?o.length:-1;e!=c;e+=r){let u=o[e],d=l[e]+a.from;if(fT(s,n,d,d+u.length)){if(u instanceof ol){if(i&_n.ExcludeBuffers)continue;let h=u.findChild(0,u.buffer.length,r,n-d,s);if(h>-1)return new jo(new bH(a,u,e,d),null,h)}else if(i&_n.IncludeAnonymous||!u.type.isAnonymous||F_(u)){let h;if(!(i&_n.IgnoreMounts)&&(h=Od.get(u))&&!h.overlay)return new zs(h.tree,d,e,a);let m=new zs(u,d,e,a);return i&_n.IncludeAnonymous||!m.type.isAnonymous?m:m.nextChild(r<0?u.children.length-1:0,r,n,s)}}}if(i&_n.IncludeAnonymous||!a.type.isAnonymous||(a.index>=0?e=a.index+r:e=r<0?-1:a._parent._tree.children.length,a=a._parent,!a))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,r,n=0){let s;if(!(n&_n.IgnoreOverlays)&&(s=Od.get(this._tree))&&s.overlay){let i=e-this.from;for(let{from:a,to:o}of s.overlay)if((r>0?a<=i:a<i)&&(r<0?o>=i:o>i))return new zs(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,r,n)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function kS(t,e,r,n){let s=t.cursor(),i=[];if(!s.firstChild())return i;if(r!=null){for(let a=!1;!a;)if(a=s.type.is(r),!s.nextSibling())return i}for(;;){if(n!=null&&s.type.is(n))return i;if(s.type.is(e)&&i.push(s.node),!s.nextSibling())return n==null?i:[]}}function oy(t,e,r=e.length-1){for(let n=t;r>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[r]&&e[r]!=n.name)return!1;r--}}return!0}class bH{constructor(e,r,n,s){this.parent=e,this.buffer=r,this.index=n,this.start=s}}class jo extends pT{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,r,n){super(),this.context=e,this._parent=r,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(e,r,n){let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],e,r-this.context.start,n);return i<0?null:new jo(this.context,this,i)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,r,n=0){if(n&_n.ExcludeBuffers)return null;let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],r>0?1:-1,e-this.context.start,r);return i<0?null:new jo(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,r=e.buffer[this.index+3];return r<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new jo(this.context,this._parent,r):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,r=this._parent?this._parent.index+4:0;return this.index==r?this.externalSibling(-1):new jo(this.context,this._parent,e.findChild(r,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],r=[],{buffer:n}=this.context,s=this.index+4,i=n.buffer[this.index+3];if(i>s){let a=n.buffer[this.index+1];e.push(n.slice(s,i,a)),r.push(0)}return new rs(this.type,e,r,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function mT(t){if(!t.length)return null;let e=0,r=t[0];for(let i=1;i<t.length;i++){let a=t[i];(a.from>r.from||a.to<r.to)&&(r=a,e=i)}let n=r instanceof zs&&r.index<0?null:r.parent,s=t.slice();return n?s[e]=n:s.splice(e,1),new vH(s,r)}class vH{constructor(e,r){this.heads=e,this.node=r}get next(){return mT(this.heads)}}function yH(t,e,r){let n=t.resolveInner(e,r),s=null;for(let i=n instanceof zs?n:n.context.parent;i;i=i.parent)if(i.index<0){let a=i.parent;(s||(s=[n])).push(a.resolve(e,r)),i=a}else{let a=Od.get(i.tree);if(a&&a.overlay&&a.overlay[0].from<=e&&a.overlay[a.overlay.length-1].to>=e){let o=new zs(a.tree,a.overlay[0].from+i.from,-1,i);(s||(s=[n])).push(jd(o,e,r,!1))}}return s?mT(s):n}class Tp{get name(){return this.type.name}constructor(e,r=0){if(this.mode=r,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof zs)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let n=e._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,r){this.index=e;let{start:n,buffer:s}=this.buffer;return this.type=r||s.set.types[s.buffer[e]],this.from=n+s.buffer[e+1],this.to=n+s.buffer[e+2],!0}yield(e){return e?e instanceof zs?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,r,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,r,n,this.mode));let{buffer:s}=this.buffer,i=s.findChild(this.index+4,s.buffer[this.index+3],e,r-this.buffer.start,n);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,r,n=this.mode){return this.buffer?n&_n.ExcludeBuffers?!1:this.enterChild(1,e,r):this.yield(this._tree.enter(e,r,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&_n.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&_n.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:r}=this.buffer,n=this.stack.length-1;if(e<0){let s=n<0?0:this.stack[n]+4;if(this.index!=s)return this.yieldBuf(r.findChild(s,this.index,-1,0,4))}else{let s=r.buffer[this.index+3];if(s<(n<0?r.buffer.length:r.buffer[this.stack[n]+3]))return this.yieldBuf(s)}return n<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let r,n,{buffer:s}=this;if(s){if(e>0){if(this.index<s.buffer.buffer.length)return!1}else for(let i=0;i<this.index;i++)if(s.buffer.buffer[i+3]<this.index)return!1;({index:r,parent:n}=s)}else({index:r,_parent:n}=this._tree);for(;n;{index:r,_parent:n}=n)if(r>-1)for(let i=r+e,a=e<0?-1:n._tree.children.length;i!=a;i+=e){let o=n._tree.children[i];if(this.mode&_n.IncludeAnonymous||o instanceof ol||!o.type.isAnonymous||F_(o))return!1}return!0}move(e,r){if(r&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,r=0){for(;(this.from==this.to||(r<1?this.from>=e:this.from>e)||(r>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,r););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,r=null,n=0;if(e&&e.context==this.buffer)e:for(let s=this.index,i=this.stack.length;i>=0;){for(let a=e;a;a=a._parent)if(a.index==s){if(s==this.index)return a;r=a,n=i+1;break e}s=this.stack[--i]}for(let s=n;s<this.stack.length;s++)r=new jo(this.buffer,r,this.stack[s]);return this.bufferNode=new jo(this.buffer,r,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,r){for(let n=0;;){let s=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(s=!0)}for(;;){if(s&&r&&r(this),s=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,s=!0}}}matchContext(e){if(!this.buffer)return oy(this.node.parent,e);let{buffer:r}=this.buffer,{types:n}=r.set;for(let s=e.length-1,i=this.stack.length-1;s>=0;i--){if(i<0)return oy(this._tree,e,s);let a=n[r.buffer[this.stack[i]]];if(!a.isAnonymous){if(e[s]&&e[s]!=a.name)return!1;s--}}return!0}}function F_(t){return t.children.some(e=>e instanceof ol||!e.type.isAnonymous||F_(e))}function _H(t){var e;let{buffer:r,nodeSet:n,maxBufferLength:s=pH,reused:i=[],minRepeatType:a=n.types.length}=t,o=Array.isArray(r)?new B_(r,r.length):r,l=n.types,c=0,u=0;function d(C,A,E,S,k,O){let{id:T,start:R,end:N,size:M}=o,B=u,U=c;if(M<0)if(o.next(),M==-1){let V=i[T];E.push(V),S.push(R-C);return}else if(M==-3){c=T;return}else if(M==-4){u=T;return}else throw new RangeError(`Unrecognized record size: ${M}`);let X=l[T],oe,L,F=R-C;if(N-R<=s&&(L=p(o.pos-A,k))){let V=new Uint16Array(L.size-L.skip),Z=o.pos-L.size,K=V.length;for(;o.pos>Z;)K=y(L.start,V,K);oe=new ol(V,N-L.start,n),F=L.start-C}else{let V=o.pos-M;o.next();let Z=[],K=[],ie=T>=a?T:-1,se=0,fe=N;for(;o.pos>V;)ie>=0&&o.id==ie&&o.size>=0?(o.end<=fe-s&&(b(Z,K,R,se,o.end,fe,ie,B,U),se=Z.length,fe=o.end),o.next()):O>2500?h(R,V,Z,K):d(R,V,Z,K,ie,O+1);if(ie>=0&&se>0&&se<Z.length&&b(Z,K,R,se,R,fe,ie,B,U),Z.reverse(),K.reverse(),ie>-1&&se>0){let Y=m(X,U);oe=W_(X,Z,K,0,Z.length,0,N-R,Y,Y)}else oe=g(X,Z,K,N-R,B-N,U)}E.push(oe),S.push(F)}function h(C,A,E,S){let k=[],O=0,T=-1;for(;o.pos>A;){let{id:R,start:N,end:M,size:B}=o;if(B>4)o.next();else{if(T>-1&&N<T)break;T<0&&(T=M-s),k.push(R,N,M),O++,o.next()}}if(O){let R=new Uint16Array(O*4),N=k[k.length-2];for(let M=k.length-3,B=0;M>=0;M-=3)R[B++]=k[M],R[B++]=k[M+1]-N,R[B++]=k[M+2]-N,R[B++]=B;E.push(new ol(R,k[2]-N,n)),S.push(N-C)}}function m(C,A){return(E,S,k)=>{let O=0,T=E.length-1,R,N;if(T>=0&&(R=E[T])instanceof rs){if(!T&&R.type==C&&R.length==k)return R;(N=R.prop(hr.lookAhead))&&(O=S[T]+R.length+N)}return g(C,E,S,k,O,A)}}function b(C,A,E,S,k,O,T,R,N){let M=[],B=[];for(;C.length>S;)M.push(C.pop()),B.push(A.pop()+E-k);C.push(g(n.types[T],M,B,O-k,R-O,N)),A.push(k-E)}function g(C,A,E,S,k,O,T){if(O){let R=[hr.contextHash,O];T=T?[R].concat(T):[R]}if(k>25){let R=[hr.lookAhead,k];T=T?[R].concat(T):[R]}return new rs(C,A,E,S,T)}function p(C,A){let E=o.fork(),S=0,k=0,O=0,T=E.end-s,R={size:0,start:0,skip:0};e:for(let N=E.pos-C;E.pos>N;){let M=E.size;if(E.id==A&&M>=0){R.size=S,R.start=k,R.skip=O,O+=4,S+=4,E.next();continue}let B=E.pos-M;if(M<0||B<N||E.start<T)break;let U=E.id>=a?4:0,X=E.start;for(E.next();E.pos>B;){if(E.size<0)if(E.size==-3||E.size==-4)U+=4;else break e;else E.id>=a&&(U+=4);E.next()}k=X,S+=M,O+=U}return(A<0||S==C)&&(R.size=S,R.start=k,R.skip=O),R.size>4?R:void 0}function y(C,A,E){let{id:S,start:k,end:O,size:T}=o;if(o.next(),T>=0&&S<a){let R=E;if(T>4){let N=o.pos-(T-4);for(;o.pos>N;)E=y(C,A,E)}A[--E]=R,A[--E]=O-C,A[--E]=k-C,A[--E]=S}else T==-3?c=S:T==-4&&(u=S);return E}let v=[],_=[];for(;o.pos>0;)d(t.start||0,t.bufferStart||0,v,_,-1,0);let w=(e=t.length)!==null&&e!==void 0?e:v.length?_[0]+v[0].length:0;return new rs(l[t.topID],v.reverse(),_.reverse(),w)}const PS=new WeakMap;function Gf(t,e){if(!t.isAnonymous||e instanceof ol||e.type!=t)return 1;let r=PS.get(e);if(r==null){r=1;for(let n of e.children){if(n.type!=t||!(n instanceof rs)){r=1;break}r+=Gf(t,n)}PS.set(e,r)}return r}function W_(t,e,r,n,s,i,a,o,l){let c=0;for(let b=n;b<s;b++)c+=Gf(t,e[b]);let u=Math.ceil(c*1.5/8),d=[],h=[];function m(b,g,p,y,v){for(let _=p;_<y;){let w=_,C=g[_],A=Gf(t,b[_]);for(_++;_<y;_++){let E=Gf(t,b[_]);if(A+E>=u)break;A+=E}if(_==w+1){if(A>u){let E=b[w];m(E.children,E.positions,0,E.children.length,g[w]+v);continue}d.push(b[w])}else{let E=g[_-1]+b[_-1].length-C;d.push(W_(t,b,g,w,_,C,E,null,l))}h.push(C+v-i)}}return m(e,r,n,s,0),(o||l)(d,h,a)}class woe{constructor(){this.map=new WeakMap}setBuffer(e,r,n){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(r,n)}getBuffer(e,r){let n=this.map.get(e);return n&&n.get(r)}set(e,r){e instanceof jo?this.setBuffer(e.context.buffer,e.index,r):e instanceof zs&&this.map.set(e.tree,r)}get(e){return e instanceof jo?this.getBuffer(e.context.buffer,e.index):e instanceof zs?this.map.get(e.tree):void 0}cursorSet(e,r){e.buffer?this.setBuffer(e.buffer.buffer,e.index,r):this.map.set(e.tree,r)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class ha{constructor(e,r,n,s,i=!1,a=!1){this.from=e,this.to=r,this.tree=n,this.offset=s,this.open=(i?1:0)|(a?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,r=[],n=!1){let s=[new ha(0,e.length,e,0,!1,n)];for(let i of r)i.to>e.length&&s.push(i);return s}static applyChanges(e,r,n=128){if(!r.length)return e;let s=[],i=1,a=e.length?e[0]:null;for(let o=0,l=0,c=0;;o++){let u=o<r.length?r[o]:null,d=u?u.fromA:1e9;if(d-l>=n)for(;a&&a.from<d;){let h=a;if(l>=h.from||d<=h.to||c){let m=Math.max(h.from,l)-c,b=Math.min(h.to,d)-c;h=m>=b?null:new ha(m,b,h.tree,h.offset+c,o>0,!!u)}if(h&&s.push(h),a.to>d)break;a=i<e.length?e[i++]:null}if(!u)break;l=u.toA,c=u.toA-u.toB}return s}}class xH{startParse(e,r,n){return typeof e=="string"&&(e=new wH(e)),n=n?n.length?n.map(s=>new Yi(s.from,s.to)):[new Yi(0,0)]:[new Yi(0,e.length)],this.createParse(e,r||[],n)}parse(e,r,n){let s=this.startParse(e,r,n);for(;;){let i=s.advance();if(i)return i}}}class wH{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,r){return this.string.slice(e,r)}}function Soe(t){return(e,r,n,s)=>new CH(e,t,r,n,s)}class TS{constructor(e,r,n,s,i){this.parser=e,this.parse=r,this.overlay=n,this.target=s,this.from=i}}function RS(t){if(!t.length||t.some(e=>e.from>=e.to))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(t))}class SH{constructor(e,r,n,s,i,a,o){this.parser=e,this.predicate=r,this.mounts=n,this.index=s,this.start=i,this.target=a,this.prev=o,this.depth=0,this.ranges=[]}}const ay=new hr({perNode:!0});class CH{constructor(e,r,n,s,i){this.nest=r,this.input=n,this.fragments=s,this.ranges=i,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let n=this.baseParse.advance();if(!n)return null;if(this.baseParse=null,this.baseTree=n,this.startInner(),this.stoppedAt!=null)for(let s of this.inner)s.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let n=this.baseTree;return this.stoppedAt!=null&&(n=new rs(n.type,n.children,n.positions,n.length,n.propValues.concat([[ay,this.stoppedAt]]))),n}let e=this.inner[this.innerDone],r=e.parse.advance();if(r){this.innerDone++;let n=Object.assign(Object.create(null),e.target.props);n[hr.mounted.id]=new Od(r,e.overlay,e.parser),e.target.props=n}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let r=this.innerDone;r<this.inner.length;r++)this.inner[r].from<e&&(e=Math.min(e,this.inner[r].parse.parsedPos));return e}stopAt(e){if(this.stoppedAt=e,this.baseParse)this.baseParse.stopAt(e);else for(let r=this.innerDone;r<this.inner.length;r++)this.inner[r].parse.stopAt(e)}startInner(){let e=new kH(this.fragments),r=null,n=null,s=new Tp(new zs(this.baseTree,this.ranges[0].from,0,null),_n.IncludeAnonymous|_n.IgnoreMounts);e:for(let i,a;;){let o=!0,l;if(this.stoppedAt!=null&&s.from>=this.stoppedAt)o=!1;else if(e.hasNode(s)){if(r){let c=r.mounts.find(u=>u.frag.from<=s.from&&u.frag.to>=s.to&&u.mount.overlay);if(c)for(let u of c.mount.overlay){let d=u.from+c.pos,h=u.to+c.pos;d>=s.from&&h<=s.to&&!r.ranges.some(m=>m.from<h&&m.to>d)&&r.ranges.push({from:d,to:h})}}o=!1}else if(n&&(a=AH(n.ranges,s.from,s.to)))o=a!=2;else if(!s.type.isAnonymous&&(i=this.nest(s,this.input))&&(s.from<s.to||!i.overlay)){s.tree||(EH(s),r&&r.depth++,n&&n.depth++);let c=e.findMounts(s.from,i.parser);if(typeof i.overlay=="function")r=new SH(i.parser,i.overlay,c,this.inner.length,s.from,s.tree,r);else{let u=LS(this.ranges,i.overlay||(s.from<s.to?[new Yi(s.from,s.to)]:[]));u.length&&RS(u),(u.length||!i.overlay)&&this.inner.push(new TS(i.parser,u.length?i.parser.startParse(this.input,DS(c,u),u):i.parser.startParse(""),i.overlay?i.overlay.map(d=>new Yi(d.from-s.from,d.to-s.from)):null,s.tree,u.length?u[0].from:s.from)),i.overlay?u.length&&(n={ranges:u,depth:0,prev:n}):o=!1}}else if(r&&(l=r.predicate(s))&&(l===!0&&(l=new Yi(s.from,s.to)),l.from<l.to)){let c=r.ranges.length-1;c>=0&&r.ranges[c].to==l.from?r.ranges[c]={from:r.ranges[c].from,to:l.to}:r.ranges.push(l)}if(o&&s.firstChild())r&&r.depth++,n&&n.depth++;else for(;!s.nextSibling();){if(!s.parent())break e;if(r&&!--r.depth){let c=LS(this.ranges,r.ranges);c.length&&(RS(c),this.inner.splice(r.index,0,new TS(r.parser,r.parser.startParse(this.input,DS(r.mounts,c),c),r.ranges.map(u=>new Yi(u.from-r.start,u.to-r.start)),r.target,c[0].from))),r=r.prev}n&&!--n.depth&&(n=n.prev)}}}}function AH(t,e,r){for(let n of t){if(n.from>=r)break;if(n.to>e)return n.from<=e&&n.to>=r?2:1}return 0}function IS(t,e,r,n,s,i){if(e<r){let a=t.buffer[e+1];n.push(t.slice(e,r,a)),s.push(a-i)}}function EH(t){let{node:e}=t,r=[],n=e.context.buffer;do r.push(t.index),t.parent();while(!t.tree);let s=t.tree,i=s.children.indexOf(n),a=s.children[i],o=a.buffer,l=[i];function c(u,d,h,m,b,g){let p=r[g],y=[],v=[];IS(a,u,p,y,v,m);let _=o[p+1],w=o[p+2];l.push(y.length);let C=g?c(p+4,o[p+3],a.set.types[o[p]],_,w-_,g-1):e.toTree();return y.push(C),v.push(_-m),IS(a,o[p+3],d,y,v,m),new rs(h,y,v,b)}s.children[i]=c(0,o.length,Ci.none,0,a.length,r.length-1);for(let u of l){let d=t.tree.children[u],h=t.tree.positions[u];t.yield(new zs(d,h+t.from,u,t._tree))}}class NS{constructor(e,r){this.offset=r,this.done=!1,this.cursor=e.cursor(_n.IncludeAnonymous|_n.IgnoreMounts)}moveTo(e){let{cursor:r}=this,n=e-this.offset;for(;!this.done&&r.from<n;)r.to>=e&&r.enter(n,1,_n.IgnoreOverlays|_n.ExcludeBuffers)||r.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let r=this.cursor.tree;;){if(r==e.tree)return!0;if(r.children.length&&r.positions[0]==0&&r.children[0]instanceof rs)r=r.children[0];else break}return!1}}class kH{constructor(e){var r;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let n=this.curFrag=e[0];this.curTo=(r=n.tree.prop(ay))!==null&&r!==void 0?r:n.to,this.inner=new NS(n.tree,-n.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let r=this.curFrag=this.fragments[this.fragI];this.curTo=(e=r.tree.prop(ay))!==null&&e!==void 0?e:r.to,this.inner=new NS(r.tree,-r.offset)}}findMounts(e,r){var n;let s=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let i=this.inner.cursor.node;i;i=i.parent){let a=(n=i.tree)===null||n===void 0?void 0:n.prop(hr.mounted);if(a&&a.parser==r)for(let o=this.fragI;o<this.fragments.length;o++){let l=this.fragments[o];if(l.from>=i.to)break;l.tree==this.curFrag.tree&&s.push({frag:l,pos:i.from-l.offset,mount:a})}}}return s}}function LS(t,e){let r=null,n=e;for(let s=1,i=0;s<t.length;s++){let a=t[s-1].to,o=t[s].from;for(;i<n.length;i++){let l=n[i];if(l.from>=o)break;l.to<=a||(r||(n=r=e.slice()),l.from<a?(r[i]=new Yi(l.from,a),l.to>o&&r.splice(i+1,0,new Yi(o,l.to))):l.to>o?r[i--]=new Yi(o,l.to):r.splice(i--,1))}}return n}function PH(t,e,r,n){let s=0,i=0,a=!1,o=!1,l=-1e9,c=[];for(;;){let u=s==t.length?1e9:a?t[s].to:t[s].from,d=i==e.length?1e9:o?e[i].to:e[i].from;if(a!=o){let h=Math.max(l,r),m=Math.min(u,d,n);h<m&&c.push(new Yi(h,m))}if(l=Math.min(u,d),l==1e9)break;u==l&&(a?(a=!1,s++):a=!0),d==l&&(o?(o=!1,i++):o=!0)}return c}function DS(t,e){let r=[];for(let{pos:n,mount:s,frag:i}of t){let a=n+(s.overlay?s.overlay[0].from:0),o=a+s.tree.length,l=Math.max(i.from,a),c=Math.min(i.to,o);if(s.overlay){let u=s.overlay.map(h=>new Yi(h.from+n,h.to+n)),d=PH(e,u,l,c);for(let h=0,m=l;;h++){let b=h==d.length,g=b?c:d[h].from;if(g>m&&r.push(new ha(m,g,s.tree,-a,i.from>=m||i.openStart,i.to<=g||i.openEnd)),b)break;m=d[h].to}}else r.push(new ha(l,c,s.tree,-a,i.from>=a||i.openStart,i.to<=o||i.openEnd))}return r}let TH=0;class qi{constructor(e,r,n,s){this.name=e,this.set=r,this.base=n,this.modified=s,this.id=TH++}toString(){let{name:e}=this;for(let r of this.modified)r.name&&(e=`${r.name}(${e})`);return e}static define(e,r){let n=typeof e=="string"?e:"?";if(e instanceof qi&&(r=e),r?.base)throw new Error("Can not derive from a modified tag");let s=new qi(n,[],null,[]);if(s.set.push(s),r)for(let i of r.set)s.set.push(i);return s}static defineModifier(e){let r=new Rp(e);return n=>n.modified.indexOf(r)>-1?n:Rp.get(n.base||n,n.modified.concat(r).sort((s,i)=>s.id-i.id))}}let RH=0;class Rp{constructor(e){this.name=e,this.instances=[],this.id=RH++}static get(e,r){if(!r.length)return e;let n=r[0].instances.find(o=>o.base==e&&IH(r,o.modified));if(n)return n;let s=[],i=new qi(e.name,s,e,r);for(let o of r)o.instances.push(i);let a=NH(r);for(let o of e.set)if(!o.modified.length)for(let l of a)s.push(Rp.get(o,l));return i}}function IH(t,e){return t.length==e.length&&t.every((r,n)=>r==e[n])}function NH(t){let e=[[]];for(let r=0;r<t.length;r++)for(let n=0,s=e.length;n<s;n++)e.push(e[n].concat(t[r]));return e.sort((r,n)=>n.length-r.length)}function LH(t){let e=Object.create(null);for(let r in t){let n=t[r];Array.isArray(n)||(n=[n]);for(let s of r.split(" "))if(s){let i=[],a=2,o=s;for(let d=0;;){if(o=="..."&&d>0&&d+3==s.length){a=1;break}let h=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(o);if(!h)throw new RangeError("Invalid path: "+s);if(i.push(h[0]=="*"?"":h[0][0]=='"'?JSON.parse(h[0]):h[0]),d+=h[0].length,d==s.length)break;let m=s[d++];if(d==s.length&&m=="!"){a=0;break}if(m!="/")throw new RangeError("Invalid path: "+s);o=s.slice(d)}let l=i.length-1,c=i[l];if(!c)throw new RangeError("Invalid path: "+s);let u=new $d(n,a,l>0?i.slice(0,l):null);e[c]=u.sort(e[c])}}return gT.add(e)}const gT=new hr({combine(t,e){let r,n,s;for(;t||e;){if(!t||e&&t.depth>=e.depth?(s=e,e=e.next):(s=t,t=t.next),r&&r.mode==s.mode&&!s.context&&!r.context)continue;let i=new $d(s.tags,s.mode,s.context);r?r.next=i:n=i,r=i}return n}});let $d=class{constructor(e,r,n,s){this.tags=e,this.mode=r,this.context=n,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}};$d.empty=new $d([],2,null);function bT(t,e){let r=Object.create(null);for(let i of t)if(!Array.isArray(i.tag))r[i.tag.id]=i.class;else for(let a of i.tag)r[a.id]=i.class;let{scope:n,all:s=null}=e||{};return{style:i=>{let a=s;for(let o of i)for(let l of o.set){let c=r[l.id];if(c){a=a?a+" "+c:c;break}}return a},scope:n}}function DH(t,e){let r=null;for(let n of t){let s=n.style(e);s&&(r=r?r+" "+s:s)}return r}function MH(t,e,r,n=0,s=t.length){let i=new OH(n,Array.isArray(e)?e:[e],r);i.highlightRange(t.cursor(),n,s,"",i.highlighters),i.flush(s)}class OH{constructor(e,r,n){this.at=e,this.highlighters=r,this.span=n,this.class=""}startSpan(e,r){r!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=r)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,r,n,s,i){let{type:a,from:o,to:l}=e;if(o>=n||l<=r)return;a.isTop&&(i=this.highlighters.filter(m=>!m.scope||m.scope(a)));let c=s,u=jH(e)||$d.empty,d=DH(i,u.tags);if(d&&(c&&(c+=" "),c+=d,u.mode==1&&(s+=(s?" ":"")+d)),this.startSpan(Math.max(r,o),c),u.opaque)return;let h=e.tree&&e.tree.prop(hr.mounted);if(h&&h.overlay){let m=e.node.enter(h.overlay[0].from+o,1),b=this.highlighters.filter(p=>!p.scope||p.scope(h.tree.type)),g=e.firstChild();for(let p=0,y=o;;p++){let v=p<h.overlay.length?h.overlay[p]:null,_=v?v.from+o:l,w=Math.max(r,y),C=Math.min(n,_);if(w<C&&g)for(;e.from<C&&(this.highlightRange(e,w,C,s,i),this.startSpan(Math.min(C,e.to),c),!(e.to>=_||!e.nextSibling())););if(!v||_>n)break;y=v.to+o,y>r&&(this.highlightRange(m.cursor(),Math.max(r,v.from+o),Math.min(n,y),"",b),this.startSpan(Math.min(n,y),c))}g&&e.parent()}else if(e.firstChild()){h&&(s="");do if(!(e.to<=r)){if(e.from>=n)break;this.highlightRange(e,r,n,s,i),this.startSpan(Math.min(n,e.to),c)}while(e.nextSibling());e.parent()}}}function jH(t){let e=t.type.prop(gT);for(;e&&e.context&&!t.matchContext(e.context);)e=e.next;return e||null}const Ke=qi.define,pf=Ke(),za=Ke(),MS=Ke(za),OS=Ke(za),Va=Ke(),mf=Ke(Va),nb=Ke(Va),To=Ke(),Sl=Ke(To),Ao=Ke(),Eo=Ke(),ly=Ke(),Wu=Ke(ly),gf=Ke(),he={comment:pf,lineComment:Ke(pf),blockComment:Ke(pf),docComment:Ke(pf),name:za,variableName:Ke(za),typeName:MS,tagName:Ke(MS),propertyName:OS,attributeName:Ke(OS),className:Ke(za),labelName:Ke(za),namespace:Ke(za),macroName:Ke(za),literal:Va,string:mf,docString:Ke(mf),character:Ke(mf),attributeValue:Ke(mf),number:nb,integer:Ke(nb),float:Ke(nb),bool:Ke(Va),regexp:Ke(Va),escape:Ke(Va),color:Ke(Va),url:Ke(Va),keyword:Ao,self:Ke(Ao),null:Ke(Ao),atom:Ke(Ao),unit:Ke(Ao),modifier:Ke(Ao),operatorKeyword:Ke(Ao),controlKeyword:Ke(Ao),definitionKeyword:Ke(Ao),moduleKeyword:Ke(Ao),operator:Eo,derefOperator:Ke(Eo),arithmeticOperator:Ke(Eo),logicOperator:Ke(Eo),bitwiseOperator:Ke(Eo),compareOperator:Ke(Eo),updateOperator:Ke(Eo),definitionOperator:Ke(Eo),typeOperator:Ke(Eo),controlOperator:Ke(Eo),punctuation:ly,separator:Ke(ly),bracket:Wu,angleBracket:Ke(Wu),squareBracket:Ke(Wu),paren:Ke(Wu),brace:Ke(Wu),content:To,heading:Sl,heading1:Ke(Sl),heading2:Ke(Sl),heading3:Ke(Sl),heading4:Ke(Sl),heading5:Ke(Sl),heading6:Ke(Sl),contentSeparator:Ke(To),list:Ke(To),quote:Ke(To),emphasis:Ke(To),strong:Ke(To),link:Ke(To),monospace:Ke(To),strikethrough:Ke(To),inserted:Ke(),deleted:Ke(),changed:Ke(),invalid:Ke(),meta:gf,documentMeta:Ke(gf),annotation:Ke(gf),processingInstruction:Ke(gf),definition:qi.defineModifier("definition"),constant:qi.defineModifier("constant"),function:qi.defineModifier("function"),standard:qi.defineModifier("standard"),local:qi.defineModifier("local"),special:qi.defineModifier("special")};for(let t in he){let e=he[t];e instanceof qi&&(e.name=t)}bT([{tag:he.link,class:"tok-link"},{tag:he.heading,class:"tok-heading"},{tag:he.emphasis,class:"tok-emphasis"},{tag:he.strong,class:"tok-strong"},{tag:he.keyword,class:"tok-keyword"},{tag:he.atom,class:"tok-atom"},{tag:he.bool,class:"tok-bool"},{tag:he.url,class:"tok-url"},{tag:he.labelName,class:"tok-labelName"},{tag:he.inserted,class:"tok-inserted"},{tag:he.deleted,class:"tok-deleted"},{tag:he.literal,class:"tok-literal"},{tag:he.string,class:"tok-string"},{tag:he.number,class:"tok-number"},{tag:[he.regexp,he.escape,he.special(he.string)],class:"tok-string2"},{tag:he.variableName,class:"tok-variableName"},{tag:he.local(he.variableName),class:"tok-variableName tok-local"},{tag:he.definition(he.variableName),class:"tok-variableName tok-definition"},{tag:he.special(he.variableName),class:"tok-variableName2"},{tag:he.definition(he.propertyName),class:"tok-propertyName tok-definition"},{tag:he.typeName,class:"tok-typeName"},{tag:he.namespace,class:"tok-namespace"},{tag:he.className,class:"tok-className"},{tag:he.macroName,class:"tok-macroName"},{tag:he.propertyName,class:"tok-propertyName"},{tag:he.operator,class:"tok-operator"},{tag:he.comment,class:"tok-comment"},{tag:he.meta,class:"tok-meta"},{tag:he.invalid,class:"tok-invalid"},{tag:he.punctuation,class:"tok-punctuation"}]);var sb;const Bc=new hr;function $H(t){return it.define({combine:t?e=>e.concat(t):void 0})}const BH=new hr;class fo{constructor(e,r,n=[],s=""){this.data=e,this.name=s,Cr.prototype.hasOwnProperty("tree")||Object.defineProperty(Cr.prototype,"tree",{get(){return Ms(this)}}),this.parser=r,this.extension=[al.of(this),Cr.languageData.of((i,a,o)=>{let l=jS(i,a,o),c=l.type.prop(Bc);if(!c)return[];let u=i.facet(c),d=l.type.prop(BH);if(d){let h=l.resolve(a-l.from,o);for(let m of d)if(m.test(h,i)){let b=i.facet(m.facet);return m.type=="replace"?b:b.concat(u)}}return u})].concat(n)}isActiveAt(e,r,n=-1){return jS(e,r,n).type.prop(Bc)==this.data}findRegions(e){let r=e.facet(al);if(r?.data==this.data)return[{from:0,to:e.doc.length}];if(!r||!r.allowsNesting)return[];let n=[],s=(i,a)=>{if(i.prop(Bc)==this.data){n.push({from:a,to:a+i.length});return}let o=i.prop(hr.mounted);if(o){if(o.tree.prop(Bc)==this.data){if(o.overlay)for(let l of o.overlay)n.push({from:l.from+a,to:l.to+a});else n.push({from:a,to:a+i.length});return}else if(o.overlay){let l=n.length;if(s(o.tree,o.overlay[0].from+a),n.length>l)return}}for(let l=0;l<i.children.length;l++){let c=i.children[l];c instanceof rs&&s(c,i.positions[l]+a)}};return s(Ms(e),0),n}get allowsNesting(){return!0}}fo.setState=sr.define();function jS(t,e,r){let n=t.facet(al),s=Ms(t).topNode;if(!n||n.allowsNesting)for(let i=s;i;i=i.enter(e,r,_n.ExcludeBuffers))i.type.isTop&&(s=i);return s}class cy extends fo{constructor(e,r,n){super(e,r,[],n),this.parser=r}static define(e){let r=$H(e.languageData);return new cy(r,e.parser.configure({props:[Bc.add(n=>n.isTop?r:void 0)]}),e.name)}configure(e,r){return new cy(this.data,this.parser.configure(e),r||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ms(t){let e=t.field(fo.state,!1);return e?e.tree:rs.empty}class FH{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,r){let n=this.cursorPos-this.string.length;return e<n||r>=this.cursorPos?this.doc.sliceString(e,r):this.string.slice(e-n,r-n)}}let Hu=null;class Ip{constructor(e,r,n=[],s,i,a,o,l){this.parser=e,this.state=r,this.fragments=n,this.tree=s,this.treeLen=i,this.viewport=a,this.skipped=o,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,r,n){return new Ip(e,r,[],rs.empty,0,n,[],null)}startParse(){return this.parser.startParse(new FH(this.state.doc),this.fragments)}work(e,r){return r!=null&&r>=this.state.doc.length&&(r=void 0),this.tree!=rs.empty&&this.isDone(r??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var n;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),r!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>r)&&r<this.state.doc.length&&this.parse.stopAt(r);;){let s=this.parse.advance();if(s)if(this.fragments=this.withoutTempSkipped(ha.addTree(s,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(n=this.parse.stoppedAt)!==null&&n!==void 0?n:this.state.doc.length,this.tree=s,this.parse=null,this.treeLen<(r??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,r;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(r=this.parse.advance()););}),this.treeLen=e,this.tree=r,this.fragments=this.withoutTempSkipped(ha.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let r=Hu;Hu=this;try{return e()}finally{Hu=r}}withoutTempSkipped(e){for(let r;r=this.tempSkipped.pop();)e=$S(e,r.from,r.to);return e}changes(e,r){let{fragments:n,tree:s,treeLen:i,viewport:a,skipped:o}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,u,d,h)=>l.push({fromA:c,toA:u,fromB:d,toB:h})),n=ha.applyChanges(n,l),s=rs.empty,i=0,a={from:e.mapPos(a.from,-1),to:e.mapPos(a.to,1)},this.skipped.length){o=[];for(let c of this.skipped){let u=e.mapPos(c.from,1),d=e.mapPos(c.to,-1);u<d&&o.push({from:u,to:d})}}}return new Ip(this.parser,r,n,s,i,a,o,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let r=this.skipped.length;for(let n=0;n<this.skipped.length;n++){let{from:s,to:i}=this.skipped[n];s<e.to&&i>e.from&&(this.fragments=$S(this.fragments,s,i),this.skipped.splice(n--,1))}return this.skipped.length>=r?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,r){this.skipped.push({from:e,to:r})}static getSkippingParser(e){return new class extends xH{createParse(r,n,s){let i=s[0].from,a=s[s.length-1].to;return{parsedPos:i,advance(){let l=Hu;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=a,new rs(Ci.none,[],[],a-i)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let r=this.fragments;return this.treeLen>=e&&r.length&&r[0].from==0&&r[0].to>=e}static get(){return Hu}}function $S(t,e,r){return ha.applyChanges(t,[{fromA:e,toA:r,fromB:e,toB:r}])}class cu{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let r=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),r.viewport.to);return r.work(20,n)||r.takeTree(),new cu(r)}static init(e){let r=Math.min(3e3,e.doc.length),n=Ip.create(e.facet(al).parser,e,{from:0,to:r});return n.work(20,r)||n.takeTree(),new cu(n)}}fo.state=gs.define({create:cu.init,update(t,e){for(let r of e.effects)if(r.is(fo.setState))return r.value;return e.startState.facet(al)!=e.state.facet(al)?cu.init(e.state):t.apply(e)}});let vT=t=>{let e=setTimeout(()=>t(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(vT=t=>{let e=-1,r=setTimeout(()=>{e=requestIdleCallback(t,{timeout:400})},100);return()=>e<0?clearTimeout(r):cancelIdleCallback(e)});const ib=typeof navigator<"u"&&(!((sb=navigator.scheduling)===null||sb===void 0)&&sb.isInputPending)?()=>navigator.scheduling.isInputPending():null,WH=ms.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let r=this.view.state.field(fo.state).context;(r.updateViewport(e.view.viewport)||this.view.viewport.to>r.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(r)}scheduleWork(){if(this.working)return;let{state:e}=this.view,r=e.field(fo.state);(r.tree!=r.context.tree||!r.context.isDone(e.doc.length))&&(this.working=vT(this.work))}work(e){this.working=null;let r=Date.now();if(this.chunkEnd<r&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=r+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:n,viewport:{to:s}}=this.view,i=n.field(fo.state);if(i.tree==i.context.tree&&i.context.isDone(s+1e5))return;let a=Date.now()+Math.min(this.chunkBudget,100,e&&!ib?Math.max(25,e.timeRemaining()-5):1e9),o=i.context.treeLen<s&&n.doc.length>s+1e3,l=i.context.work(()=>ib&&ib()||Date.now()>a,s+(o?0:1e5));this.chunkBudget-=Date.now()-r,(l||this.chunkBudget<=0)&&(i.context.takeTree(),this.view.dispatch({effects:fo.setState.of(new cu(i.context))})),this.chunkBudget>0&&!(l&&!o)&&this.scheduleWork(),this.checkAsyncSchedule(i.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(r=>Oi(this.view.state,r)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),al=it.define({combine(t){return t.length?t[0]:null},enables:t=>[fo.state,WH,st.contentAttributes.compute([t],e=>{let r=e.facet(t);return r&&r.name?{"data-language":r.name}:{}})]});class Eoe{constructor(e,r=[]){this.language=e,this.support=r,this.extension=[e,r]}}class Ts{constructor(e,r,n,s,i,a=void 0){this.name=e,this.alias=r,this.extensions=n,this.filename=s,this.loadFunc=i,this.support=a,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(e=>this.support=e,e=>{throw this.loading=null,e}))}static of(e){let{load:r,support:n}=e;if(!r){if(!n)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");r=()=>Promise.resolve(n)}return new Ts(e.name,(e.alias||[]).concat(e.name).map(s=>s.toLowerCase()),e.extensions||[],e.filename,r,n)}static matchFilename(e,r){for(let s of e)if(s.filename&&s.filename.test(r))return s;let n=/\.([^.]+)$/.exec(r);if(n){for(let s of e)if(s.extensions.indexOf(n[1])>-1)return s}return null}static matchLanguageName(e,r,n=!0){r=r.toLowerCase();for(let s of e)if(s.alias.some(i=>i==r))return s;if(n)for(let s of e)for(let i of s.alias){let a=r.indexOf(i);if(a>-1&&(i.length>2||!/\w/.test(r[a-1])&&!/\w/.test(r[a+i.length])))return s}return null}}const HH=it.define(),vu=it.define({combine:t=>{if(!t.length)return" ";let e=t[0];if(!e||/\S/.test(e)||Array.from(e).some(r=>r!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(t[0]));return e}});function Np(t){let e=t.facet(vu);return e.charCodeAt(0)==9?t.tabSize*e.length:e.length}function Bd(t,e){let r="",n=t.tabSize,s=t.facet(vu)[0];if(s==" "){for(;e>=n;)r+=" ",e-=n;s=" "}for(let i=0;i<e;i++)r+=s;return r}function H_(t,e){t instanceof Cr&&(t=new Em(t));for(let n of t.state.facet(HH)){let s=n(t,e);if(s!==void 0)return s}let r=Ms(t.state);return r.length>=e?zH(t,r,e):null}class Em{constructor(e,r={}){this.state=e,this.options=r,this.unit=Np(e)}lineAt(e,r=1){let n=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:i}=this.options;return s!=null&&s>=n.from&&s<=n.to?i&&s==e?{text:"",from:e}:(r<0?s<e:s<=e)?{text:n.text.slice(s-n.from),from:s}:{text:n.text.slice(0,s-n.from),from:n.from}:n}textAfterPos(e,r=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:n,from:s}=this.lineAt(e,r);return n.slice(e-s,Math.min(n.length,e+100-s))}column(e,r=1){let{text:n,from:s}=this.lineAt(e,r),i=this.countColumn(n,e-s),a=this.options.overrideIndentation?this.options.overrideIndentation(s):-1;return a>-1&&(i+=a-this.countColumn(n,n.search(/\S|$/))),i}countColumn(e,r=e.length){return ym(e,this.state.tabSize,r)}lineIndent(e,r=1){let{text:n,from:s}=this.lineAt(e,r),i=this.options.overrideIndentation;if(i){let a=i(s);if(a>-1)return a}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const UH=new hr;function zH(t,e,r){let n=e.resolveStack(r),s=e.resolveInner(r,-1).resolve(r,0).enterUnfinishedNodesBefore(r);if(s!=n.node){let i=[];for(let a=s;a&&!(a.from<n.node.from||a.to>n.node.to||a.from==n.node.from&&a.type==n.node.type);a=a.parent)i.push(a);for(let a=i.length-1;a>=0;a--)n={node:i[a],next:n}}return yT(n,t,r)}function yT(t,e,r){for(let n=t;n;n=n.next){let s=GH(n.node);if(s)return s(U_.create(e,r,n))}return 0}function VH(t){return t.pos==t.options.simulateBreak&&t.options.simulateDoubleBreak}function GH(t){let e=t.type.prop(UH);if(e)return e;let r=t.firstChild,n;if(r&&(n=r.type.prop(hr.closedBy))){let s=t.lastChild,i=s&&n.indexOf(s.name)>-1;return a=>_T(a,!0,1,void 0,i&&!VH(a)?s.from:void 0)}return t.parent==null?qH:null}function qH(){return 0}class U_ extends Em{constructor(e,r,n){super(e.state,e.options),this.base=e,this.pos=r,this.context=n}get node(){return this.context.node}static create(e,r,n){return new U_(e,r,n)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let r=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(r.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(KH(n,e))break;r=this.state.doc.lineAt(n.from)}return this.lineIndent(r.from)}continue(){return yT(this.context.next,this.base,this.pos)}}function KH(t,e){for(let r=e;r;r=r.parent)if(t==r)return!0;return!1}function YH(t){let e=t.node,r=e.childAfter(e.from),n=e.lastChild;if(!r)return null;let s=t.options.simulateBreak,i=t.state.doc.lineAt(r.from),a=s==null||s<=i.from?i.to:Math.min(i.to,s);for(let o=r.to;;){let l=e.childAfter(o);if(!l||l==n)return null;if(!l.type.isSkipped){if(l.from>=a)return null;let c=/^ */.exec(i.text.slice(r.to-i.from))[0].length;return{from:r.from,to:r.to+c}}o=l.to}}function koe({closing:t,align:e=!0,units:r=1}){return n=>_T(n,e,r,t)}function _T(t,e,r,n,s){let i=t.textAfter,a=i.match(/^\s*/)[0].length,o=n&&i.slice(a,a+n.length)==n||s==t.pos+a,l=e?YH(t):null;return l?o?t.column(l.from):t.column(l.to):t.baseIndent+(o?0:t.unit*r)}const Poe=t=>t.baseIndent;function Toe({except:t,units:e=1}={}){return r=>{let n=t&&t.test(r.textAfter);return r.baseIndent+(n?0:e*r.unit)}}const XH=200;function JH(){return Cr.transactionFilter.of(t=>{if(!t.docChanged||!t.isUserEvent("input.type")&&!t.isUserEvent("input.complete"))return t;let e=t.startState.languageDataAt("indentOnInput",t.startState.selection.main.head);if(!e.length)return t;let r=t.newDoc,{head:n}=t.newSelection.main,s=r.lineAt(n);if(n>s.from+XH)return t;let i=r.sliceString(s.from,n);if(!e.some(c=>c.test(i)))return t;let{state:a}=t,o=-1,l=[];for(let{head:c}of a.selection.ranges){let u=a.doc.lineAt(c);if(u.from==o)continue;o=u.from;let d=H_(a,u.from);if(d==null)continue;let h=/^\s*/.exec(u.text)[0],m=Bd(a,d);h!=m&&l.push({from:u.from,to:u.from+h.length,insert:m})}return l.length?[t,{changes:l,sequential:!0}]:t})}const QH=it.define(),ZH=new hr;function Roe(t){let e=t.firstChild,r=t.lastChild;return e&&e.to<r.from?{from:e.to,to:r.type.isError?t.to:r.from}:null}function e6(t,e,r){let n=Ms(t);if(n.length<r)return null;let s=n.resolveStack(r,1),i=null;for(let a=s;a;a=a.next){let o=a.node;if(o.to<=r||o.from>r)continue;if(i&&o.from<e)break;let l=o.type.prop(ZH);if(l&&(o.to<n.length-50||n.length==t.doc.length||!t6(o))){let c=l(o,t);c&&c.from<=r&&c.from>=e&&c.to>r&&(i=c)}}return i}function t6(t){let e=t.lastChild;return e&&e.to==t.to&&e.type.isError}function BS(t,e,r){for(let n of t.facet(QH)){let s=n(t,e,r);if(s)return s}return e6(t,e,r)}function xT(t,e){let r=e.mapPos(t.from,1),n=e.mapPos(t.to,-1);return r>=n?void 0:{from:r,to:n}}const wT=sr.define({map:xT}),z_=sr.define({map:xT}),Lp=gs.define({create(){return lr.none},update(t,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((r,n)=>t=FS(t,r,n)),t=t.map(e.changes);for(let r of e.effects)if(r.is(wT)&&!r6(t,r.value.from,r.value.to)){let{preparePlaceholder:n}=e.state.facet(ST),s=n?lr.replace({widget:new i6(n(e.state,r.value))}):WS;t=t.update({add:[s.range(r.value.from,r.value.to)]})}else r.is(z_)&&(t=t.update({filter:(n,s)=>r.value.from!=n||r.value.to!=s,filterFrom:r.value.from,filterTo:r.value.to}));return e.selection&&(t=FS(t,e.selection.main.head)),t},provide:t=>st.decorations.from(t),toJSON(t,e){let r=[];return t.between(0,e.doc.length,(n,s)=>{r.push(n,s)}),r},fromJSON(t){if(!Array.isArray(t)||t.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let r=0;r<t.length;){let n=t[r++],s=t[r++];if(typeof n!="number"||typeof s!="number")throw new RangeError("Invalid JSON for fold state");e.push(WS.range(n,s))}return lr.set(e,!0)}});function FS(t,e,r=e){let n=!1;return t.between(e,r,(s,i)=>{s<r&&i>e&&(n=!0)}),n?t.update({filterFrom:e,filterTo:r,filter:(s,i)=>s>=r||i<=e}):t}function uy(t,e,r){var n;let s=null;return(n=t.field(Lp,!1))===null||n===void 0||n.between(e,r,(i,a)=>{(!s||s.from>i)&&(s={from:i,to:a})}),s}function r6(t,e,r){let n=!1;return t.between(e,e,(s,i)=>{s==e&&i==r&&(n=!0)}),n}const n6={placeholderDOM:null,preparePlaceholder:null,placeholderText:"â¦"},ST=it.define({combine(t){return uc(t,n6)}});function s6(t){return[Lp,l6]}function CT(t,e){let{state:r}=t,n=r.facet(ST),s=a=>{let o=t.lineBlockAt(t.posAtDOM(a.target)),l=uy(t.state,o.from,o.to);
47l&&t.dispatch({effects:z_.of(l)}),a.preventDefault()};if(n.placeholderDOM)return n.placeholderDOM(t,s,e);let i=document.createElement("span");return i.textContent=n.placeholderText,i.setAttribute("aria-label",r.phrase("folded code")),i.title=r.phrase("unfold"),i.className="cm-foldPlaceholder",i.onclick=s,i}const WS=lr.replace({widget:new class extends dl{toDOM(t){return CT(t,null)}}});class i6 extends dl{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return CT(e,this.value)}}const o6={openText:"â",closedText:"âº",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class ob extends ba{constructor(e,r){super(),this.config=e,this.open=r}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let r=document.createElement("span");return r.textContent=this.open?this.config.openText:this.config.closedText,r.title=e.state.phrase(this.open?"Fold line":"Unfold line"),r}}function a6(t={}){let e={...o6,...t},r=new ob(e,!0),n=new ob(e,!1),s=ms.fromClass(class{constructor(a){this.from=a.viewport.from,this.markers=this.buildMarkers(a)}update(a){(a.docChanged||a.viewportChanged||a.startState.facet(al)!=a.state.facet(al)||a.startState.field(Lp,!1)!=a.state.field(Lp,!1)||Ms(a.startState)!=Ms(a.state)||e.foldingChanged(a))&&(this.markers=this.buildMarkers(a.view))}buildMarkers(a){let o=new oc;for(let l of a.viewportLineBlocks){let c=uy(a.state,l.from,l.to)?n:BS(a.state,l.from,l.to)?r:null;c&&o.add(l.from,l.from,c)}return o.finish()}}),{domEventHandlers:i}=e;return[s,nH({class:"cm-foldGutter",markers(a){var o;return((o=a.plugin(s))===null||o===void 0?void 0:o.markers)||gr.empty},initialSpacer(){return new ob(e,!1)},domEventHandlers:{...i,click:(a,o,l)=>{if(i.click&&i.click(a,o,l))return!0;let c=uy(a.state,o.from,o.to);if(c)return a.dispatch({effects:z_.of(c)}),!0;let u=BS(a.state,o.from,o.to);return u?(a.dispatch({effects:wT.of(u)}),!0):!1}}}),s6()]}const l6=st.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class km{constructor(e,r){this.specs=e;let n;function s(o){let l=nl.newName();return(n||(n=Object.create(null)))["."+l]=o,l}const i=typeof r.all=="string"?r.all:r.all?s(r.all):void 0,a=r.scope;this.scope=a instanceof fo?o=>o.prop(Bc)==a.data:a?o=>o==a:void 0,this.style=bT(e.map(o=>({tag:o.tag,class:o.class||s(Object.assign({},o,{tag:null}))})),{all:i}).style,this.module=n?new nl(n):null,this.themeType=r.themeType}static define(e,r){return new km(e,r||{})}}const dy=it.define(),c6=it.define({combine(t){return t.length?[t[0]]:null}});function ab(t){let e=t.facet(dy);return e.length?e:t.facet(c6)}function u6(t,e){let r=[h6],n;return t instanceof km&&(t.module&&r.push(st.styleModule.of(t.module)),n=t.themeType),n?r.push(dy.computeN([st.darkTheme],s=>s.facet(st.darkTheme)==(n=="dark")?[t]:[])):r.push(dy.of(t)),r}class d6{constructor(e){this.markCache=Object.create(null),this.tree=Ms(e.state),this.decorations=this.buildDeco(e,ab(e.state)),this.decoratedTo=e.viewport.to}update(e){let r=Ms(e.state),n=ab(e.state),s=n!=ab(e.startState),{viewport:i}=e.view,a=e.changes.mapPos(this.decoratedTo,1);r.length<i.to&&!s&&r.type==this.tree.type&&a>=i.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=a):(r!=this.tree||e.viewportChanged||s)&&(this.tree=r,this.decorations=this.buildDeco(e.view,n),this.decoratedTo=i.to)}buildDeco(e,r){if(!r||!this.tree.length)return lr.none;let n=new oc;for(let{from:s,to:i}of e.visibleRanges)MH(this.tree,r,(a,o,l)=>{n.add(a,o,this.markCache[l]||(this.markCache[l]=lr.mark({class:l})))},s,i);return n.finish()}}const h6=ul.high(ms.fromClass(d6,{decorations:t=>t.decorations})),f6=st.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),AT=1e4,ET="()[]{}",kT=it.define({combine(t){return uc(t,{afterCursor:!0,brackets:ET,maxScanDistance:AT,renderMatch:g6})}}),p6=lr.mark({class:"cm-matchingBracket"}),m6=lr.mark({class:"cm-nonmatchingBracket"});function g6(t){let e=[],r=t.matched?p6:m6;return e.push(r.range(t.start.from,t.start.to)),t.end&&e.push(r.range(t.end.from,t.end.to)),e}const b6=gs.define({create(){return lr.none},update(t,e){if(!e.docChanged&&!e.selection)return t;let r=[],n=e.state.facet(kT);for(let s of e.state.selection.ranges){if(!s.empty)continue;let i=$o(e.state,s.head,-1,n)||s.head>
vendor: 12,150 bytes, line 47
470&&$o(e.state,s.head-1,1,n)||n.afterCursor&&($o(e.state,s.head,1,n)||s.head<e.state.doc.length&&$o(e.state,s.head+1,-1,n));i&&(r=r.concat(n.renderMatch(i,e.state)))}return lr.set(r,!0)},provide:t=>st.decorations.from(t)}),v6=[b6,f6];function y6(t={}){return[kT.of(t),v6]}const _6=new hr;function hy(t,e,r){let n=t.prop(e<0?hr.openedBy:hr.closedBy);if(n)return n;if(t.name.length==1){let s=r.indexOf(t.name);if(s>-1&&s%2==(e<0?1:0))return[r[s+e]]}return null}function fy(t){let e=t.type.prop(_6);return e?e(t.node):t}function $o(t,e,r,n={}){let s=n.maxScanDistance||AT,i=n.brackets||ET,a=Ms(t),o=a.resolveInner(e,r);for(let l=o;l;l=l.parent){let c=hy(l.type,r,i);if(c&&l.from<l.to){let u=fy(l);if(u&&(r>0?e>=u.from&&e<u.to:e>u.from&&e<=u.to))return x6(t,e,r,l,u,c,i)}}return w6(t,e,r,a,o.type,s,i)}function x6(t,e,r,n,s,i,a){let o=n.parent,l={from:s.from,to:s.to},c=0,u=o?.cursor();if(u&&(r<0?u.childBefore(n.from):u.childAfter(n.to)))do if(r<0?u.to<=n.from:u.from>=n.to){if(c==0&&i.indexOf(u.type.name)>-1&&u.from<u.to){let d=fy(u);return{start:l,end:d?{from:d.from,to:d.to}:void 0,matched:!0}}else if(hy(u.type,r,a))c++;else if(hy(u.type,-r,a)){if(c==0){let d=fy(u);return{start:l,end:d&&d.from<d.to?{from:d.from,to:d.to}:void 0,matched:!1}}c--}}while(r<0?u.prevSibling():u.nextSibling());return{start:l,matched:!1}}function w6(t,e,r,n,s,i,a){let o=r<0?t.sliceDoc(e-1,e):t.sliceDoc(e,e+1),l=a.indexOf(o);if(l<0||l%2==0!=r>0)return null;let c={from:r<0?e-1:e,to:r>0?e+1:e},u=t.doc.iterRange(e,r>0?t.doc.length:0),d=0;for(let h=0;!u.next().done&&h<=i;){let m=u.value;r<0&&(h+=m.length);let b=e+h*r;for(let g=r>0?0:m.length-1,p=r>0?m.length:-1;g!=p;g+=r){let y=a.indexOf(m[g]);if(!(y<0||n.resolveInner(b+g,1).type!=s))if(y%2==0==r>0)d++;else{if(d==1)return{start:c,end:{from:b+g,to:b+g+1},matched:y>>1==l>>1};d--}}r>0&&(h+=m.length)}return u.done?{start:c,matched:!1}:null}const S6=Object.create(null),HS=[Ci.none],US=[],zS=Object.create(null),C6=Object.create(null);for(let[t,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])C6[t]=A6(S6,e);function lb(t,e){US.indexOf(t)>-1||(US.push(t),console.warn(e))}function A6(t,e){let r=[];for(let o of e.split(" ")){let l=[];for(let c of o.split(".")){let u=t[c]||he[c];u?typeof u=="function"?l.length?l=l.map(u):lb(c,`Modifier ${c} used at start of tag`):l.length?lb(c,`Tag ${c} used as modifier`):l=Array.isArray(u)?u:[u]:lb(c,`Unknown highlighting tag ${c}`)}for(let c of l)r.push(c)}if(!r.length)return 0;let n=e.replace(/ /g,"_"),s=n+" "+r.map(o=>o.id),i=zS[s];if(i)return i.id;let a=zS[s]=Ci.define({id:HS.length,name:n,props:[LH({[n]:r})]});return HS.push(a),a.id}en.RTL,en.LTR;class PT{constructor(e,r,n,s){this.state=e,this.pos=r,this.explicit=n,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let r=Ms(this.state).resolveInner(this.pos,-1);for(;r&&e.indexOf(r.name)<0;)r=r.parent;return r?{from:r.from,to:this.pos,text:this.state.sliceDoc(r.from,this.pos),type:r.type}:null}matchBefore(e){let r=this.state.doc.lineAt(this.pos),n=Math.max(r.from,this.pos-250),s=r.text.slice(n-r.from,this.pos-r.from),i=s.search(TT(e,!1));return i<0?null:{from:n+i,to:this.pos,text:s.slice(i)}}get aborted(){return this.abortListeners==null}addEventListener(e,r,n){e=="abort"&&this.abortListeners&&(this.abortListeners.push(r),n&&n.onDocChange&&(this.abortOnDocChange=!0))}}function VS(t){let e=Object.keys(t).join(""),r=/\w/.test(e);return r&&(e=e.replace(/\w/g,"")),`[${r?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function E6(t){let e=Object.create(null),r=Object.create(null);for(let{label:s}of t){e[s[0]]=!0;for(let i=1;i<s.length;i++)r[s[i]]=!0}let n=VS(e)+VS(r)+"*$";return[new RegExp("^"+n),new RegExp(n)]}function k6(t){let e=t.map(s=>typeof s=="string"?{label:s}:s),[r,n]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:E6(e);return s=>{let i=s.matchBefore(n);return i||s.explicit?{from:i?i.from:s.pos,options:e,validFor:r}:null}}function Ioe(t,e){return r=>{for(let n=Ms(r.state).resolveInner(r.pos,-1);n;n=n.parent){if(t.indexOf(n.name)>-1)return null;if(n.type.isTop)break}return e(r)}}class GS{constructor(e,r,n,s){this.completion=e,this.source=r,this.match=n,this.score=s}}function Jl(t){return t.selection.main.from}function TT(t,e){var r;let{source:n}=t,s=e&&n[0]!="^",i=n[n.length-1]!="$";return!s&&!i?t:new RegExp(`${s?"^":""}(?:${n})${i?"$":""}`,(r=t.flags)!==null&&r!==void 0?r:t.ignoreCase?"i":"")}const V_=xa.define();function P6(t,e,r,n){let{main:s}=t.selection,i=r-s.from,a=n-s.from;return{...t.changeByRange(o=>{if(o!=s&&r!=n&&t.sliceDoc(o.from+i,o.from+a)!=t.sliceDoc(r,n))return{range:o};let l=t.toText(e);return{changes:{from:o.from+i,to:n==s.from?o.to:o.from+a,insert:l},range:ke.cursor(o.from+i+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const qS=new WeakMap;function T6(t){if(!Array.isArray(t))return t;let e=qS.get(t);return e||qS.set(t,e=k6(t)),e}const Dp=sr.define(),Fd=sr.define();class R6{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let r=0;r<e.length;){let n=lo(e,r),s=na(n);this.chars.push(n);let i=e.slice(r,r+s),a=i.toUpperCase();this.folded.push(lo(a==i?i.toLowerCase():a,0)),r+=s}this.astral=e.length!=this.chars.length}ret(e,r){return this.score=e,this.matched=r,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:r,folded:n,any:s,precise:i,byWord:a}=this;if(r.length==1){let v=lo(e,0),_=na(v),w=_==e.length?0:-100;if(v!=r[0])if(v==n[0])w+=-200;else return null;return this.ret(w,[0,_])}let o=e.indexOf(this.pattern);if(o==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=r.length,c=0;if(o<0){for(let v=0,_=Math.min(e.length,200);v<_&&c<l;){let w=lo(e,v);(w==r[c]||w==n[c])&&(s[c++]=v),v+=na(w)}if(c<l)return null}let u=0,d=0,h=!1,m=0,b=-1,g=-1,p=/[a-z]/.test(e),y=!0;for(let v=0,_=Math.min(e.length,200),w=0;v<_&&d<l;){let C=lo(e,v);o<0&&(u<l&&C==r[u]&&(i[u++]=v),m<l&&(C==r[m]||C==n[m]?(m==0&&(b=v),g=v+1,m++):m=0));let A,E=C<255?C>=48&&C<=57||C>=97&&C<=122?2:C>=65&&C<=90?1:0:(A=A_(C))!=A.toLowerCase()?1:A!=A.toUpperCase()?2:0;(!v||E==1&&p||w==0&&E!=0)&&(r[d]==C||n[d]==C&&(h=!0)?a[d++]=v:a.length&&(y=!1)),w=E,v+=na(C)}return d==l&&a[0]==0&&y?this.result(-100+(h?-200:0),a,e):m==l&&b==0?this.ret(-200-e.length+(g==e.length?0:-100),[0,g]):o>-1?this.ret(-700-e.length,[o,o+this.pattern.length]):m==l?this.ret(-900-e.length,[b,g]):d==l?this.result(-100+(h?-200:0)+-700+(y?0:-1100),a,e):r.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,r,n){let s=[],i=0;for(let a of r){let o=a+(this.astral?na(lo(n,a)):1);i&&s[i-1]==a?s[i-1]=o:(s[i++]=a,s[i++]=o)}return this.ret(e-n.length,s)}}class I6{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let r=e.slice(0,this.pattern.length),n=r==this.pattern?0:r.toLowerCase()==this.folded?-200:null;return n==null?null:(this.matched=[0,r.length],this.score=n+(e.length==this.pattern.length?0:-100),this)}}const ps=it.define({combine(t){return uc(t,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:N6,filterStrict:!1,compareCompletions:(e,r)=>(e.sortText||e.label).localeCompare(r.sortText||r.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,r)=>e&&r,closeOnBlur:(e,r)=>e&&r,icons:(e,r)=>e&&r,tooltipClass:(e,r)=>n=>KS(e(n),r(n)),optionClass:(e,r)=>n=>KS(e(n),r(n)),addToOptions:(e,r)=>e.concat(r),filterStrict:(e,r)=>e||r})}});function KS(t,e){return t?e?t+" "+e:t:e}function N6(t,e,r,n,s,i){let a=t.textDirection==en.RTL,o=a,l=!1,c="top",u,d,h=e.left-s.left,m=s.right-e.right,b=n.right-n.left,g=n.bottom-n.top;if(o&&h<Math.min(b,m)?o=!1:!o&&m<Math.min(b,h)&&(o=!0),b<=(o?h:m))u=Math.max(s.top,Math.min(r.top,s.bottom-g))-e.top,d=Math.min(400,o?h:m);else{l=!0,d=Math.min(400,(a?e.right:s.right-e.left)-30);let v=s.bottom-e.bottom;v>=g||v>e.top?u=r.bottom-e.top:(c="bottom",u=e.bottom-r.top)}let p=(e.bottom-e.top)/i.offsetHeight,y=(e.right-e.left)/i.offsetWidth;return{style:`${c}: ${u/p}px; max-width: ${d/y}px`,class:"cm-completionInfo-"+(l?a?"left-narrow":"right-narrow":o?"left":"right")}}function L6(t){let e=t.addToOptions.slice();return t.icons&&e.push({render(r){let n=document.createElement("div");return n.classList.add("cm-completionIcon"),r.type&&n.classList.add(...r.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),n.setAttribute("aria-hidden","true"),n},position:20}),e.push({render(r,n,s,i){let a=document.createElement("span");a.className="cm-completionLabel";let o=r.displayLabel||r.label,l=0;for(let c=0;c<i.length;){let u=i[c++],d=i[c++];u>l&&a.appendChild(document.createTextNode(o.slice(l,u)));let h=a.appendChild(document.createElement("span"));h.appendChild(document.createTextNode(o.slice(u,d))),h.className="cm-completionMatchedText",l=d}return l<o.length&&a.appendChild(document.createTextNode(o.slice(l))),a},position:50},{render(r){if(!r.detail)return null;let n=document.createElement("span");return n.className="cm-completionDetail",n.textContent=r.detail,n},position:80}),e.sort((r,n)=>r.position-n.position).map(r=>r.render)}function cb(t,e,r){if(t<=r)return{from:0,to:t};if(e<0&&(e=0),e<=t>>1){let s=Math.floor(e/r);return{from:s*r,to:(s+1)*r}}let n=Math.floor((t-e)/r);return{from:t-(n+1)*r,to:t-n*r}}class D6{constructor(e,r,n){this.view=e,this.stateField=r,this.applyCompletion=n,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let s=e.state.field(r),{options:i,selected:a}=s.open,o=e.state.facet(ps);this.optionContent=L6(o),this.optionClass=o.optionClass,this.tooltipClass=o.tooltipClass,this.range=cb(i.length,a,o.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(r).open;for(let u=l.target,d;u&&u!=this.dom;u=u.parentNode)if(u.nodeName=="LI"&&(d=/-(\d+)$/.exec(u.id))&&+d[1]<c.length){this.applyCompletion(e,c[+d[1]]),l.preventDefault();return}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(ps).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Fd.of(null)})}),this.showOptions(i,s.id)}mount(){this.updateSel()}showOptions(e,r){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,r,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var r;let n=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),n!=s){let{options:i,selected:a,disabled:o}=n.open;(!s.open||s.open.options!=i)&&(this.range=cb(i.length,a,e.state.facet(ps).maxRenderedOptions),this.showOptions(i,n.id)),this.updateSel(),o!=((r=s.open)===null||r===void 0?void 0:r.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!o)}}updateTooltipClass(e){let r=this.tooltipClass(e);if(r!=this.currentClass){for(let n of this.currentClass.split(" "))n&&this.dom.classList.remove(n);for(let n of r.split(" "))n&&this.dom.classList.add(n);this.currentClass=r}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),r=e.open;(r.selected>-1&&r.selected<this.range.from||r.selected>=this.range.to)&&(this.range=cb(r.options.length,r.selected,this.view.state.facet(ps).maxRenderedOptions),this.showOptions(r.options,e.id));let n=this.updateSelectedOption(r.selected);if(n){this.destroyInfo();
vendor: 4,857 bytes, line 47
47let{completion:s}=r.options[r.selected],{info:i}=s;if(!i)return;let a=typeof i=="string"?document.createTextNode(i):i(s);if(!a)return;"then"in a?a.then(o=>{o&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(o,s)}).catch(o=>Oi(this.view.state,o,"completion info")):(this.addInfoPane(a,s),n.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,r){this.destroyInfo();let n=this.info=document.createElement("div");if(n.className="cm-tooltip cm-completionInfo",n.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)n.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:i}=e;n.appendChild(s),this.infoDestroy=i||null}this.dom.appendChild(n),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let r=null;for(let n=this.list.firstChild,s=this.range.from;n;n=n.nextSibling,s++)n.nodeName!="LI"||!n.id?s--:s==e?n.hasAttribute("aria-selected")||(n.setAttribute("aria-selected","true"),r=n):n.hasAttribute("aria-selected")&&(n.removeAttribute("aria-selected"),n.removeAttribute("aria-describedby"));return r&&O6(this.list,r),r}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let r=this.dom.getBoundingClientRect(),n=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),i=this.space;if(!i){let a=this.dom.ownerDocument.documentElement;i={left:0,top:0,right:a.clientWidth,bottom:a.clientHeight}}return s.top>Math.min(i.bottom,r.bottom)-10||s.bottom<Math.max(i.top,r.top)+10?null:this.view.state.facet(ps).positionInfo(this.view,r,s,n,i,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,r,n){const s=document.createElement("ul");s.id=r,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions")),s.addEventListener("mousedown",a=>{a.target==s&&a.preventDefault()});let i=null;for(let a=n.from;a<n.to;a++){let{completion:o,match:l}=e[a],{section:c}=o;if(c){let h=typeof c=="string"?c:c.name;if(h!=i&&(a>n.from||n.from==0))if(i=h,typeof c!="string"&&c.header)s.appendChild(c.header(c));else{let m=s.appendChild(document.createElement("completion-section"));m.textContent=h}}const u=s.appendChild(document.createElement("li"));u.id=r+"-"+a,u.setAttribute("role","option");let d=this.optionClass(o);d&&(u.className=d);for(let h of this.optionContent){let m=h(o,this.view.state,this.view,l);m&&u.appendChild(m)}}return n.from&&s.classList.add("cm-completionListIncompleteTop"),n.to<e.length&&s.classList.add("cm-completionListIncompleteBottom"),s}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function M6(t,e){return r=>new D6(r,t,e)}function O6(t,e){let r=t.getBoundingClientRect(),n=e.getBoundingClientRect(),s=r.height/t.offsetHeight;n.top<r.top?t.scrollTop-=(r.top-n.top)/s:n.bottom>r.bottom&&(t.scrollTop+=(n.bottom-r.bottom)/s)}function YS(t){return(t.boost||0)*100+(t.apply?10:0)+(t.info?5:0)+(t.type?1:0)}function j6(t,e){let r=[],n=null,s=null,i=u=>{r.push(u);let{section:d}=u.completion;if(d){n||(n=[]);let h=typeof d=="string"?d:d.name;n.some(m=>m.name==h)||n.push(typeof d=="string"?{name:h}:d)}},a=e.facet(ps);for(let u of t)if(u.hasResult()){let d=u.result.getMatch;if(u.result.filter===!1)for(let h of u.result.options)i(new GS(h,u.source,d?d(h):[],1e9-r.length));else{let h=e.sliceDoc(u.from,u.to),m,b=a.filterStrict?new I6(h):new R6(h);for(let g of u.result.options)if(m=b.match(g.label)){let p=g.displayLabel?d?d(g,m.matched):[]:m.matched,y=m.score+(g.boost||0);if(i(new GS(g,u.source,p,y)),typeof g.section=="object"&&g.section.rank==="dynamic"){let{name:v}=g.section;s||(s=Object.create(null)),s[v]=Math.max(y,s[v]||-1e9)}}}}if(n){let u=Object.create(null),d=0,h=(m,b)=>(m.rank==="dynamic"&&b.rank==="dynamic"?s[b.name]-s[m.name]:0)||(typeof m.rank=="number"?m.rank:1e9)-(typeof b.rank=="number"?b.rank:1e9)||(m.name<b.name?-1:1);for(let m of n.sort(h))d-=1e5,u[m.name]=d;for(let m of r){let{section:b}=m.completion;b&&(m.score+=u[typeof b=="string"?b:b.name])}}let o=[],l=null,c=a.compareCompletions;for(let u of r.sort((d,h)=>h.score-d.score||c(d.completion,h.completion))){let d=u.completion;!l||l.label!=d.label||l.detail!=d.detail||l.type!=null&&d.type!=null&&l.type!=d.type||l.apply!=d.apply||l.boost!=d.boost?o.push(u):YS(u.completion)>YS(l)&&(o[o.length-1]=u),l=u.completion}return o}class Fc{constructor(e,r,n,s,i,a){this.options=e,this.attrs=r,this.tooltip=n,this.timestamp=s,this.selected=i,this.disabled=a}setSelected(e,r){return e==this.selected||e>=this.options.length?this:new Fc(this.options,XS(r,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,r,n,s,i,a){if(s&&!a&&e.some(c=>
vendor: 39,367 bytes, line 47
47c.isPending))return s.setDisabled();let o=j6(e,r);if(!o.length)return s&&e.some(c=>c.isPending)?s.setDisabled():null;let l=r.facet(ps).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let c=s.options[s.selected].completion;for(let u=0;u<o.length;u++)if(o[u].completion==c){l=u;break}}return new Fc(o,XS(n,l),{pos:e.reduce((c,u)=>u.hasResult()?Math.min(c,u.from):c,1e8),create:U6,above:i.aboveCursor},s?s.timestamp:Date.now(),l,!1)}map(e){return new Fc(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Fc(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Mp{constructor(e,r,n){this.active=e,this.id=r,this.open=n}static start(){return new Mp(W6,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:r}=e,n=r.facet(ps),i=(n.override||r.languageDataAt("autocomplete",Jl(r)).map(T6)).map(l=>(this.active.find(u=>u.source==l)||new Xi(l,this.active.some(u=>u.state!=0)?1:0)).update(e,n));i.length==this.active.length&&i.every((l,c)=>l==this.active[c])&&(i=this.active);let a=this.open,o=e.effects.some(l=>l.is(G_));a&&e.docChanged&&(a=a.map(e.changes)),e.selection||i.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!$6(i,this.active)||o?a=Fc.build(i,r,this.id,a,n,o):a&&a.disabled&&!i.some(l=>l.isPending)&&(a=null),!a&&i.every(l=>!l.isPending)&&i.some(l=>l.hasResult())&&(i=i.map(l=>l.hasResult()?new Xi(l.source,0):l));for(let l of e.effects)l.is(IT)&&(a=a&&a.setSelected(l.value,this.id));return i==this.active&&a==this.open?this:new Mp(i,this.id,a)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?B6:F6}}function $6(t,e){if(t==e)return!0;for(let r=0,n=0;;){for(;r<t.length&&!t[r].hasResult();)r++;for(;n<e.length&&!e[n].hasResult();)n++;let s=r==t.length,i=n==e.length;if(s||i)return s==i;if(t[r++].result!=e[n++].result)return!1}}const B6={"aria-autocomplete":"list"},F6={};function XS(t,e){let r={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":t};return e>-1&&(r["aria-activedescendant"]=t+"-"+e),r}const W6=[];function RT(t,e){if(t.isUserEvent("input.complete")){let n=t.annotation(V_);if(n&&e.activateOnCompletion(n))return 12}let r=t.isUserEvent("input.type");return r&&e.activateOnTyping?5:r?1:t.isUserEvent("delete.backward")?2:t.selection?8:t.docChanged?16:0}class Xi{constructor(e,r,n=!1){this.source=e,this.state=r,this.explicit=n}hasResult(){return!1}get isPending(){return this.state==1}update(e,r){let n=RT(e,r),s=this;(n&8||n&16&&this.touches(e))&&(s=new Xi(s.source,0)),n&4&&s.state==0&&(s=new Xi(this.source,1)),s=s.updateFor(e,n);for(let i of e.effects)if(i.is(Dp))s=new Xi(s.source,1,i.value);else if(i.is(Fd))s=new Xi(s.source,0);else if(i.is(G_))for(let a of i.value)a.source==s.source&&(s=a);return s}updateFor(e,r){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(Jl(e.state))}}class Xc extends Xi{constructor(e,r,n,s,i,a){super(e,3,r),this.limit=n,this.result=s,this.from=i,this.to=a}hasResult(){return!0}updateFor(e,r){var n;if(!(r&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let i=e.changes.mapPos(this.from),a=e.changes.mapPos(this.to,1),o=Jl(e.state);if(o>a||!s||r&2&&(Jl(e.startState)==this.from||o<this.limit))return new Xi(this.source,r&4?1:0);let l=e.changes.mapPos(this.limit);return H6(s.validFor,e.state,i,a)?new Xc(this.source,this.explicit,l,s,i,a):s.update&&(s=s.update(s,i,a,new PT(e.state,o,!1)))?new Xc(this.source,this.explicit,l,s,s.from,(n=s.to)!==null&&n!==void 0?n:Jl(e.state)):new Xi(this.source,1,this.explicit)}map(e){return e.empty?this:(this.result.map?this.result.map(this.result,e):this.result)?new Xc(this.source,this.explicit,e.mapPos(this.limit),this.result,e.mapPos(this.from),e.mapPos(this.to,1)):new Xi(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}}function H6(t,e,r,n){if(!t)return!1;let s=e.sliceDoc(r,n);return typeof t=="function"?t(s,r,n,e):TT(t,!0).test(s)}const G_=sr.define({map(t,e){return t.map(r=>r.map(e))}}),IT=sr.define(),_i=gs.define({create(){return Mp.start()},update(t,e){return t.update(e)},provide:t=>[$_.from(t,e=>e.tooltip),st.contentAttributes.from(t,e=>e.attrs)]});function q_(t,e){const r=e.completion.apply||e.completion.label;let n=t.state.field(_i).active.find(s=>s.source==e.source);return n instanceof Xc?(typeof r=="string"?t.dispatch({...P6(t.state,r,n.from,n.to),annotations:V_.of(e.completion)}):r(t,e.completion,n.from,n.to),!0):!1}const U6=M6(_i,q_);function bf(t,e="option"){return r=>{let n=r.state.field(_i,!1);if(!n||!n.open||n.open.disabled||Date.now()-n.open.timestamp<r.state.facet(ps).interactionDelay)return!1;let s=1,i;e=="page"&&(i=lT(r,n.open.tooltip))&&(s=Math.max(2,Math.floor(i.dom.offsetHeight/i.dom.querySelector("li").offsetHeight)-1));let{length:a}=n.open.options,o=n.open.selected>-1?n.open.selected+s*(t?1:-1):t?0:a-1;return o<0?o=e=="page"?0:a-1:o>=a&&(o=e=="page"?a-1:0),r.dispatch({effects:IT.of(o)}),!0}}const NT=t=>{let e=t.state.field(_i,!1);return t.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<t.state.facet(ps).interactionDelay?!1:q_(t,e.open.options[e.open.selected])},ub=t=>t.state.field(_i,!1)?(t.dispatch({effects:Dp.of(!0)}),!0):!1,z6=t=>{let e=t.state.field(_i,!1);return!e||!e.active.some(r=>r.state!=0)?!1:(t.dispatch({effects:Fd.of(null)}),!0)};class V6{constructor(e,r){this.active=e,this.context=r,this.time=Date.now(),this.updates=[],this.done=void 0}}const G6=50,q6=1e3,K6=ms.fromClass(class{constructor(t){this.view=t,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of t.state.field(_i).active)e.isPending&&this.startQuery(e)}update(t){let e=t.state.field(_i),r=t.state.facet(ps);if(!t.selectionSet&&!t.docChanged&&t.startState.field(_i)==e)return;let n=t.transactions.some(i=>{let a=RT(i,r);return a&8||(i.selection||i.docChanged)&&!(a&3)});for(let i=0;i<this.running.length;i++){let a=this.running[i];if(n||a.context.abortOnDocChange&&t.docChanged||a.updates.length+t.transactions.length>G6&&Date.now()-a.time>q6){for(let o of a.context.abortListeners)try{o()}catch(l){Oi(this.view.state,l)}a.context.abortListeners=null,this.running.splice(i--,1)}else a.updates.push(...t.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),t.transactions.some(i=>i.effects.some(a=>a.is(Dp)))&&(this.pendingStart=!0);let s=this.pendingStart?50:r.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(i=>i.isPending&&!this.running.some(a=>a.active.source==i.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let i of t.transactions)i.isUserEvent("input.type")?this.composing=2:this.composing==2&&i.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:t}=this.view,e=t.field(_i);for(let r of e.active)r.isPending&&!this.running.some(n=>n.active.source==r.source)&&this.startQuery(r);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ps).updateSyncTime))}startQuery(t){let{state:e}=this.view,r=Jl(e),n=new PT(e,r,t.explicit,this.view),s=new V6(t,n);this.running.push(s),Promise.resolve(t.source(n)).then(i=>{s.context.aborted||(s.done=i||null,this.scheduleAccept())},i=>{this.view.dispatch({effects:Fd.of(null)}),Oi(this.view.state,i)})}scheduleAccept(){this.running.every(t=>t.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ps).updateSyncTime))}accept(){var t;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],r=this.view.state.facet(ps),n=this.view.state.field(_i);for(let s=0;s<this.running.length;s++){let i=this.running[s];if(i.done===void 0)continue;if(this.running.splice(s--,1),i.done){let o=Jl(i.updates.length?i.updates[0].startState:this.view.state),l=Math.min(o,i.done.from+(i.active.explicit?0:1)),c=new Xc(i.active.source,i.active.explicit,l,i.done,i.done.from,(t=i.done.to)!==null&&t!==void 0?t:o);for(let u of i.updates)c=c.update(u,r);if(c.hasResult()){e.push(c);continue}}let a=n.active.find(o=>o.source==i.active.source);if(a&&a.isPending)if(i.done==null){let o=new Xi(i.active.source,0);for(let l of i.updates)o=o.update(l,r);o.isPending||e.push(o)}else this.startQuery(a)}(e.length||n.open&&n.open.disabled)&&this.view.dispatch({effects:G_.of(e)})}},{eventHandlers:{blur(t){let e=this.view.state.field(_i,!1);if(e&&e.tooltip&&this.view.state.facet(ps).closeOnBlur){let r=e.open&&lT(this.view,e.open.tooltip);(!r||!r.dom.contains(t.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Fd.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Dp.of(!1)}),20),this.composing=0}}}),Y6=typeof navigator=="object"&&/Win/.test(navigator.platform),X6=ul.highest(st.domEventHandlers({keydown(t,e){let r=e.state.field(_i,!1);if(!r||!r.open||r.open.disabled||r.open.selected<0||t.key.length>1||t.ctrlKey&&!(Y6&&t.altKey)||t.metaKey)return!1;let n=r.open.options[r.open.selected],s=r.active.find(a=>a.source==n.source),i=n.completion.commitCharacters||s.result.commitCharacters;return i&&i.indexOf(t.key)>-1&&q_(e,n),!1}})),LT=st.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'Æ'"}},".cm-completionIcon-class":{"&:after":{content:"'â'"}},".cm-completionIcon-interface":{"&:after":{content:"'â'"}},".cm-completionIcon-variable":{"&:after":{content:"'ð¥'"}},".cm-completionIcon-constant":{"&:after":{content:"'ð¶'"}},".cm-completionIcon-type":{"&:after":{content:"'ð¡'"}},".cm-completionIcon-enum":{"&:after":{content:"'âª'"}},".cm-completionIcon-property":{"&:after":{content:"'â¡'"}},".cm-completionIcon-keyword":{"&:after":{content:"'ðï¸'"}},".cm-completionIcon-namespace":{"&:after":{content:"'â¢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class J6{constructor(e,r,n,s){this.field=e,this.line=r,this.from=n,this.to=s}}class K_{constructor(e,r,n){this.field=e,this.from=r,this.to=n}map(e){let r=e.mapPos(this.from,-1,Hs.TrackDel),n=e.mapPos(this.to,1,Hs.TrackDel);return r==null||n==null?null:new K_(this.field,r,n)}}class Y_{constructor(e,r){this.lines=e,this.fieldPositions=r}instantiate(e,r){let n=[],s=[r],i=e.doc.lineAt(r),a=/^\s*/.exec(i.text)[0];for(let l of this.lines){if(n.length){let c=a,u=/^\t*/.exec(l)[0].length;for(let d=0;d<u;d++)c+=e.facet(vu);s.push(r+c.length-u),l=c+l.slice(u)}n.push(l),r+=l.length+1}let o=this.fieldPositions.map(l=>new K_(l.field,s[l.line]+l.from,s[l.line]+l.to));return{text:n,ranges:o}}static parse(e){let r=[],n=[],s=[],i;for(let a of e.split(/\r\n?|\n/)){for(;i=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(a);){let o=i[1]?+i[1]:null,l=i[2]||i[3]||"",c=-1,u=l.replace(/\\[{}]/g,d=>d[1]);for(let d=0;d<r.length;d++)(o!=null?r[d].seq==o:u&&r[d].name==u)&&(c=d);if(c<0){let d=0;for(;d<r.length&&(o==null||r[d].seq!=null&&r[d].seq<o);)d++;r.splice(d,0,{seq:o,name:u}),c=d;for(let h of s)h.field>=c&&h.field++}for(let d of s)if(d.line==n.length&&d.from>i.index){let h=i[2]?3+(i[1]||"").length:2;d.from-=h,d.to-=h}s.push(new J6(c,n.length,i.index,i.index+u.length)),a=a.slice(0,i.index)+l+a.slice(i.index+i[0].length)}a=a.replace(/\\([{}])/g,(o,l,c)=>{for(let u of s)u.line==n.length&&u.from>c&&(u.from--,u.to--);return l}),n.push(a)}return new Y_(n,s)}}let Q6=lr.widget({widget:new class extends dl{toDOM(){let t=document.createElement("span");return t.className="cm-snippetFieldPosition",t}ignoreEvent(){return!1}}}),Z6=lr.mark({class:"cm-snippetField"});class yu{constructor(e,r){this.ranges=e,this.active=r,this.deco=lr.set(e.map(n=>(n.from==n.to?Q6:Z6).range(n.from,n.to)),!0)}map(e){let r=[];for(let n of this.ranges){let s=n.map(e);if(!s)return null;r.push(s)}return new yu(r,this.active)}selectionInsideField(e){return e.ranges.every(r=>this.ranges.some(n=>n.field==this.active&&n.from<=r.from&&n.to>=r.to))}}const bh=sr.define({map(t,e){return t&&t.map(e)}}),eU=sr.define(),Wd=gs.define({create(){return null},update(t,e){for(let r of e.effects){if(r.is(bh))return r.value;if(r.is(eU)&&t)return new yu(t.ranges,r.value)}return t&&e.docChanged&&(t=t.map(e.changes)),t&&e.selection&&!t.selectionInsideField(e.selection)&&(t=null),t},provide:t=>st.decorations.from(t,e=>e?e.deco:lr.none)});function X_(t,e){return ke.create(t.filter(r=>r.field==e).map(r=>ke.range(r.from,r.to)))}function tU(t){let e=Y_.parse(t);return(r,n,s,i)=>{let{text:a,ranges:o}=e.instantiate(r.state,s),{main:l}=r.state.selection,c={changes:{from:s,to:i==l.from?l.to:i,insert:Mr.of(a)},scrollIntoView:!0,annotations:n?[V_.of(n),qn.userEvent.of("input.complete")]:void 0};if(o.length&&(c.selection=X_(o,0)),o.some(u=>u.field>0)){let u=new yu(o,0),d=c.effects=[bh.of(u)];r.state.field(Wd,!1)===void 0&&d.push(sr.appendConfig.of([Wd,oU,aU,LT]))}r.dispatch(r.state.update(c))}}function DT(t){return({state:e,dispatch:r})=>{let n=e.field(Wd,!1);if(!n||t<0&&n.active==0)return!1;let s=n.active+t,i=t>0&&!n.ranges.some(a=>a.field==s+t);return r(e.update({selection:X_(n.ranges,s),effects:bh.of(i?null:new yu(n.ranges,s)),scrollIntoView:!0})),!0}}const rU=({state:t,dispatch:e})=>t.field(Wd,!1)?(e(t.update({effects:bh.of(null)})),!0):!1,nU=DT(1),sU=DT(-1),iU=[{key:"Tab",run:nU,shift:sU},{key:"Escape",run:rU}],JS=it.define({combine(t){return t.length?t[0]:iU}}),oU=ul.highest(Am.compute([JS],t=>t.facet(JS)));function Noe(t,e){return{...e,apply:tU(t)}}const aU=st.domEventHandlers({mousedown(t,e){let r=e.state.field(Wd,!1),n;if(!r||(n=e.posAtCoords({x:t.clientX,y:t.clientY}))==null)return!1;let s=r.ranges.find(i=>i.from<=n&&i.to>=n);return!s||s.field==r.active?!1:(e.dispatch({selection:X_(r.ranges,s.field),effects:bh.of(r.ranges.some(i=>i.field>s.field)?new yu(r.ranges,s.field):null),scrollIntoView:!0}),!0)}}),Op={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Gl=sr.define({map(t,e){let r=e.mapPos(t,-1,Hs.TrackAfter);return r??void 0}}),J_=new class extends rl{};J_.startSide=1;J_.endSide=-1;const MT=gs.define({create(){return gr.empty},update(t,e){if(t=t.map(e.changes),e.selection){let r=e.state.doc.lineAt(e.selection.main.head);t=t.update({filter:n=>n>=r.from&&n<=r.to})}for(let r of e.effects)r.is(Gl)&&(t=t.update({add:[J_.range(r.value,r.value+1)]}));return t}});function lU(){return[hU,MT]}const db="()[]{}<>«»»«[]ï½ï½";function cU(t){for(let e=0;e<db.length;e+=2)if(db.charCodeAt(e)==t)return db.charAt(e+1);return A_(t<128?t:t+1)}function uU(t,e){return t.languageDataAt("closeBrackets",e)[0]||Op}const dU=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),hU=st.inputHandler.of((t,e,r,n)=>{if((dU?t.composing:t.compositionStarted)||t.state.readOnly)return!1;let s=t.state.selection.main;if(n.length>2||n.length==2&&na(lo(n,0))==1||e!=s.from||r!=s.to)return!1;let i=fU(t.state,n);return i?(t.dispatch(i),!0):!1});function fU(t,e){let r=uU(t,t.selection.main.head),n=r.brackets||Op.brackets;for(let s of n){let i=cU(lo(s,0));if(e==s)return i==s?gU(t,s,n.indexOf(s+s+s)>-1,r):pU(t,s,i,r.before||Op.before);if(e==i&&OT(t,t.selection.main.from))return mU(t,s,i)}return null}function OT(t,e){let r=!1;return t.field(MT).between(0,t.doc.length,n=>{n==e&&(r=!0)}),r}function Q_(t,e){let r=t.sliceString(e,e+2);return r.slice(0,na(lo(r,0)))}function pU(t,e,r,n){let s=null,i=t.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:r,from:a.to}],effects:Gl.of(a.to+e.length),range:ke.range(a.anchor+e.length,a.head+e.length)};let o=Q_(t.doc,a.head);return!o||/\s/.test(o)||n.indexOf(o)>-1?{changes:{insert:e+r,from:a.head},effects:Gl.of(a.head+e.length),range:ke.cursor(a.head+e.length)}:{range:s=a}});return s?null:t.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function mU(t,e,r){let n=null,s=t.changeByRange(i=>i.empty&&Q_(t.doc,i.head)==r?{changes:{from:i.head,to:i.head+r.length,insert:r},range:ke.cursor(i.head+r.length)}:n={range:i});return n?null:t.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function gU(t,e,r,n){let s=n.stringPrefixes||Op.stringPrefixes,i=null,a=t.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:e,from:o.to}],effects:Gl.of(o.to+e.length),range:ke.range(o.anchor+e.length,o.head+e.length)};let l=o.head,c=Q_(t.doc,l),u;if(c==e){if(QS(t,l))return{changes:{insert:e+e,from:l},effects:Gl.of(l+e.length),range:ke.cursor(l+e.length)};if(OT(t,l)){let h=r&&t.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+h.length,insert:h},range:ke.cursor(l+h.length)}}}else{if(r&&t.sliceDoc(l-2*e.length,l)==e+e&&(u=ZS(t,l-2*e.length,s))>-1&&QS(t,u))return{changes:{insert:e+e+e+e,from:l},effects:Gl.of(l+e.length),range:ke.cursor(l+e.length)};if(t.charCategorizer(l)(c)!=Kn.Word&&ZS(t,l,s)>-1&&!bU(t,l,e,s))return{changes:{insert:e+e,from:l},effects:Gl.of(l+e.length),range:ke.cursor(l+e.length)}}return{range:i=o}});return i?null:t.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function QS(t,e){let r=Ms(t).resolveInner(e+1);return r.parent&&r.from==e}function bU(t,e,r,n){let s=Ms(t).resolveInner(e,-1),i=n.reduce((a,o)=>Math.max(a,o.length),0);for(let a=0;a<5;a++){let o=t.sliceDoc(s.from,Math.min(s.to,s.from+r.length+i)),l=o.indexOf(r);if(!l||l>-1&&n.indexOf(o.slice(0,l))>-1){let u=s.firstChild;for(;u&&u.from==s.from&&u.to-u.from>r.length+l;){if(t.sliceDoc(u.to-r.length,u.to)==r)return!1;u=u.firstChild}return!0}let c=s.to==e&&s.parent;if(!c)break;s=c}return!1}function ZS(t,e,r){let n=t.charCategorizer(e);if(n(t.sliceDoc(e-1,e))!=Kn.Word)return e;for(let s of r){let i=e-s.length;if(t.sliceDoc(i,e)==s&&n(t.sliceDoc(i-1,i))!=Kn.Word)return i}return-1}function vU(t={}){return[X6,_i,ps.of(t),K6,_U,LT]}const yU=[{key:"Ctrl-Space",run:ub},{mac:"Alt-`",run:ub},{mac:"Alt-i",run:ub},{key:"Escape",run:z6},{key:"ArrowDown",run:bf(!0)},{key:"ArrowUp",run:bf(!1)},{key:"PageDown",run:bf(!0,"page")},{key:"PageUp",run:bf(!1,"page")},{key:"Enter",run:NT}],_U=ul.highest(Am.computeN([ps],t=>t.facet(ps).defaultKeymap?[yU]:[])),xU=t=>{let{state:e}=t,r=e.doc.lineAt(e.selection.main.from),n=e0(t.state,r.from);return n.line?wU(t):n.block?CU(t):!1};function Z_(t,e){return({state:r,dispatch:n})=>{if(r.readOnly)return!1;let s=t(e,r);return s?(n(r.update(s)),!0):!1}}const wU=Z_(kU,0),SU=Z_(jT,0),CU=Z_((t,e)=>jT(t,e,EU(e)),0);function e0(t,e){let r=t.languageDataAt("commentTokens",e,1);return r.length?r[0]:{}}const Uu=50;function AU(t,{open:e,close:r},n,s){let i=t.sliceDoc(n-Uu,n),a=t.sliceDoc(s,s+Uu),o=/\s*$/.exec(i)[0].length,l=/^\s*/.exec(a)[0].length,c=i.length-o;if(i.slice(c-e.length,c)==e&&a.slice(l,l+r.length)==r)return{open:{pos:n-o,margin:o&&1},close:{pos:s+l,margin:l&&1}};let u,d;s-n<=2*Uu?u=d=t.sliceDoc(n,s):(u=t.sliceDoc(n,n+Uu),d=t.sliceDoc(s-Uu,s));let h=/^\s*/.exec(u)[0].length,m=/\s*$/.exec(d)[0].length,b=d.length-m-r.length;return u.slice(h,h+e.length)==e&&d.slice(b,b+r.length)==r?{open:{pos:n+h+e.length,margin:/\s/.test(u.charAt(h+e.length))?1:0},close:{pos:s-m-r.length,margin:/\s/.test(d.charAt(b-1))?1:0}}:null}function EU(t){let e=[];for(let r of t.selection.ranges){let n=t.doc.lineAt(r.from),s=r.to<=n.to?n:t.doc.lineAt(r.to);s.from>n.from&&s.from==r.to&&(s=r.to==n.to+1?n:t.doc.lineAt(r.to-1));let i=e.length-1;i>=0&&e[i].to>n.from?e[i].to=s.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:s.to})}return e}function jT(t,e,r=e.selection.ranges){let n=r.map(i=>e0(e,i.from).block);if(!n.every(i=>i))return null;let s=r.map((i,a)=>AU(e,n[a],i.from,i.to));if(t!=2&&!s.every(i=>i))return{changes:e.changes(r.map((i,a)=>s[a]?[]:[{from:i.from,insert:n[a].open+" "},{from:i.to,insert:" "+n[a].close}]))};if(t!=1&&s.some(i=>i)){let i=[];for(let a=0,o;a<s.length;a++)if(o=s[a]){let l=n[a],{open:c,close:u}=o;i.push({from:c.pos-l.open.length,to:c.pos+c.margin},{from:u.pos-u.margin,to:u.pos+l.close.length})}return{changes:i}}return null}function kU(t,e,r=e.selection.ranges){let n=[],s=-1;for(let{from:i,to:a}of r){let o=n.length,l=1e9,c=e0(e,i).line;if(c){for(let u=i;u<=a;){let d=e.doc.lineAt(u);if(d.from>s&&(i==a||a>d.from)){s=d.from;let h=/^\s*/.exec(d.text)[0].length,m=h==d.length,b=d.text.slice(h,h+c.length)==c?h:-1;h<d.text.length&&h<l&&(l=h),n.push({line:d,comment:b,token:c,indent:h,empty:m,single:!1})}u=d.to+1}if(l<1e9)for(let u=o;u<n.length;u++)n[u].indent<n[u].line.text.length&&(n[u].indent=l);n.length==o+1&&(n[o].single=!0)}}if(t!=2&&n.some(i=>i.comment<0&&(!i.empty||i.single))){let i=[];for(let{line:o,token:l,indent:c,empty:u,single:d}of n)(d||!u)&&i.push({from:o.from+c,insert:l+" "});let a=e.changes(i);return{changes:a,selection:e.selection.map(a,1)}}else if(t!=1&&n.some(i=>i.comment>=0)){let i=[];for(let{line:a,comment:o,token:l}of n)if(o>=0){let c=a.from+o,u=c+l.length;a.text[u-a.from]==" "&&u++,i.push({from:c,to:u})}return{changes:i}}return null}const py=xa.define(),PU=xa.define(),TU=it.define(),$T=it.define({combine(t){return uc(t,{minDepth:100,newGroupDelay:500,joinToEvent:(e,r)=>r},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,r)=>(n,s)=>e(n,s)||r(n,s)})}}),BT=gs.define({create(){return Bo.empty},update(t,e){let r=e.state.facet($T),n=e.annotation(py);if(n){let l=wi.fromTransaction(e,n.selection),c=n.side,u=c==0?t.undone:t.done;return l?u=jp(u,u.length,r.minDepth,l):u=HT(u,e.startState.selection),new Bo(c==0?n.rest:u,c==0?u:n.rest)}let s=e.annotation(PU);if((s=="full"||s=="before")&&(t=t.isolate()),e.annotation(qn.addToHistory)===!1)return e.changes.empty?t:t.addMapping(e.changes.desc);let i=wi.fromTransaction(e),a=e.annotation(qn.time),o=e.annotation(qn.userEvent);return i?t=t.addChanges(i,a,o,r,e):e.selection&&(t=t.addSelection(e.startState.selection,a,o,r.newGroupDelay)),(s=="full"||s=="after")&&(t=t.isolate()),t},toJSON(t){return{done:t.done.map(e=>e.toJSON()),undone:t.undone.map(e=>e.toJSON())}},fromJSON(t){return new Bo(t.done.map(wi.fromJSON),t.undone.map(wi.fromJSON))}});function RU(t={}){return[BT,$T.of(t),st.domEventHandlers({beforeinput(e,r){let n=e.inputType=="historyUndo"?FT:e.inputType=="historyRedo"?my:null;return n?(e.preventDefault(),n(r)):!1}})]}function Pm(t,e){return function({state:r,dispatch:n}){if(!e&&r.readOnly)return!1;let s=r.field(BT,!1);if(!s)return!1;let i=s.pop(t,r,e);return i?(n(i),!0):!1}}const FT=Pm(0,!1),my=Pm(1,!1),IU=Pm(0,!0),NU=Pm(1,!0);class wi{constructor(e,r,n,s,i){this.changes=e,this.effects=r,this.mapped=n,this.startSelection=s,this.selectionsAfter=i}setSelAfter(e){return new wi(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,r,n;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(r=this.mapped)===null||r===void 0?void 0:r.toJSON(),startSelection:(n=this.startSelection)===null||n===void 0?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new wi(e.changes&&es.fromJSON(e.changes),[],e.mapped&&Wo.fromJSON(e.mapped),e.startSelection&&ke.fromJSON(e.startSelection),e.selectionsAfter.map(ke.fromJSON))}static fromTransaction(e,r){let n=Ji;for(let s of e.startState.facet(TU)){let i=s(e);i.length&&(n=n.concat(i))}return!n.length&&e.changes.empty?null:new wi(e.changes.invert(e.startState.doc),n,void 0,r||e.startState.selection,Ji)}static selection(e){return new wi(void 0,Ji,void 0,void 0,e)}}function jp(t,e,r,n){let s=e+1>r+20?e-r-1:0,i=t.slice(s,e);return i.push(n),i}function LU(t,e){let r=[],n=!1;return t.iterChangedRanges((s,i)=>r.push(s,i)),e.iterChangedRanges((s,i,a,o)=>{for(let l=0;l<r.length;){let c=r[l++],u=r[l++];o>=c&&a<=u&&(n=!0)}}),n}function DU(t,e){return t.ranges.length==e.ranges.length&&t.ranges.filter((r,n)=>r.empty!=e.ranges[n].empty).length===0}function WT(t,e){return t.length?e.length?t.concat(e):t:e}const Ji=[],MU=200;function HT(t,e){if(t.length){let r=t[t.length-1],n=r.selectionsAfter.slice(Math.max(0,r.selectionsAfter.length-MU));return n.length&&n[n.length-1].eq(e)?t:(n.push(e),jp(t,t.length-1,1e9,r.setSelAfter(n)))}else return[wi.selection([e])]}function OU(t){let e=t[t.length-1],r=t.slice();return r[t.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),r}function hb(t,e){if(!t.length)return t;let r=t.length,n=Ji;for(;r;){let s=jU(t[r-1],e,n);if(s.changes&&!s.changes.empty||s.effects.length){let i=t.slice(0,r);return i[r-1]=s,i}else e=s.mapped,r--,n=s.selectionsAfter}return n.length?[wi.selection(n)]:Ji}function jU(t,e,r){let n=WT(t.selectionsAfter.length?t.selectionsAfter.map(o=>o.map(e)):Ji,r);if(!t.changes)return wi.selection(n);let s=t.changes.map(e),i=e.mapDesc(t.changes,!0),a=t.mapped?t.mapped.composeDesc(i):i;return new wi(s,sr.mapEffects(t.effects,e),a,t.startSelection.map(i),n)}const $U=/^(input\.type|delete)($|\.)/;class Bo{constructor(e,r,n=0,s=void 0){this.done=e,this.undone=r,this.prevTime=n,this.prevUserEvent=s}isolate(){return this.prevTime?new Bo(this.done,this.undone):this}addChanges(e,r,n,s,i){let a=this.done,o=a[a.length-1];return o&&o.changes&&!o.changes.empty&&e.changes&&(!n||$U.test(n))&&(!o.selectionsAfter.length&&r-this.prevTime<s.newGroupDelay&&s.joinToEvent(i,LU(o.changes,e.changes))||n=="input.type.compose")?a=jp(a,a.length-1,s.minDepth,new wi(e.changes.compose(o.changes),WT(sr.mapEffects(e.effects,o.changes),o.effects),o.mapped,o.startSelection,Ji)):a=jp(a,a.length,s.minDepth,e),new Bo(a,Ji,r,n)}addSelection(e,r,n,s){let i=this.done.length?this.done[this.done.length-1].selectionsAfter:Ji;return i.length>0&&r-this.prevTime<s&&n==this.prevUserEvent&&n&&/^select($|\.)/.test(n)&&DU(i[i.length-1],e)?this:new Bo(HT(this.done,e),this.undone,r,n)}addMapping(e){return new Bo(hb(this.done,e),hb(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,r,n){let s=e==0?this.done:this.undone;if(s.length==0)return null;let i=s[s.length-1],a=i.selectionsAfter[0]||r.selection;if(n&&i.selectionsAfter.length)return r.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:py.of({side:e,rest:OU(s),selection:a}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(i.changes){let o=s.length==1?Ji:s.slice(0,s.length-1);return i.mapped&&(o=hb(o,i.mapped)),r.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:py.of({side:e,rest:o,selection:a}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}}Bo.empty=new Bo(Ji,Ji);const BU=[{key:"Mod-z",run:FT,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:my,preventDefault:!0},{linux:"Ctrl-Shift-z",run:my,preventDefault:!0},{key:"Mod-u",run:IU,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:NU,preventDefault:!0}];function _u(t,e){return ke.create(t.ranges.map(e),t.mainIndex)}function vo(t,e){return t.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function yo({state:t,dispatch:e},r){let n=_u(t.selection,r);return n.eq(t.selection,!0)?!1:(e(vo(t,n)),!0)}function Tm(t,e){return ke.cursor(e?t.to:t.from)}function UT(t,e){return yo(t,r=>r.empty?t.moveByChar(r,e):Tm(r,e))}function Vs(t){return t.textDirectionAt(t.state.selection.main.head)==en.LTR}const zT=t=>UT(t,!Vs(t)),VT=t=>UT(t,Vs(t));function GT(t,e){return yo(t,r=>r.empty?t.moveByGroup(r,e):Tm(r,e))}const FU=t=>GT(t,!Vs(t)),WU=t=>GT(t,Vs(t));function HU(t,e,r){if(e.type.prop(r))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(t.sliceDoc(e.from,e.to)))||e.firstChild}function Rm(t,e,r){let n=Ms(t).resolveInner(e.head),s=r?hr.closedBy:hr.openedBy;for(let l=e.head;;){let c=r?n.childAfter(l):n.childBefore(l);if(!c)break;HU(t,c,s)?n=c:l=r?c.to:c.from}let i=n.type.prop(s),a,o;return i&&(a=r?$o(t,n.from,1):$o(t,n.to,-1))&&a.matched?o=r?a.end.to:a.end.from:o=r?n.to:n.from,ke.cursor(o,r?-1:1)}const UU=t=>yo(t,e=>Rm(t.state,e,!Vs(t))),zU=t=>yo(t,e=>Rm(t.state,e,Vs(t)));function qT(t,e){return yo(t,r=>{if(!r.empty)return Tm(r,e);let n=t.moveVertically(r,e);return n.head!=r.head?n:t.moveToLineBoundary(r,e)})}const KT=t=>qT(t,!1),YT=t=>qT(t,!0);function XT(t){let e=t.scrollDOM.clientHeight<t.scrollDOM.scrollHeight-2,r=0,n=0,s;if(e){for(let i of t.state.facet(st.scrollMargins)){let a=i(t);a?.top&&(r=Math.max(a?.top,r)),a?.bottom&&(n=Math.max(a?.bottom,n))}s=t.scrollDOM.clientHeight-r-n}else s=(t.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:r,marginBottom:n,selfScroll:e,height:Math.max(t.defaultLineHeight,s-5)}}function JT(t,e){let r=XT(t),{state:n}=t,s=_u(n.selection,a=>a.empty?t.moveVertically(a,e,r.height):Tm(a,e));if(s.eq(n.selection))return!1;let i;if(r.selfScroll){let a=t.coordsAtPos(n.selection.main.head),o=t.scrollDOM.getBoundingClientRect(),l=o.top+r.marginTop,c=o.bottom-r.marginBottom;a&&a.top>l&&a.bottom<c&&(i=st.scrollIntoView(s.main.head,{y:"start",yMargin:a.top-l}))}return t.dispatch(vo(n,s),{effects:i}),!0}const eC=t=>JT(t,!1),gy=t=>JT(t,!0);function hl(t,e,r){let n=t.lineBlockAt(e.head),s=t.moveToLineBoundary(e,r);if(s.head==e.head&&s.head!=(r?n.to:n.from)&&(s=t.moveToLineBoundary(e,r,!1)),!r&&s.head==n.from&&n.length){let i=/^\s*/.exec(t.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;i&&e.head!=n.from+i&&(s=ke.cursor(n.from+i))}return s}const VU=t=>yo(t,e=>hl(t,e,!0)),GU=t=>yo(t,e=>hl(t,e,!1)),qU=t=>yo(t,e=>hl(t,e,!Vs(t))),KU=t=>yo(t,e=>hl(t,e,Vs(t))),YU=t=>yo(t,e=>ke.cursor(t.lineBlockAt(e.head).from,1)),XU=t=>yo(t,e=>ke.cursor(t.lineBlockAt(e.head).to,-1));function JU(t,e,r){let n=!1,s=_u(t.selection,i=>{let a=$o(t,i.head,-1)||$o(t,i.head,1)||i.head>0&&$o(t,i.head-1,1)||i.head<t.doc.length&&$o(t,i.head+1,-1);if(!a||!a.end)return i;n=!0;let o=a.start.from==i.head?a.end.to:a.end.from;return ke.cursor(o)});return n?(e(vo(t,s)),!0):!1}const QU=({state:t,dispatch:e})=>JU(t,e);function to(t,e){let r=_u(t.state.selection,n=>{let s=e(n);return ke.range(n.anchor,s.head,s.goalColumn,s.bidiLevel||void 0)});return r.eq(t.state.selection)?!1:(t.dispatch(vo(t.state,r)),!0)}function QT(t,e){return to(t,r=>t.moveByChar(r,e))}const ZT=t=>QT(t,!Vs(t)),eR=t=>QT(t,Vs(t));function tR(t,e){return to(t,r=>t.moveByGroup(r,e))}const ZU=t=>tR(t,!Vs(t)),e8=t=>tR(t,Vs(t)),t8=t=>to(t,e=>Rm(t.state,e,!Vs(t))),r8=t=>to(t,e=>Rm(t.state,e,Vs(t)));function rR(t,e){return to(t,r=>t.moveVertically(r,e))}const nR=t=>rR(t,!1),sR=t=>rR(t,!0);function iR(t,e){return to(t,r=>t.moveVertically(r,e,XT(t).height))}const tC=t=>iR(t,!1),rC=t=>iR(t,!0),n8=t=>to(t,e=>hl(t,e,!0)),s8=t=>to(t,e=>hl(t,e,!1)),i8=t=>to(t,e=>hl(t,e,!Vs(t))),o8=t=>to(t,e=>hl(t,e,Vs(t))),a8=t=>to(t,e=>ke.cursor(t.lineBlockAt(e.head).from)),l8=t=>to(t,e=>ke.cursor(t.lineBlockAt(e.head).to)),nC=({state:t,dispatch:e})=>(e(vo(t,{anchor:0})),!0),sC=({state:t,dispatch:e})=>(e(vo(t,{anchor:t.doc.length})),!0),iC=({state:t,dispatch:e})=>(e(vo(t,{anchor:t.selection.main.anchor,head:0})),!0),oC=({state:t,dispatch:e})=>(e(vo(t,{anchor:t.selection.main.anchor,head:t.doc.length})),!0),c8=({state:t,dispatch:e})=>(e(t.update({selection:{anchor:0,head:t.doc.length},userEvent:"select"})),!0),u8=({state:t,dispatch:e})=>{let r=Im(t).map(({from:n,to:s})=>ke.range(n,Math.min(s+1,t.doc.length)));return e(t.update({selection:ke.create(r),userEvent:"select"})),!0},d8=({state:t,dispatch:e})=>{let r=_u(t.selection,n=>{let s=Ms(t),i=s.resolveStack(n.from,1);if(n.empty){let a=s.resolveStack(n.from,-1);a.node.from>=i.node.from&&a.node.to<=i.node.to&&(i=a)}for(let a=i;a;a=a.next){let{node:o}=a;if((o.from<n.from&&o.to>=n.to||o.to>n.to&&o.from<=n.from)&&a.next)return ke.range(o.to,o.from)}return n});return r.eq(t.selection)?!1:(e(vo(t,r)),!0)};function oR(t,e){let{state:r}=t,n=r.selection,s=r.selection.ranges.slice();for(let i of r.selection.ranges){let a=r.doc.lineAt(i.head);if(e?a.to<t.state.doc.length:a.from>0)for(let o=i;;){let l=t.moveVertically(o,e);if(l.head<a.from||l.head>a.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==o.head)break;o=l}}}return s.length==n.ranges.length?!1:(t.dispatch(vo(r,ke.create(s,s.length-1))),!0)}const h8=t=>oR(t,!1),f8=t=>oR(t,!0),p8=({state:t,dispatch:e})=>{let r=t.selection,n=null;return r.ranges.length>1?n=ke.create([r.main]):r.main.empty||(n=ke.create([ke.cursor(r.main.head)])),n?(e(vo(t,n)),!0):!1};function vh(t,e){if(t.state.readOnly)return!1;let r="delete.selection",{state:n}=t,s=n.changeByRange(i=>{let{from:a,to:o}=i;if(a==o){let l=e(i);l<a?(r="delete.backward",l=vf(t,l,!1)):l>a&&(r="delete.forward",l=vf(t,l,!0)),a=Math.min(a,l),o=Math.max(o,l)}else a=vf(t,a,!1),o=vf(t,o,!0);return a==o?{range:i}:{changes:{from:a,to:o},range:ke.cursor(a,a<i.head?-1:1)}});return s.changes.empty?!1:(t.dispatch(n.update(s,{scrollIntoView:!0,userEvent:r,effects:r=="delete.selection"?st.announce.of(n.phrase("Selection deleted")):void 0})),!0)}function vf(t,e,r){if(t instanceof st)for(let n of t.state.facet(st.atomicRanges).map(s=>s(t)))n.between(e,e,(s,i)=>{s<e&&i>e&&(e=r?i:s)});return e}const aR=(t,e,r)=>vh(t,n=>{let s=n.from,{state:i}=t,a=i.doc.lineAt(s),o,l;if(r&&!e&&s>a.from&&s<a.from+200&&!/[^ \t]/.test(o=a.text.slice(0,s-a.from))){if(o[o.length-1]==" ")return s-1;let c=ym(o,i.tabSize),u=c%Np(i)||Np(i);for(let d=0;d<u&&o[o.length-1-d]==" ";d++)s--;l=s}else l=ts(a.text,s-a.from,e,e)+a.from,l==s&&a.number!=(e?i.doc.lines:1)?l+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(a.text.slice(l-a.from,s-a.from))&&(l=ts(a.text,l-a.from,!1,!1)+a.from);return l}),by=t=>aR(t,!1,!0),lR=t=>aR(t,!0,!1),cR=(t,e)=>vh(t,r=>{let n=r.head,{state:s}=t,i=s.doc.lineAt(n),a=s.charCategorizer(n);for(let o=null;;){if(n==(e?i.to:i.from)){n==r.head&&i.number!=(e?s.doc.lines:1)&&(n+=e?1:-1);break}let l=ts(i.text,n-i.from,e)+i.from,c=i.text.slice(Math.min(n,l)-i.from,Math.max(n,l)-i.from),u=a(c);if(o!=null&&u!=o)break;(c!=" "||n!=r.head)&&(o=u),n=l}return n}),uR=t=>cR(t,!1),m8=t=>cR(t,!0),g8=t=>vh(t,e=>{let r=t.lineBlockAt(e.head).to;return e.head<r?r:Math.min(t.state.doc.length,e.head+1)}),b8=t=>vh(t,e=>{let r=t.moveToLineBoundary(e,!1).head;return e.head>r?r:Math.max(0,e.head-1)}),v8=t=>vh(t,e=>{let r=t.moveToLineBoundary(e,!0).head;return e.head<r?r:Math.min(t.state.doc.length,e.head+1)}),y8=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>({changes:{from:n.from,to:n.to,insert:Mr.of(["",""])},range:ke.cursor(n.from)}));return e(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0},_8=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>{if(!n.empty||n.from==0||n.from==t.doc.length)return{range:n};let s=n.from,i=t.doc.lineAt(s),a=s==i.from?s-1:ts(i.text,s-i.from,!1)+i.from,o=s==i.to?s+1:ts(i.text,s-i.from,!0)+i.from;return{changes:{from:a,to:o,insert:t.doc.slice(s,o).append(t.doc.slice(a,s))},range:ke.cursor(o)}});return r.changes.empty?!1:(e(t.update(r,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Im(t){let e=[],r=-1;for(let n of t.selection.ranges){let s=t.doc.lineAt(n.from),i=t.doc.lineAt(n.to);if(!n.empty&&n.to==i.from&&(i=t.doc.lineAt(n.to-1)),r>=s.number){let a=e[e.length-1];a.to=i.to,a.ranges.push(n)}else e.push({from:s.from,to:i.to,ranges:[n]});r=i.number+1}return e}function dR(t,e,r){if(t.readOnly)return!1;let n=[],s=[];for(let i of Im(t)){if(r?i.to==t.doc.length:i.from==0)continue;let a=t.doc.lineAt(r?i.to+1:i.from-1),o=a.length+1;if(r){n.push({from:i.to,to:a.to},{from:i.from,insert:a.text+t.lineBreak});for(let l of i.ranges)s.push(ke.range(Math.min(t.doc.length,l.anchor+o),Math.min(t.doc.length,l.head+o)))}else{n.push({from:a.from,to:i.from},{from:i.to,insert:t.lineBreak+a.text});for(let l of i.ranges)s.push(ke.range(l.anchor-o,l.head-o))}}return n.length?(e(t.update({changes:n,scrollIntoView:!0,selection:ke.create(s,t.selection.mainIndex),userEvent:"move.line"})),!0):!1}const x8=({state:t,dispatch:e})=>dR(t,e,!1),w8=({state:t,dispatch:e})=>dR(t,e,!0);function hR(t,e,r){if(t.readOnly)return!1;let n=[];for(let s of Im(t))r?n.push({from:s.from,insert:t.doc.slice(s.from,s.to)+t.lineBreak}):n.push({from:s.to,insert:t.lineBreak+t.doc.slice(s.from,s.to)});return e(t.update({changes:n,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const S8=({state:t,dispatch:e})=>hR(t,e,!1),C8=({state:t,dispatch:e})=>hR(t,e,!0),A8=t=>{if(t.state.readOnly)return!1;let{state:e}=t,r=e.changes(Im(e).map(({from:s,to:i})=>(s>0?s--:i<e.doc.length&&i++,{from:s,to:i}))),n=_u(e.selection,s=>{let i;if(t.lineWrapping){let a=t.lineBlockAt(s.head),o=t.coordsAtPos(s.head,s.assoc||1);o&&(i=a.bottom+t.documentTop-o.bottom+t.defaultLineHeight/2)}return t.moveVertically(s,!0,i)}).map(r);return t.dispatch({changes:r,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0};function E8(t,e){if(/\(\)|\[\]|\{\}/.test(t.sliceDoc(e-1,e+1)))return{from:e,to:e};let r=Ms(t).resolveInner(e),n=r.childBefore(e),s=r.childAfter(e),i;return n&&s&&n.to<=e&&s.from>=e&&(i=n.type.prop(hr.closedBy))&&i.indexOf(s.name)>-1&&t.doc.lineAt(n.to).from==t.doc.lineAt(s.from).from&&!/\S/.test(t.sliceDoc(n.to,s.from))?{from:n.to,to:s.from}:null}const aC=fR(!1),k8=fR(!0);function fR(t){return({state:e,dispatch:r})=>{if(e.readOnly)return!1;let n=e.changeByRange(s=>{let{from:i,to:a}=s,o=e.doc.lineAt(i),l=!t&&i==a&&E8(e,i);t&&(i=a=(a<=o.to?o:e.doc.lineAt(a)).to);let c=new Em(e,{simulateBreak:i,simulateDoubleBreak:!!l}),u=H_(c,i);for(u==null&&(u=ym(/^\s*/.exec(e.doc.lineAt(i).text)[0],e.tabSize));a<o.to&&/\s/.test(o.text[a-o.from]);)a++;l?{from:i,to:a}=l:i>o.from&&i<o.from+100&&!/\S/.test(o.text.slice(0,i))&&(i=o.from);let d=["",Bd(e,u)];return l&&d.push(Bd(e,c.lineIndent(o.from,-1))),{changes:{from:i,to:a,insert:Mr.of(d)}
47,range:ke.cursor(i+1+d[1].length)}});return r(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0}}function t0(t,e){let r=-1;return t.changeByRange(n=>{let s=[];for(let a=n.from;a<=n.to;){let o=t.doc.lineAt(a);o.number>r&&(n.empty||n.to>o.from)&&(e(o,s,n),r=o.number),a=o.to+1}let i=t.changes(s);return{changes:s,range:ke.range(i.mapPos(n.anchor,1),i.mapPos(n.head,1))}})}const P8=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=Object.create(null),n=new Em(t,{overrideIndentation:i=>{let a=r[i];return a??-1}}),s=t0(t,(i,a,o)=>{let l=H_(n,i.from);if(l==null)return;/\S/.test(i.text)||(l=0);let c=/^\s*/.exec(i.text)[0],u=Bd(t,l);(c!=u||o.from<i.from+c.length)&&(r[i.from]=l,a.push({from:i.from,to:i.from+c.length,insert:u}))});return s.changes.empty||e(t.update(s,{userEvent:"indent"})),!0},T8=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(t0(t,(r,n)=>{n.push({from:r.from,insert:t.facet(vu)})}),{userEvent:"input.indent"})),!0),pR=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(t0(t,(r,n)=>{let s=/^\s*/.exec(r.text)[0];if(!s)return;let i=ym(s,t.tabSize),a=0,o=Bd(t,Math.max(0,i-Np(t)));for(;a<s.length&&a<o.length&&s.charCodeAt(a)==o.charCodeAt(a);)a++;n.push({from:r.from+a,to:r.from+s.length,insert:o.slice(a)})}),{userEvent:"delete.dedent"})),!0),R8=t=>(t.setTabFocusMode(),!0),I8=[{key:"Ctrl-b",run:zT,shift:ZT,preventDefault:!0},{key:"Ctrl-f",run:VT,shift:eR},{key:"Ctrl-p",run:KT,shift:nR},{key:"Ctrl-n",run:YT,shift:sR},{key:"Ctrl-a",run:YU,shift:a8},{key:"Ctrl-e",run:XU,shift:l8},{key:"Ctrl-d",run:lR},{key:"Ctrl-h",run:by},{key:"Ctrl-k",run:g8},{key:"Ctrl-Alt-h",run:uR},{key:"Ctrl-o",run:y8},{key:"Ctrl-t",run:_8},{key:"Ctrl-v",run:gy}],N8=[{key:"ArrowLeft",run:zT,shift:ZT,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:FU,shift:ZU,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:qU,shift:i8,preventDefault:!0},{key:"ArrowRight",run:VT,shift:eR,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:WU,shift:e8,preventDefault:!0},{mac:"Cmd-ArrowRight",run:KU,shift:o8,preventDefault:!0},{key:"ArrowUp",run:KT,shift:nR,preventDefault:!0},{mac:"Cmd-ArrowUp",run:nC,shift:iC},{mac:"Ctrl-ArrowUp",run:eC,shift:tC},{key:"ArrowDown",run:YT,shift:sR,preventDefault:!0},{mac:"Cmd-ArrowDown",run:sC,shift:oC},{mac:"Ctrl-ArrowDown",run:gy,shift:rC},{key:"PageUp",run:eC,shift:tC},{key:"PageDown",run:gy,shift:rC},{key:"Home",run:GU,shift:s8,preventDefault:!0},{key:"Mod-Home",run:nC,shift:iC},{key:"End",run:VU,shift:n8,preventDefault:!0},{key:"Mod-End",run:sC,shift:oC},{key:"Enter",run:aC,shift:aC},{key:"Mod-a",run:c8},{key:"Backspace",run:by,shift:by,preventDefault:!0},{key:"Delete",run:lR,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:uR,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:m8,preventDefault:!0},{mac:"Mod-Backspace",run:b8,preventDefault:!0},{mac:"Mod-Delete",run:v8,preventDefault:!0}].concat(I8.map(t=>({mac:t.key,run:t.run,shift:t.shift}))),L8=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:UU,shift:t8},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:zU,shift:r8},{key:"Alt-ArrowUp",run:x8},{key:"Shift-Alt-ArrowUp",run:S8},{key:"Alt-ArrowDown",run:w8},{key:"Shift-Alt-ArrowDown",run:C8},{key:"Mod-Alt-ArrowUp",run:h8},{key:"Mod-Alt-ArrowDown",run:f8},{key:"Escape",run:p8},{key:"Mod-Enter",run:k8},{key:"Alt-l",mac:"Ctrl-l",run:u8},{key:"Mod-i",run:d8,preventDefault:!0},{key:"Mod-[",run:pR},{key:"Mod-]",run:T8},{key:"Mod-Alt-\\",run:P8},{key:"Shift-Mod-k",run:A8},{key:"Shift-Mod-\\",run:QU},{key:"Mod-/",run:xU},{key:"Alt-A",run:SU},{key:"Ctrl-m",mac:"Shift-Alt-m",run:R8}].concat(N8),lC=typeof String.prototype.normalize=="function"?t=>t.normalize("NFKD"):t=>t;class Hd{constructor(e,r,n=0,s=e.length,i,a){this.test=a,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(n,s),this.bufferStart=n,this.normalize=i?o=>i(lC(o)):lC,this.query=this.normalize(r)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return lo(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let r=A_(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=na(e);let s=this.normalize(r);if(s.length)for(let i=0,a=n;;i++){let o=s.charCodeAt(i),l=this.match(o,a,this.bufferPos+this.bufferStart);if(i==s.length-1){if(l)return this.value=l,this;break}a==n&&i<r.length&&r.charCodeAt(i)==o&&a++}}}match(e,r,n){let s=null;for(let i=0;i<this.matches.length;i+=2){let a=this.matches[i],o=!1;
47this.query.charCodeAt(a)==e&&(a==this.query.length-1?s={from:this.matches[i+1],to:n}:(this.matches[i]++,o=!0)),o||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==e&&(this.query.length==1?s={from:r,to:n}:this.matches.push(1,r)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(Hd.prototype[Symbol.iterator]=function(){return this});const mR={from:-1,to:-1,match:/.*/.exec("")},r0="gm"+(/x/.unicode==null?"":"u");class gR{constructor(e,r,n,s=0,i=e.length){if(this.text=e,this.to=i,this.curLine="",this.done=!1,this.value=mR,/\\[sWDnr]|\n|\r|\[\^/.test(r))return new bR(e,r,n,s,i);this.re=new RegExp(r,r0+(n?.ignoreCase?"i":"")),this.test=n?.test,this.iter=e.iter();let a=e.lineAt(s);this.curLineStart=a.from,this.matchPos=$p(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let r=this.matchPos<=this.to&&this.re.exec(this.curLine);if(r){let n=this.curLineStart+r.index,s=n+r[0].length;if(this.matchPos=$p(this.text,s+(n==s?1:0)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(n<s||n>this.value.to)&&(!this.test||this.test(n,s,r)))return this.value={from:n,to:s,match:r},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}}const fb=new WeakMap;class Jc{constructor(e,r){this.from=e,this.text=r}get to(){return this.from+this.text.length}static get(e,r,n){let s=fb.get(e);if(!s||s.from>=n||s.to<=r){let o=new Jc(r,e.sliceString(r,n));return fb.set(e,o),o}if(s.from==r&&s.to==n)return s;let{text:i,from:a}=s;return a>r&&(i=e.sliceString(r,a)+i,a=r),s.to<n&&(i+=e.sliceString(s.to,n)),fb.set(e,new Jc(a,i)),new Jc(r,i.slice(r-a,n-a))}}class bR{constructor(e,r,n,s,i){this.text=e,this.to=i,this.done=!1,this.value=mR,this.matchPos=$p(e,s),this.re=new RegExp(r,r0+(n?.ignoreCase?"i":"")),this.test=n?.test,this.flat=Jc.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,r=this.re.exec(this.flat.text);if(r&&!r[0]&&r.index==e&&(this.re.lastIndex=e+1,r=this.re.exec(this.flat.text)),r){let n=this.flat.from+r.index,s=n+r[0].length;if((this.flat.to>=this.to||r.index+r[0].length<=this.flat.text.length-10)&&(!this.test||this.test(n,s,r)))return this.value={from:n,to:s,match:r},this.matchPos=$p(this.text,s+(n==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Jc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(gR.prototype[Symbol.iterator]=bR.prototype[Symbol.iterator]=function(){return this});function D8(t){try{return new RegExp(t,r0),!0}catch{return!1}}function $p(t,e){if(e>=t.length)return e;let r=t.lineAt(e),n;for(;e<r.to&&(n=r.text.charCodeAt(e-r.from))>=56320&&n<57344;)e++;return e}function vy(t){let e=String(t.state.doc.lineAt(t.state.selection.main.head).number),r=Rs("input",{class:"cm-textfield",name:"line",value:e}),n=Rs("form",{class:"cm-gotoLine",onkeydown:i=>{i.keyCode==27?(i.preventDefault(),t.dispatch({effects:gd.of(!1)}),t.focus()):i.keyCode==13&&(i.preventDefault(),s())},onsubmit:i=>{i.preventDefault(),s()}},Rs("label",t.state.phrase("Go to line"),": ",r)," ",Rs("button",{class:"cm-button",type:"submit"},t.state.phrase("go")),Rs("button",{name:"close",onclick:()=>{t.dispatch({effects:gd.of(!1)}),t.focus()},"aria-label":t.state.phrase("close"),type:"button"},["Ã"]));function s(){let i=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.value);if(!i)return;let{state:a}=t,o=a.doc.lineAt(a.selection.main.head),[,l,c,u,d]=i,h=u?+u.slice(1):0,m=c?+c:o.number;if(c&&d){let p=m/100;l&&(p=p*(l=="-"?-1:1)+o.number/a.doc.lines),m=Math.round(a.doc.lines*p)}else c&&l&&(m=m*(l=="-"?-1:1)+o.number);
47let b=a.doc.line(Math.max(1,Math.min(a.doc.lines,m))),g=ke.cursor(b.from+Math.max(0,Math.min(h,b.length)));t.dispatch({effects:[gd.of(!1),st.scrollIntoView(g.from,{y:"center"})],selection:g}),t.focus()}return{dom:n}}const gd=sr.define(),cC=gs.define({create(){return!0},update(t,e){for(let r of e.effects)r.is(gd)&&(t=r.value);return t},provide:t=>Pp.from(t,e=>e?vy:null)}),M8=t=>{let e=kp(t,vy);if(!e){let r=[gd.of(!0)];t.state.field(cC,!1)==null&&r.push(sr.appendConfig.of([cC,O8])),t.dispatch({effects:r}),e=kp(t,vy)}return e&&e.dom.querySelector("input").select(),!0},O8=st.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px",position:"relative","& label":{fontSize:"80%"},"& [name=close]":{position:"absolute",top:"0",bottom:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:"0"}}}),j8=({state:t,dispatch:e})=>{let{selection:r}=t,n=ke.create(r.ranges.map(s=>t.wordAt(s.head)||ke.cursor(s.head)),r.mainIndex);return n.eq(r)?!1:(e(t.update({selection:n})),!0)};function $8(t,e){let{main:r,ranges:n}=t.selection,s=t.wordAt(r.head),i=s&&s.from==r.from&&s.to==r.to;for(let a=!1,o=new Hd(t.doc,e,n[n.length-1].to);;)if(o.next(),o.done){if(a)return null;o=new Hd(t.doc,e,0,Math.max(0,n[n.length-1].from-1)),a=!0}else{if(a&&n.some(l=>l.from==o.value.from))continue;if(i){let l=t.wordAt(o.value.from);if(!l||l.from!=o.value.from||l.to!=o.value.to)continue}return o.value}}const B8=({state:t,dispatch:e})=>{let{ranges:r}=t.selection;if(r.some(i=>i.from===i.to))return j8({state:t,dispatch:e});let n=t.sliceDoc(r[0].from,r[0].to);if(t.selection.ranges.some(i=>t.sliceDoc(i.from,i.to)!=n))return!1;let s=$8(t,n);return s?(e(t.update({selection:t.selection.addRange(ke.range(s.from,s.to),!1),effects:st.scrollIntoView(s.to)})),!0):!1},xu=it.define({combine(t){return uc(t,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new J8(e),scrollToMatch:e=>st.scrollIntoView(e)})}});class vR{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||D8(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(r,n)=>n=="n"?` 48`:n=="r"?"\r":n=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new U8(this):new W8(this)}getCursor(e,r=0,n){let s=e.doc?e:Cr.create({doc:e});return n==null&&(n=s.doc.length),this.regexp?Tc(this,s,r,n):Pc(this,s,r,n)}}class yR{constructor(e){this.spec=e}}function Pc(t,e,r,n){return new Hd(e.doc,t.unquoted,r,n,t.caseSensitive?void 0:s=>s.toLowerCase(),t.wholeWord?F8(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function F8(t,e){return(r,n,s,i)=>((i>r||i+s.length<n)&&(i=Math.max(0,r-2),s=t.sliceString(i,Math.min(t.length,n+2))),(e(Bp(s,r-i))!=Kn.Word||e(Fp(s,r-i))!=Kn.Word)&&(e(Fp(s,n-i))!=Kn.Word||e(Bp(s,n-i))!=Kn.Word))}class W8 extends yR{constructor(e){super(e)}nextMatch(e,r,n){let s=Pc(this.spec,e,n,e.doc.length).nextOverlapping();if(s.done){let i=Math.min(e.doc.length,r+this.spec.unquoted.length);s=Pc(this.spec,e,0,i).nextOverlapping()}return s.done||s.value.from==r&&s.value.to==n?null:s.value}prevMatchInRange(e,r,n){for(let s=n;;){let i=Math.max(r,s-1e4-this.spec.unquoted.length),a=Pc(this.spec,e,i,s),o=null;for(;!a.nextOverlapping().done;)o=a.value;if(o)return o;if(i==r)return null;s-=1e4}}prevMatch(e,r,n){let s=this.prevMatchInRange(e,0,r);return s||(s=this.prevMatchInRange(e,Math.max(0,n-this.spec.unquoted.length),e.doc.length)),s&&(s.from!=r||s.to!=n)?s:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,r){let n=Pc(this.spec,e,0,e.doc.length),s=[];for(;!n.next().done;){if(s.length>=r)return null;s.push(n.value)}return s}highlight(e,r,n,s){let i=Pc(this.spec,e,Math.max(0,r-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function Tc(t,e,r,n){return new gR(e.doc,t.search,{ignoreCase:!t.caseSensitive,test:t.wholeWord?H8(e.charCategorizer(e.selection.main.head)):void 0}
vendor: 4,354 bytes, line 48
48,r,n)}function Bp(t,e){return t.slice(ts(t,e,!1),e)}function Fp(t,e){return t.slice(e,ts(t,e))}function H8(t){return(e,r,n)=>!n[0].length||(t(Bp(n.input,n.index))!=Kn.Word||t(Fp(n.input,n.index))!=Kn.Word)&&(t(Fp(n.input,n.index+n[0].length))!=Kn.Word||t(Bp(n.input,n.index+n[0].length))!=Kn.Word)}class U8 extends yR{nextMatch(e,r,n){let s=Tc(this.spec,e,n,e.doc.length).next();return s.done&&(s=Tc(this.spec,e,0,r).next()),s.done?null:s.value}prevMatchInRange(e,r,n){for(let s=1;;s++){let i=Math.max(r,n-s*1e4),a=Tc(this.spec,e,i,n),o=null;for(;!a.next().done;)o=a.value;if(o&&(i==r||o.from>i+10))return o;if(i==r)return null}}prevMatch(e,r,n){return this.prevMatchInRange(e,0,r)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(r,n)=>{if(n=="&")return e.match[0];if(n=="$")return"$";for(let s=n.length;s>0;s--){let i=+n.slice(0,s);if(i>0&&i<e.match.length)return e.match[i]+n.slice(s)}return r})}matchAll(e,r){let n=Tc(this.spec,e,0,e.doc.length),s=[];for(;!n.next().done;){if(s.length>=r)return null;s.push(n.value)}return s}highlight(e,r,n,s){let i=Tc(this.spec,e,Math.max(0,r-250),Math.min(n+250,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const Ud=sr.define(),n0=sr.define(),Qa=gs.define({create(t){return new pb(yy(t).create(),null)},update(t,e){for(let r of e.effects)r.is(Ud)?t=new pb(r.value.create(),t.panel):r.is(n0)&&(t=new pb(t.query,r.value?s0:null));return t},provide:t=>Pp.from(t,e=>e.panel)});class pb{constructor(e,r){this.query=e,this.panel=r}}const z8=lr.mark({class:"cm-searchMatch"}),V8=lr.mark({class:"cm-searchMatch cm-searchMatch-selected"}),G8=ms.fromClass(class{constructor(t){this.view=t,this.decorations=this.highlight(t.state.field(Qa))}update(t){let e=t.state.field(Qa);(e!=t.startState.field(Qa)||t.docChanged||t.selectionSet||t.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:t,panel:e}){if(!e||!t.spec.valid)return lr.none;let{view:r}=this,n=new oc;for(let s=0,i=r.visibleRanges,a=i.length;s<a;s++){let{from:o,to:l}=i[s];for(;s<a-1&&l>i[s+1].from-2*250;)l=i[++s].to;t.highlight(r.state,o,l,(c,u)=>{let d=r.state.selection.ranges.some(h=>h.from==c&&h.to==u);n.add(c,u,d?V8:z8)})}return n.finish()}},{decorations:t=>t.decorations});function yh(t){return e=>{let r=e.state.field(Qa,!1);return r&&r.query.spec.valid?t(e,r):wR(e)}}const Wp=yh((t,{query:e})=>{let{to:r}=t.state.selection.main,n=e.nextMatch(t.state,r,r);if(!n)return!1;let s=ke.single(n.from,n.to),i=t.state.facet(xu);return t.dispatch({selection:s,effects:[i0(t,n),i.scrollToMatch(s.main,t)],userEvent:"select.search"}),xR(t),!0}),Hp=yh((t,{query:e})=>{let{state:r}=t,{from:n}=r.selection.main,s=e.prevMatch(r,n,n);if(!s)return!1;let i=ke.single(s.from,s.to),a=t.state.facet(xu);return t.dispatch({selection:i,effects:[i0(t,s),a.scrollToMatch(i.main,t)],userEvent:"select.search"}),xR(t),!0}),q8=yh((t,{query:e})=>{let r=e.matchAll(t.state,1e3);return!r||!r.length?!1:(t.dispatch({selection:ke.create(r.map(n=>ke.range(n.from,n.to))),userEvent:"select.search.matches"}),!0)}),K8=({state:t,dispatch:e})=>{let r=t.selection;if(r.ranges.length>1||r.main.empty)return!1;let{from:n,to:s}=r.main,i=[],a=0;for(let o=new Hd(t.doc,t.sliceDoc(n,s));!o.next().done;){if(i.length>1e3)return!1;o.value.from==n&&(a=i.length),i.push(ke.range(o.value.from,o.value.to))}return e(t.update({selection:ke.create(i,a),userEvent:"select.search.matches"})),!0},uC=yh((t,{query:e})=>{let{state:r}=t,{from:n,to:s}=r.selection.main;if(r.readOnly)return!1;let i=e.nextMatch(r,n,n);if(!i)return!1;let a=i,o=[],l,c,u=[];a.from==n&&a.to==s&&(c=r.toText(e.getReplacement(a)),o.push({from:a.from,to:a.to,insert:c}),a=e.nextMatch(r,a.from,a.to),u.push(st.announce.of(r.phrase("replaced match on line $",r.doc.lineAt(n).number)+".")));let d=t.state.changes(o);return a&&(l=ke.single(a.from,a.to).map(d),u.push(i0(t,a)),u.push(r.facet(xu).scrollToMatch(l.main,t))),t.dispatch({changes:d,selection:l,effects:u,userEvent:"input.replace"}),!0}),Y8=yh((t,{query:e})=>{if(t.state.readOnly)return!1;let r=e.matchAll(t.state,1e9).map(s=>{let{from:i,to:a}=s;return{from:i,to:a,insert:e.getReplacement(s)}});if(!r.length)return!1;let n=t.state.phrase("replaced $ matches",r.length)+".";return t.dispatch({changes:r,effects:st.announce.of(n),userEvent:"input.replace.all"}),!0});
48function s0(t){return t.state.facet(xu).createPanel(t)}function yy(t,e){var r,n,s,i,a;let o=t.selection.main,l=o.empty||o.to>o.from+100?"":t.sliceDoc(o.from,o.to);if(e&&!l)return e;let c=t.facet(xu);return new vR({search:((r=e?.literal)!==null&&r!==void 0?r:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(n=e?.caseSensitive)!==null&&n!==void 0?n:c.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:c.literal,regexp:(i=e?.regexp)!==null&&i!==void 0?i:c.regexp,wholeWord:(a=e?.wholeWord)!==null&&a!==void 0?a:c.wholeWord})}function _R(t){let e=kp(t,s0);return e&&e.dom.querySelector("[main-field]")}function xR(t){let e=_R(t);e&&e==t.root.activeElement&&e.select()}const wR=t=>{let e=t.state.field(Qa,!1);if(e&&e.panel){let r=_R(t);if(r&&r!=t.root.activeElement){let n=yy(t.state,e.query.spec);n.valid&&t.dispatch({effects:Ud.of(n)}),r.focus(),r.select()}}else t.dispatch({effects:[n0.of(!0),e?Ud.of(yy(t.state,e.query.spec)):sr.appendConfig.of(Z8)]});return!0},SR=t=>{let e=t.state.field(Qa,!1);if(!e||!e.panel)return!1;let r=kp(t,s0);return r&&r.dom.contains(t.root.activeElement)&&t.focus(),t.dispatch({effects:n0.of(!1)}),!0},X8=[{key:"Mod-f",run:wR,scope:"editor search-panel"},{key:"F3",run:Wp,shift:Hp,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Wp,shift:Hp,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:SR,scope:"editor search-panel"},{key:"Mod-Shift-l",run:K8},{key:"Mod-Alt-g",run:M8},{key:"Mod-d",run:B8,preventDefault:!0}];class J8{constructor(e){this.view=e;let r=this.query=e.state.field(Qa).query.spec;this.commit=this.commit.bind(this),this.searchField=Rs("input",{value:r.search,placeholder:Ni(e,"Find"),"aria-label":Ni(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Rs("input",{value:r.replace,placeholder:Ni(e,"Replace"),"aria-label":Ni(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Rs("input",{type:"checkbox",name:"case",form:"",checked:r.caseSensitive,onchange:this.commit}),this.reField=Rs("input",{type:"checkbox",name:"re",form:"",checked:r.regexp,onchange:this.commit}),this.wordField=Rs("input",{type:"checkbox",name:"word",form:"",checked:r.wholeWord,onchange:this.commit});function n(s,i,a){return Rs("button",{class:"cm-button",name:s,onclick:i,type:"button"},a)}this.dom=Rs("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,n("next",()=>Wp(e),[Ni(e,"next")]),n("prev",()=>Hp(e),[Ni(e,"previous")]),n("select",()=>
48q8(e),[Ni(e,"all")]),Rs("label",null,[this.caseField,Ni(e,"match case")]),Rs("label",null,[this.reField,Ni(e,"regexp")]),Rs("label",null,[this.wordField,Ni(e,"by word")]),...e.state.readOnly?[]:[Rs("br"),this.replaceField,n("replace",()=>uC(e),[Ni(e,"replace")]),n("replaceAll",()=>Y8(e),[Ni(e,"replace all")])],Rs("button",{name:"close",onclick:()=>SR(e),"aria-label":Ni(e,"close"),type:"button"},["Ã"])])}commit(){let e=new vR({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Ud.of(e)}))}keydown(e){DW(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Hp:Wp)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),uC(this.view))}update(e){for(let r of e.transactions)for(let n of r.effects)n.is(Ud)&&!n.value.eq(this.query)&&this.setQuery(n.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(xu).top}}function Ni(t,e){return t.state.phrase(e)}const yf=30,_f=/[\s\.,:;?!]/;function i0(t,{from:e,to:r}){let n=t.state.doc.lineAt(e),s=t.state.doc.lineAt(r).to,i=Math.max(n.from,e-yf),a=Math.min(s,r+yf),o=t.state.sliceDoc(i,a);if(i!=n.from){for(let l=0;l<yf;l++)if(!_f.test(o[l+1])&&_f.test(o[l])){o=o.slice(l);break}}if(a!=s){for(let l=o.length-1;l>o.length-yf;l--)if(!_f.test(o[l-1])&&_f.test(o[l])){o=o.slice(0,l);break}}return st.announce.of(`${t.state.phrase("current match")}. ${o} ${t.state.phrase("on line")} ${n.number}.`)}const Q8=st.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Z8=[Qa,ul.low(G8),Q8],ez={apng:"image/apng",avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/x-icon",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp"};function tz(t){return String(t||"").trim().toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]}function rz(t){const e=String(t||"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/");if(!e)return"";const r=e.length%4;return r===0?e:`${e}${"=".repeat(4-r)}`}function nz(t,e){const r=rz(t);if(!r)return null;const n=atob(r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return new Blob([s],{type:e})}function sz(t,e){const r=x.useMemo(()=>tz(t),[t]),[n,s]=x.useState(null);return x.useEffect(()=>{if(s(null),!r)return;if(r==="svg"){if(!e||!/<svg[\s>]/i.test(e))return;const a=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),o=URL.createObjectURL(a);return s(o),()=>{URL.revokeObjectURL(o)}}const i=ez[r];if(!(!i||!e))try{const a=nz(e,i);if(!a)return;const o=URL.createObjectURL(a);return s(o),()=>{URL.revokeObjectURL(o)}}catch{return}},[e,r]),n}function iz({filePath:t,content:e}){const r=sz(t,e);return r?f.jsxs("div",{className:"absolute inset-0 z-10 flex min-h-0 flex-col bg-bolt-elements-background-depth-2",children:[f.jsx("div",{className:"shrink-0 border-b border-bolt-elements-borderColor px-4 py-3 text-sm text-bolt-elements-textSecondary",children:"Image preview"}),f.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:f.jsx("div",{className:"flex min-h-full items-center justify-center rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-4",children:f.jsx("img",{src:r,alt:t.split("/").pop()||"Workspace image",className:"max-h-full max-w-full rounded-md object-contain shadow-sm"})})})]}):f.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-bolt-elements-background-depth-2 px-6 text-center text-sm text-bolt-elements-textPrimary",children:"File format cannot be displayed."})}var CR=t=>{var{theme:e,settings:r={},styles:n=[]}=t,s={".cm-gutters":{}},i={};r.background&&(i.backgroundColor=r.background),r.backgroundImage&&(i.backgroundImage=r.backgroundImage),r.foreground&&(i.color=r.foreground),r.fontSize&&(i.fontSize=r.fontSize),(r.background||r.foreground)&&
48(s["&"]=i),r.fontFamily&&(s["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(s[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(s[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(s[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(s[".cm-content"]={caretColor:r.caret},s[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var a={};r.gutterActiveForeground&&(a.color=r.gutterActiveForeground),r.lineHighlight&&(s[".cm-activeLine"]={backgroundColor:r.lineHighlight},a.backgroundColor=r.lineHighlight),s[".cm-activeLineGutter"]=a,r.selection&&(s["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(s["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var o=st.theme(s,{dark:e==="dark"}),l=km.define(n),c=[o,u6(l)];return c},oz={background:"#ffffff",foreground:"#383a42",caret:"#000",selection:"#add6ff",selectionMatch:"#a8ac94",lineHighlight:"#99999926",gutterBackground:"#fff",gutterForeground:"#237893",gutterActiveForeground:"#0b216f",fontFamily:'Menlo, Monaco, Consolas, "Andale Mono", "Ubuntu Mono", "Courier New", monospace'},az=[{tag:[he.keyword,he.operatorKeyword,he.modifier,he.color,he.constant(he.name),he.standard(he.name),he.standard(he.tagName),he.special(he.brace),he.atom,he.bool,he.special(he.variableName)],color:"#0000ff"},{tag:[he.moduleKeyword,he.controlKeyword],color:"#af00db"},{tag:[he.name,he.deleted,he.character,he.macroName,he.propertyName,he.variableName,he.labelName,he.definition(he.name)],color:"#0070c1"},{tag:he.heading,fontWeight:"bold",color:"#0070c1"},{tag:[he.typeName,he.className,he.tagName,he.number,he.changed,he.annotation,he.self,he.namespace],color:"#267f99"},{tag:[he.function(he.variableName),he.function(he.propertyName)],color:"#795e26"},{tag:[he.number],color:"#098658"},{tag:[he.operator,he.punctuation,he.separator,he.url,he.escape,he.regexp],color:"#383a42"},{tag:[he.regexp],color:"#af00db"},{tag:[he.special(he.string),he.processingInstruction,he.string,he.inserted],color:"#a31515"},{tag:[he.angleBracket],color:"#383a42"},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.meta,he.comment],color:"#008000"},{tag:he.link,color:"#4078f2",textDecoration:"underline"},{tag:he.invalid,color:"#e45649"}];function lz(t){var{theme:e="light",settings:r={},styles:n=[]}={};return CR({theme:e,settings:X1({},oz,r),styles:[...az,...n]})}var cz=lz(),uz={background:"#1e1e1e",foreground:"#9cdcfe",caret:"#c6c6c6",selection:"#6199ff2f",selectionMatch:"#72a1ff59",lineHighlight:"#ffffff0f",gutterBackground:"#1e1e1e",gutterForeground:"#838383",gutterActiveForeground:"#fff",fontFamily:'Menlo, Monaco, Consolas, "Andale Mono", "Ubuntu Mono", "Courier New", monospace'},dz=[{tag:[he.keyword,he.operatorKeyword,he.modifier,he.color,he.constant(he.name),he.standard(he.name),he.standard(he.tagName),he.special(he.brace),he.atom,he.bool,he.special(he.variableName)],color:"#569cd6"},{tag:[he.controlKeyword,he.moduleKeyword],color:"#c586c0"},{tag:[he.name,he.deleted,he.character,he.macroName,he.propertyName,he.variableName,he.labelName,he.definition(he.name)],color:"#9cdcfe"},{tag:he.heading,fontWeight:"bold",color:"#9cdcfe"},{tag:[he.typeName,he.className,he.tagName,he.number,he.changed,he.annotation,he.self,he.namespace],color:"#4ec9b0"},{tag:[he.function(he.variableName),he.function(he.propertyName)],color:"#dcdcaa"},{tag:[he.number],color:"#b5cea8"},{tag:[he.operator,he.punctuation,he.separator,he.url,he.escape,he.regexp],color:"#d4d4d4"},{tag:[he.regexp],color:"#d16969"},{tag:[he.special(he.string),he.processingInstruction,he.string,he.inserted],color:"#ce9178"},{tag:[he.angleBracket],color:"#808080"},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.meta,he.comment],color:"#6a9955"},{tag:he.link,color:"#6a9955",textDecoration:"underline"},{tag:he.invalid,color:"#ff0000"}];function hz(t){var{theme:e="dark",settings:r={},styles:n=[]}={};return CR({theme:e,settings:X1({},uz,r),styles:[...dz,...n]})}var fz=hz();st.theme({},{dark:!0});const _y=new ic;function pz(t,e={}){return[mz(e),t==="dark"?_y.of([kR()]):_y.of([ER()])]}function AR(t){return _y.reconfigure(t==="dark"?kR():ER())}function mz(t){return st.theme({"&":{fontSize:t.fontSize??"12px"},"&.cm-editor":{height:"100%",background:"var(--cm-backgroundColor)",color:"var(--cm-textColor)"},".cm-cursor":{borderLeft:"var(--cm-cursor-width) solid var(--cm-cursor-backgroundColor)"},".cm-scroller":{lineHeight:"1.5","&:focus-visible":{outline:"none"}},".cm-line":{padding:"0 0 0 4px"},"&.cm-focused > .cm-scroller >
48 .cm-selectionLayer .cm-selectionBackground":{backgroundColor:"var(--cm-selection-backgroundColorFocused) !important",opacity:"var(--cm-selection-backgroundOpacityFocused, 0.3)"},"&:not(.cm-focused) > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{backgroundColor:"var(--cm-selection-backgroundColorBlured)",opacity:"var(--cm-selection-backgroundOpacityBlured, 0.3)"},"&.cm-focused > .cm-scroller .cm-matchingBracket":{backgroundColor:"var(--cm-matching-bracket)"},".cm-activeLine":{background:"var(--cm-activeLineBackgroundColor)"},".cm-gutters":{background:"var(--cm-gutter-backgroundColor)",borderRight:0,color:"var(--cm-gutter-textColor)"},".cm-gutter":{"&.cm-lineNumbers":{fontFamily:"Roboto Mono, monospace",fontSize:t.gutterFontSize??t.fontSize??"12px",minWidth:"40px"},"& .cm-activeLineGutter":{background:"transparent",color:"var(--cm-gutter-activeLineTextColor)"},"&.cm-foldGutter .cm-gutterElement > .fold-icon":{cursor:"pointer",color:"var(--cm-foldGutter-textColor)",transform:"translateY(2px)","&:hover":{color:"var(--cm-foldGutter-textColorHover)"}}},".cm-foldGutter .cm-gutterElement":{padding:"0 4px"},".cm-tooltip-autocomplete > ul > li":{minHeight:"18px"},".cm-panel.cm-search label":{marginLeft:"2px",fontSize:"12px"},".cm-panel.cm-search .cm-button":{fontSize:"12px"},".cm-panel.cm-search .cm-textfield":{fontSize:"12px"},".cm-panel.cm-search input[type=checkbox]":{position:"relative",transform:"translateY(2px)",marginRight:"4px"},".cm-panels":{borderColor:"var(--cm-panels-borderColor)"},".cm-panels-bottom":{borderTop:"1px solid var(--cm-panels-borderColor)",backgroundColor:"transparent"},".cm-panel.cm-search":{background:"var(--cm-search-backgroundColor)",color:"var(--cm-search-textColor)",padding:"8px"},".cm-search .cm-button":{background:"var(--cm-search-button-backgroundColor)",borderColor:"var(--cm-search-button-borderColor)",color:"var(--cm-search-button-textColor)",borderRadius:"4px","&:hover":{color:"var(--cm-search-button-textColorHover)"},"&:focus-visible":{outline:"none",borderColor:"var(--cm-search-button-borderColorFocused)"},"&:hover:not(:focus-visible)":{background:"var(--cm-search-button-backgroundColorHover)",borderColor:"var(--cm-search-button-borderColorHover)"},"&:hover:focus-visible":{background:"var(--cm-search-button-backgroundColorHover)",borderColor:"var(--cm-search-button-borderColorFocused)"}},".cm-panel.cm-search [name=close]":{top:"6px",right:"6px",padding:"0 6px",fontSize:"1rem",backgroundColor:"var(--cm-search-closeButton-backgroundColor)",color:"var(--cm-search-closeButton-textColor)","&:hover":{"border-radius":"6px",color:"var(--cm-search-closeButton-textColorHover)",backgroundColor:"var(--cm-search-closeButton-backgroundColorHover)"}},".cm-search input":{background:"var(--cm-search-input-backgroundColor)",borderColor:"var(--cm-search-input-borderColor)",color:"var(--cm-search-input-textColor)",outline:"none",borderRadius:"4px","&:focus-visible":{borderColor:"var(--cm-search-input-borderColorFocused)"}},".cm-tooltip":{background:"var(--cm-tooltip-backgroundColor)",border:"1px solid transparent",borderColor:"var(--cm-tooltip-borderColor)",color:"var(--cm-tooltip-textColor)"},".cm-tooltip.cm-tooltip-autocomplete ul li[aria-selected]":{background:"var(--cm-tooltip-backgroundColorSelected)",color:"var(--cm-tooltip-textColorSelected)"},".cm-searchMatch":{backgroundColor:"var(--cm-searchMatch-backgroundColor)"},".cm-tooltip.cm-readonly-tooltip":{padding:"4px",whiteSpace:"nowrap",backgroundColor:"var(--bolt-elements-bg-depth-2)",borderColor:"var(--bolt-elements-borderColorActive)","& .cm-tooltip-arrow:before":{borderTopColor:"var(--bolt-elements-borderColorActive)"},"& .cm-tooltip-arrow:after":{borderTopColor:"transparent"}}})}function ER(){return cz}function kR(){return fz}const gz={key:"Tab",run:bz,shift:pR};function bz({state:t,dispatch:e}){return t.readOnly?!1:(e(t.update(vz(t,(r,n,s)=>{s.push({from:r,to:n,insert:t.facet(vu)})}),{userEvent:"input.indent"})),!0)}function vz(t,e){return t.changeByRange(r=>{const n=[],s=t.doc.lineAt(r.from);if(r.from===r.to)e(r.from,void 0,n,s);else if(r.from<r.to&&r.to<=s.to)e(r.from,r.to,n,s);else{let a=-1;for(let o=r.from;o<=r.to;){const l=t.doc.lineAt(o);l.number>a&&(r.empty||r.to>l.from)&&(e(l.from,void 0,n,l),a=l.number),o=l.to+1}}const i=t.changes(n);return{changes:n,range:ke.range(i.mapPos(r.anchor,1),i.mapPos(r.head,1))}})}const yz=[Ts.of({name:"VUE",extensions:["vue"],async load(){return H(()=>import("./index-CHJK_WGo.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89])).then(t=>t.vue())}}),Ts.of({name:"TS",extensions:["ts"],async load(){return H(()=>import("./index-ClVLQyOJ.js"),__vite__mapDeps([89,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.javascript({typescript:!0}))}}),Ts.of({name:"JS",extensions:["js","mjs","cjs"],async load(){return H(()=>import("./index-ClVLQyOJ.js"),__vite__mapDeps([89,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.javascript())}}),Ts.of({name:"TSX",extensions:["tsx"],async load(){return H(()=>import("./index-ClVLQyOJ.js"),__vite__mapDeps([89,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>
48t.javascript({jsx:!0,typescript:!0}))}}),Ts.of({name:"JSX",extensions:["jsx"],async load(){return H(()=>import("./index-ClVLQyOJ.js"),__vite__mapDeps([89,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.javascript({jsx:!0}))}}),Ts.of({name:"HTML",extensions:["html"],async load(){return H(()=>import("./index-BSuLgOgM.js"),__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89])).then(t=>t.html())}}),Ts.of({name:"CSS",extensions:["css"],async load(){return H(()=>import("./index-BWG24D4D.js"),__vite__mapDeps([4,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.css())}}),Ts.of({name:"SASS",extensions:["sass"],async load(){return H(()=>import("./index-CdNT3kup.js"),__vite__mapDeps([90,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.sass({indented:!0}))}}),Ts.of({name:"SCSS",extensions:["scss"],async load(){return H(()=>import("./index-CdNT3kup.js"),__vite__mapDeps([90,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.sass({indented:!1}))}}),Ts.of({name:"JSON",extensions:["json"],async load(){return H(()=>import("./index-MuJDxPXn.js"),__vite__mapDeps([91,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.json())}}),Ts.of({name:"Markdown",extensions:["md"],async load(){return H(()=>import("./index-uSfUUvZD.js"),__vite__mapDeps([92,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89])).then(t=>t.markdown())}}),Ts.of({name:"Wasm",extensions:["wat"],async load(){return H(()=>import("./index-Gg5lkPbv.js"),__vite__mapDeps([93,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.wast())}}),Ts.of({name:"Python",extensions:["py"],async load(){return H(()=>import("./index-DdJCVIS5.js"),__vite__mapDeps([94,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.python())}}),Ts.of({name:"C++",extensions:["cpp"],async load(){return H(()=>import("./index-B19Skoh2.js"),__vite__mapDeps([95,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>t.cpp())}})];async function _z(t){const e=Ts.matchFilename(yz,t);if(e)return await e.load()}class xz extends dl{constructor(e){super(),this._value=e}eq(e){return e._value===this._value}toDOM(){const e=document.createElement("span");return e.textContent="*".repeat(this._value.length),e.className="
48cm-masked-text",e}ignoreEvent(){return!1}}function wz(t){return ms.fromClass(class{decorations;constructor(e){this.decorations=this.buildDecorations(e)}update(e){(e.docChanged||e.viewportChanged)&&(this.decorations=this.buildDecorations(e.view))}buildDecorations(e){const r=t();if(!(r?.endsWith(".env")||r?.includes(".env.")||r?.includes("/.env")))return lr.none;const s=[],i=e.state.doc;for(let a=1;a<=i.lines;a++){const o=i.line(a),l=o.text,c=l.match(/^([^=]+)=(.+)$/);if(c&&!l.trim().startsWith("#")){const[,u,d]=c,h=o.from+u.length+1;s.push(lr.replace({inclusive:!0,widget:new xz(d)}).range(h,o.to))}}return lr.set(s)}},{decorations:e=>e.decorations})}const bd=ya("CodeMirrorEditor");let PR;const TR=sr.define(),Sz=gs.define({create:()=>[],update(t,e){if(!e.state.readOnly)return[];for(const r of e.effects)if(r.is(TR)&&r.value)return kz(e.state);return[]},provide:t=>$_.computeN([t],e=>e.field(t))}),o0=sr.define(),dC=gs.define({create(){return!0},update(t,e){for(const r of e.effects)if(r.is(o0))return r.value;return t}}),RR=x.memo(({id:t,doc:e,debounceScroll:r=100,debounceChange:n=150,autoFocusOnDocumentChange:s=!1,editable:i=!0,onScroll:a,onChange:o,onSave:l,theme:c,settings:u,className:d=""})=>{gu.trace("CodeMirrorEditor");const[h]=x.useState(new ic),[m]=x.useState(new ic),b=x.useRef(null),g=x.useRef(),p=x.useRef(),y=x.useRef(),v=x.useRef(),_=x.useRef(a),w=x.useRef(o),C=x.useRef(l);return x.useEffect(()=>{_.current=a,w.current=o,C.current=l,y.current=e,PR=e,p.current=c}),x.useEffect(()=>{if(!(!g.current||!e||e.isBinary))if(typeof e.scroll?.line=="number"){const A=e.scroll.line,E=e.scroll.column??0;try{const S=g.current.state.doc.lines;if(A<S){const k=g.current.state.doc.line(A+1).from+E;g.current.dispatch({selection:{anchor:k},scrollIntoView:!0}),g.current.focus()}else bd.warn(`Invalid line number ${A+1} in ${S}-line document`)}catch(S){bd.error("Error scrolling to line:",S)}}else(typeof e.scroll?.top=="number"||typeof e.scroll?.left=="number")&&g.current.scrollDOM.scrollTo(e.scroll.left??0,e.scroll.top??0)},[e?.scroll?.line,e?.scroll?.column,e?.scroll?.top,e?.scroll?.left]),x.useEffect(()=>{const A=sh(S=>{w.current?.(S)},n),E=new st({parent:b.current,dispatchTransactions(S){const k=E.state.selection;E.update(S);const O=E.state.selection,T=O!==k&&(O===void 0||k===void 0||!O.eq(k));y.current&&(S.some(R=>R.docChanged)||T)&&(A({selection:E.state.selection,content:E.state.doc.toString()}),v.current.set(y.current.filePath,E.state))}});return g.current=E,()=>{g.current?.destroy(),g.current=void 0}},[]),x.useEffect(()=>{g.current&&g.current.dispatch({effects:[AR(c)]})},[c]),x.useEffect(()=>{v.current=new Map},[t]),x.useEffect(()=>{const A=v.current,E=g.current,S=p.current;if(!e){const R=hC("",S,u,_,r,C,[h.of([]),m.of([])]);E.setState(R),Az(E);return}if(e.isBinary)return;e.filePath===""&&bd.warn("File path should not be empty");let k=A.get(e.filePath);k||(k=hC(e.value,S,u,_,r,C,[h.of([]),m.of([wz(()=>y.current?.filePath)])]),A.set(e.filePath,k)),E.setState(k),Ez(E,S,i,h,s,e);const O=Zy(),{locked:T}=e_(e.filePath,O);T&&E.dispatch({effects:[o0.of(!1)]})},[e?.value,i,e?.filePath,s]),f.jsxs("div",{className:ue("relative h-full",d),children:[Cz(e)&&e&&f.jsx(iz,{filePath:e.filePath,content:e.value}),f.jsx("div",{className:"h-full overflow-hidden",ref:b})]})});RR.displayName="CodeMirrorEditor";function Cz(t){return t?t.isBinary||/\.svg$/i.test(t.filePath):!1}function hC(t,e,r,n,s,i,a){return Cr.create({doc:t,extensions:[st.domEventHandlers({scroll:sh((o,l)=>{o.target===l.scrollDOM&&n.current?.({left:l.scrollDOM.scrollLeft,top:l.scrollDOM.scrollTop})},s),keydown:(o,l)=>l.state.readOnly?(l.dispatch({effects:[TR.of(o.key!=="Escape")]}),!0):!1}),pz(e,r),RU(),Am.of([...L8,...BU,...X8,{key:"Tab",run:NT},{key:"Mod-s",preventDefault:!0,run:()=>(i.current?.(),!0)},gz]),vu.of(" "),vU({closeOnBlur:!1}),JW({position:"absolute",parent:document.body,tooltipSpace:o=>{const l=o.dom.getBoundingClientRect();return{top:l.top-50,left:l.left,bottom:l.bottom,right:l.right+10}}}),lU(),uH(),GW(),VW(),FW(),y6(),Cr.tabSize.of(r?.tabSize??2),JH(),Sz,dC,Cr.readOnly.from(dC,o=>!o),fH(),qW(),a6({markerDOM:o=>{const l=document.createElement("div");return l.className=`fold-icon ${o?"i-ph-caret-down-bold":"i-ph-caret-right-bold"}`,l}}),...a]})}function Az(t){t.dispatch({selection:{anchor:0},changes:{from:0,to:t.state.doc.length,insert:""}}),t.scrollDOM.scrollTo(0,0)}function Ez(t,e,r,n,s,i){i.value!==t.state.doc.toString()&&t.dispatch({selection:{anchor:0},changes:{from:0,to:t.state.doc.length,insert:i.value}});const a=Zy(),{locked:o}=e_(i.filePath,a);t.dispatch({effects:[o0.of(r&&!i.isBinary&&!o)]}),_z(i.filePath).then(l=>{l&&(t.dispatch({effects:[n.reconfigure([l]),AR(e)]}),requestAnimationFrame(()=>{const c=t.scrollDOM.scrollLeft,u=t.scrollDOM.scrollTop,d=i.scroll?.left??0,h=i.scroll?.top??0;if(typeof i.scroll?.line=="number"){const b=i.scroll.line,g=i.scroll.column??0;try{const p=t.state.doc.lines;if(b<p){const y=t.state.doc.line(b+1).from+g;
48t.dispatch({selection:{anchor:y},scrollIntoView:!0}),t.focus()}else bd.warn(`Invalid line number ${b+1} in ${p}-line document`)}catch(p){bd.error("Error scrolling to line:",p)}return}s&&r&&(c!==d||u!==h?t.scrollDOM.addEventListener("scroll",()=>{t.focus()},{once:!0}):t.focus()),t.scrollDOM.scrollTo(d,h)}))})}function kz(t){if(!t.readOnly)return[];const e=PR;let r="Cannot edit file while AI response is being generated";if(e?.filePath){const n=Zy(),{locked:s}=e_(e.filePath,n);s&&(r="This file is locked and cannot be edited")}return t.selection.ranges.filter(n=>n.empty).map(n=>({pos:n.head,above:!0,strictSide:!0,arrow:!0,create:()=>{const s=document.createElement("div");return s.className="cm-readonly-tooltip",s.textContent=r,{dom:s}}}))}const Mn=x.memo(({className:t,disabledClassName:e,disabled:r=!1,title:n,children:s,onClick:i})=>f.jsx("button",{className:ue("flex items-center shrink-0 gap-1.5 whitespace-nowrap px-1.5 rounded-md py-0.5 text-bolt-elements-item-contentDefault bg-transparent enabled:hover:text-bolt-elements-item-contentActive enabled:hover:bg-bolt-elements-item-backgroundActive disabled:cursor-not-allowed",{[ue("opacity-30",e)]:r},t),disabled:r,title:n,onClick:a=>{r||i?.(a)},children:s})),Pz=x.memo,Tz=Pz(({selected:t,options:e,setSelected:r})=>{const n=!!e.middle,s=t===e.left.value,i=n&&e.middle?t===e.middle.value:!1;return f.jsxs("div",{className:"flex items-center flex-wrap shrink-0 gap-1 bg-bolt-elements-background-depth-1 overflow-hidden rounded-full p-1",children:[f.jsx(mb,{selected:s,setSelected:()=>r?.(e.left.value),children:e.left.text}),e.middle&&f.jsx(mb,{selected:i,setSelected:()=>r?.(e.middle.value),children:e.middle.text}),f.jsx(mb,{selected:!s&&!i,setSelected:()=>r?.(e.right.value),children:e.right.text})]})}),mb=x.memo(({selected:t,children:e,setSelected:r})=>f.jsxs("button",{onClick:r,className:ue("bg-transparent text-sm px-2.5 py-0.5 rounded-full relative",t?"text-bolt-elements-item-contentAccent":"text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive"),children:[f.jsx("span",{className:"relative z-10",children:e}),t&&f.jsx(ar.span,{layoutId:"pill-tab",transition:{duration:.2,ease:Ds},className:"absolute inset-0 z-0 bg-bolt-elements-item-backgroundAccent rounded-full"})]})),Nm=x.createContext(null);Nm.displayName="PanelGroupContext";const Pn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},a0=10,Ql=x.useLayoutEffect,fC=rp.useId,Rz=typeof fC=="function"?fC:()=>null;let Iz=0;function l0(t=null){const e=Rz(),r=x.useRef(t||e||null);return r.current===null&&(r.current=""+Iz++),t??r.current}function IR({children:t,className:e="",collapsedSize:r,collapsible:n,defaultSize:s,forwardedRef:i,id:a,maxSize:o,minSize:l,onCollapse:c,onExpand:u,onResize:d,order:h,style:m,tagName:b="div",...g}){const p=x.useContext(Nm);if(p===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:v,getPanelSize:_,getPanelStyle:w,groupId:C,isPanelCollapsed:A,reevaluatePanelConstraints:E,registerPanel:S,resizePanel:k,unregisterPanel:O}=p,T=l0(a),R=x.useRef({callbacks:{onCollapse:c,onExpand:u,onResize:d},constraints:{collapsedSize:r,collapsible:n,defaultSize:s,maxSize:o,minSize:l},id:T,idIsFromProps:a!==void 0,order:h});x.useRef({didLogMissingDefaultSizeWarning:!1}),Ql(()=>{const{callbacks:M,constraints:B}=R.current,U={...B};R.current.id=T,R.current.idIsFromProps=a!==void 0,R.current.order=h,M.onCollapse=c,M.onExpand=u,M.onResize=d,B.collapsedSize=r,B.collapsible=n,B.defaultSize=s,B.maxSize=o,B.minSize=l,(U.collapsedSize!==B.collapsedSize||U.collapsible!==B.collapsible||U.maxSize!==B.maxSize||U.minSize!==B.minSize)&&E(R.current,U)}),Ql(()=>{const M=R.current;return S(M),()=>{O(M)}},[h,T,S,O]),x.useImperativeHandle(i,()=>({collapse:()=>{y(R.current)},expand:M=>{v(R.current,M)},getId(){return T}
48,getSize(){return _(R.current)},isCollapsed(){return A(R.current)},isExpanded(){return!A(R.current)},resize:M=>{k(R.current,M)}}),[y,v,_,A,T,k]);const N=w(R.current,s);return x.createElement(b,{...g,children:t,className:e,id:T,style:{...N,...m},[Pn.groupId]:C,[Pn.panel]:"",[Pn.panelCollapsible]:n||void 0,[Pn.panelId]:T,[Pn.panelSize]:parseFloat(""+N.flexGrow).toFixed(1)})}const vd=x.forwardRef((t,e)=>x.createElement(IR,{...t,forwardedRef:e}));IR.displayName="Panel";vd.displayName="forwardRef(Panel)";let xy=null,qf=-1,qa=null;function Nz(t,e){if(e){const r=(e&OR)!==0,n=(e&jR)!==0,s=(e&$R)!==0,i=(e&BR)!==0;if(r)return s?"se-resize":i?"ne-resize":"e-resize";if(n)return s?"sw-resize":i?"nw-resize":"w-resize";if(s)return"s-resize";if(i)return"n-resize"}switch(t){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Lz(){qa!==null&&(document.head.removeChild(qa),xy=null,qa=null,qf=-1)}function gb(t,e){var r,n;const s=Nz(t,e);if(xy!==s){if(xy=s,qa===null&&(qa=document.createElement("style"),document.head.appendChild(qa)),qf>=0){var i;(i=qa.sheet)===null||i===void 0||i.removeRule(qf)}qf=(r=(n=qa.sheet)===null||n===void 0?void 0:n.insertRule(`*{cursor: ${s} !important;}`))!==null&&r!==void 0?r:-1}}function NR(t){return t.type==="keydown"}function LR(t){return t.type.startsWith("pointer")}function DR(t){return t.type.startsWith("mouse")}function Lm(t){if(LR(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(DR(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function Dz(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Mz(t,e,r){return t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y}function Oz(t,e){if(t===e)throw new Error("Cannot compare node with itself");const r={a:gC(t),b:gC(e)};let n;for(;r.a.at(-1)===r.b.at(-1);)t=r.a.pop(),e=r.b.pop(),n=t;tr(n,"Stacking order can only be calculated for elements with a common ancestor");const s={a:mC(pC(r.a)),b:mC(pC(r.b))};if(s.a===s.b){const i=n.childNodes,a={a:r.a.at(-1),b:r.b.at(-1)};let o=i.length;for(;o--;){const l=i[o];if(l===a.a)return 1;if(l===a.b)return-1}}return Math.sign(s.a-s.b)}const jz=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function $z(t){var e;const r=getComputedStyle((e=MR(t))!==null&&e!==void 0?e:t).display;return r==="flex"||r==="inline-flex"}function Bz(t){const e=getComputedStyle(t);return!!(e.position==="fixed"||e.zIndex!=="auto"&&(e.position!=="static"||$z(t))||+e.opacity<1||"transform"in e&&e.transform!=="none"||"webkitTransform"in e&&e.webkitTransform!=="none"||"mixBlendMode"in e&&e.mixBlendMode!=="normal"||"filter"in e&&e.filter!=="none"||"webkitFilter"in e&&e.webkitFilter!=="none"||"isolation"in e&&e.isolation==="isolate"||jz.test(e.willChange)||e.webkitOverflowScrolling==="touch")}function pC(t){let e=t.length;for(;e--;){const r=t[e];if(tr(r,"Missing node"),Bz(r))return r}return null}function mC(t){return t&&Number(getComputedStyle(t).zIndex)||0}function gC(t){const e=[];for(;t;)e.push(t),t=MR(t);return e}function MR(t){const{parentNode:e}=t;return e&&e instanceof ShadowRoot?e.host:e}const OR=1,jR=2,$R=4,BR=8,Fz=Dz()==="coarse";let po=[],Qc=!1,jl=new Map,Dm=new Map;const zd=new Set;function Wz(t,e,r,n,s){var i;const{ownerDocument:a}=e,o={direction:r,element:e,hitAreaMargins:n,setResizeHandlerState:s},l=(i=jl.get(a))!==null&&i!==void 0?i:0;return jl.set(a,l+1),zd.add(o),Up(),function(){var u;Dm.delete(t),zd.delete(o);const d=(u=jl.get(a))!==null&&u!==void 0?u:1;if(jl.set(a,d-1),Up(),d===1&&jl.delete(a),po.includes(o)){const h=po.indexOf(o);h>=0&&po.splice(h,1),u0(),s("up",!0,null)}}}function Hz(t){const{target:e}=t,{x:r,y:n}=Lm(t);Qc=!0,c0({target:e,x:r,y:n}),Up(),po.length>0&&(zp("down",t),t.preventDefault(),FR(e)||t.stopImmediatePropagation())}function bb(t){const{x:e,y:r}=Lm(t);if(Qc&&t.buttons===0&&(Qc=!1,zp("up",t)),!Qc){const{target:n}=t;c0({target:n,x:e,y:r})}zp("move",t),u0(),po.length>0&&t.preventDefault()}function vb(t){const{target:e}=t,{x:r,y:n}=Lm(t);Dm.clear(),Qc=!1,po.length>0&&(t.preventDefault(),FR(e)||t.stopImmediatePropagation()),zp("up",t),c0({target:e,x:r,y:n}),u0(),Up()}function FR(t){let e=t;for(;e;){if(e.hasAttribute(Pn.resizeHandle))return!0;e=e.parentElement}return!1}function c0({target:t,x:e,y:r}){po.splice(0);let n=null;(t instanceof HTMLElement||t instanceof SVGElement)&&(n=t),zd.forEach(s=>{const{element:i,hitAreaMargins:a}=s,o=i.getBoundingClientRect(),{bottom:l,left:c,right:u,top:d}=o,h=Fz?a.coarse:a.fine;if(e>=c-h&&e<=u+h&&r>=d-h&&r<=l+h){if(n!==null&&document.contains(n)&&i!==n&&!i.contains(n)&&!n.contains(i)&&Oz(n,i)>0){let b=n,g=!1;for(;b&&!b.contains(i);){if(Mz(b.getBoundingClientRect(),o)){g=!0;break}b=b.parentElement}if(g)return}po.push(s)}})}function yb(t,e){Dm.set(t,e)}function u0(){let t=!1,e=!1;
48po.forEach(n=>{const{direction:s}=n;s==="horizontal"?t=!0:e=!0});let r=0;Dm.forEach(n=>{r|=n}),t&&e?gb("intersection",r):t?gb("horizontal",r):e?gb("vertical",r):Lz()}let _b=new AbortController;function Up(){_b.abort(),_b=new AbortController;const t={capture:!0,signal:_b.signal};zd.size&&(Qc?(po.length>0&&jl.forEach((e,r)=>{const{body:n}=r;e>0&&(n.addEventListener("contextmenu",vb,t),n.addEventListener("pointerleave",bb,t),n.addEventListener("pointermove",bb,t))}),window.addEventListener("pointerup",vb,t),window.addEventListener("pointercancel",vb,t)):jl.forEach((e,r)=>{const{body:n}=r;e>0&&(n.addEventListener("pointerdown",Hz,t),n.addEventListener("pointermove",bb,t))}))}function zp(t,e){zd.forEach(r=>{const{setResizeHandlerState:n}=r,s=po.includes(r);n(t,s,e)})}function Uz(){const[t,e]=x.useState(0);return x.useCallback(()=>e(r=>r+1),[])}function tr(t,e){if(!t)throw console.error(e),Error(e)}function cc(t,e,r=a0){return t.toFixed(r)===e.toFixed(r)?0:t>e?1:-1}function ia(t,e,r=a0){return cc(t,e,r)===0}function Di(t,e,r){return cc(t,e,r)===0}function zz(t,e,r){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){const s=t[n],i=e[n];if(!Di(s,i,r))return!1}return!0}function Wc({panelConstraints:t,panelIndex:e,size:r}){const n=t[e];tr(n!=null,`Panel constraints not found for index ${e}`);let{collapsedSize:s=0,collapsible:i,maxSize:a=100,minSize:o=0}=n;if(cc(r,o)<0)if(i){const l=(s+o)/2;cc(r,l)<0?r=s:r=o}else r=o;return r=Math.min(a,r),r=parseFloat(r.toFixed(a0)),r}function rd({delta:t,initialLayout:e,panelConstraints:r,pivotIndices:n,prevLayout:s,trigger:i}){if(Di(t,0))return e;const a=[...e],[o,l]=n;tr(o!=null,"Invalid first pivot index"),tr(l!=null,"Invalid second pivot index");let c=0;if(i==="keyboard"){{const d=t<0?l:o,h=r[d];tr(h,`Panel constraints not found for index ${d}`);const{collapsedSize:m=0,collapsible:b,minSize:g=0}=h;if(b){const p=e[d];if(tr(p!=null,`Previous layout not found for panel index ${d}`),Di(p,m)){const y=g-p;cc(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}{const d=t<0?o:l,h=r[d];tr(h,`No panel constraints found for index ${d}`);const{collapsedSize:m=0,collapsible:b,minSize:g=0}=h;if(b){const p=e[d];if(tr(p!=null,`Previous layout not found for panel index ${d}`),Di(p,g)){const y=p-m;cc(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}}{const d=t<0?1:-1;let h=t<0?l:o,m=0;for(;;){const g=e[h];tr(g!=null,`Previous layout not found for panel index ${h}`);const y=Wc({panelConstraints:r,panelIndex:h,size:100})-g;if(m+=y,h+=d,h<0||h>=r.length)break}const b=Math.min(Math.abs(t),Math.abs(m));t=t<0?0-b:b}{let h=t<0?o:l;for(;h>=0&&h<r.length;){const m=Math.abs(t)-Math.abs(c),b=e[h];tr(b!=null,`Previous layout not found for panel index ${h}`);const g=b-m,p=Wc({panelConstraints:r,panelIndex:h,size:g});if(!Di(b,p)&&(c+=b-p,a[h]=p,c.toPrecision(3).localeCompare(Math.abs(t).toPrecision(3),void 0,{numeric:!0})>=0))break;t<0?h--:h++}}if(zz(s,a))return s;{const d=t<0?l:o,h=e[d];tr(h!=null,`Previous layout not found for panel index ${d}`);const m=h+c,b=Wc({panelConstraints:r,panelIndex:d,size:m});if(a[d]=b,!Di(b,m)){let g=m-b,y=t<0?l:o;for(;y>=0&&y<r.length;){const v=a[y];tr(v!=null,`Previous layout not found for panel index ${y}`);const _=v+g,w=Wc({panelConstraints:r,panelIndex:y,size:_});if(Di(v,w)||(g-=w-v,a[y]=w),Di(g,0))break;t>0?y--:y++}}}const u=a.reduce((d,h)=>h+d,0);return Di(u,100)?a:s}function Vz({layout:t,panelsArray:e,pivotIndices:r}){let n=0,s=100,i=0,a=0;const o=r[0];tr(o!=null,"No pivot index found"),e.forEach((d,h)=>{const{constraints:m}=d,{maxSize:b=100,minSize:g=0}=m;h===o?(n=g,s=b):(i+=g,a+=b)});const l=Math.min(s,100-i),c=Math.max(n,100-a),u=t[o];return{valueMax:l,valueMin:c,valueNow:u}}function Vd(t,e=document){return Array.from(e.querySelectorAll(`[${Pn.resizeHandleId}][data-panel-group-id="${t}"]`))}function WR(t,e,r=document){const s=Vd(t,r).findIndex(i=>i.getAttribute(Pn.resizeHandleId)===e);return s??null}function HR(t,e,r){const n=WR(t,e,r);return n!=null?[n,n+1]:[-1,-1]}function UR(t,e=document){var r;if(e instanceof HTMLElement&&(e==null||(r=e.dataset)===null||r===void 0?void 0:r.panelGroupId)==t)return e;
48const n=e.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return n||null}function Mm(t,e=document){const r=e.querySelector(`[${Pn.resizeHandleId}="${t}"]`);return r||null}function Gz(t,e,r,n=document){var s,i,a,o;const l=Mm(e,n),c=Vd(t,n),u=l?c.indexOf(l):-1,d=(s=(i=r[u])===null||i===void 0?void 0:i.id)!==null&&s!==void 0?s:null,h=(a=(o=r[u+1])===null||o===void 0?void 0:o.id)!==null&&a!==void 0?a:null;return[d,h]}function qz({committedValuesRef:t,eagerValuesRef:e,groupId:r,layout:n,panelDataArray:s,panelGroupElement:i,setLayout:a}){x.useRef({didWarnAboutMissingResizeHandle:!1}),Ql(()=>{if(!i)return;const o=Vd(r,i);for(let l=0;l<s.length-1;l++){const{valueMax:c,valueMin:u,valueNow:d}=Vz({layout:n,panelsArray:s,pivotIndices:[l,l+1]}),h=o[l];if(h!=null){const m=s[l];tr(m,`No panel data found for index "${l}"`),h.setAttribute("aria-controls",m.id),h.setAttribute("aria-valuemax",""+Math.round(c)),h.setAttribute("aria-valuemin",""+Math.round(u)),h.setAttribute("aria-valuenow",d!=null?""+Math.round(d):"")}}return()=>{o.forEach((l,c)=>{l.removeAttribute("aria-controls"),l.removeAttribute("aria-valuemax"),l.removeAttribute("aria-valuemin"),l.removeAttribute("aria-valuenow")})}},[r,n,s,i]),x.useEffect(()=>{if(!i)return;const o=e.current;tr(o,"Eager values not found");const{panelDataArray:l}=o,c=UR(r,i);tr(c!=null,`No group found for id "${r}"`);const u=Vd(r,i);tr(u,`No resize handles found for group id "${r}"`);const d=u.map(h=>{const m=h.getAttribute(Pn.resizeHandleId);tr(m,"Resize handle element has no handle id attribute");const[b,g]=Gz(r,m,l,i);if(b==null||g==null)return()=>{};const p=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const v=l.findIndex(_=>_.id===b);if(v>=0){const _=l[v];tr(_,`No panel data found for index ${v}`);const w=n[v],{collapsedSize:C=0,collapsible:A,minSize:E=0}=_.constraints;if(w!=null&&A){const S=rd({delta:Di(w,C)?E-C:C-w,initialLayout:n,panelConstraints:l.map(k=>k.constraints),pivotIndices:HR(r,m,i),prevLayout:n,trigger:"keyboard"});n!==S&&a(S)}}break}}};return h.addEventListener("keydown",p),()=>{h.removeEventListener("keydown",p)}});return()=>{d.forEach(h=>h())}},[i,t,e,r,n,s,a])}function bC(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function zR(t,e){const r=t==="horizontal",{x:n,y:s}=Lm(e);return r?n:s}function Kz(t,e,r,n,s){const i=r==="horizontal",a=Mm(e,s);tr(a,`No resize handle element found for id "${e}"`);const o=a.getAttribute(Pn.groupId);tr(o,"Resize handle element has no group id attribute");let{initialCursorPosition:l}=n;const c=zR(r,t),u=UR(o,s);tr(u,`No group element found for id "${o}"`);const d=u.getBoundingClientRect(),h=i?d.width:d.height;return(c-l)/h*100}function Yz(t,e,r,n,s,i){if(NR(t)){const a=r==="horizontal";let o=0;t.shiftKey?o=100:s!=null?o=s:o=10;let l=0;switch(t.key){case"ArrowDown":l=a?0:o;break;case"ArrowLeft":l=a?-o:0;break;case"ArrowRight":l=a?o:0;break;case"ArrowUp":l=a?0:-o;break;case"End":l=100;break;case"Home":l=-100;break}return l}else return n==null?0:Kz(t,e,r,n,i)}function Xz({panelDataArray:t}){const e=Array(t.length),r=t.map(i=>i.constraints);let n=0,s=100;for(let i=0;i<t.length;i++){const a=r[i];tr(a,`Panel constraints not found for index ${i}`);const{defaultSize:o}=a;o!=null&&(n++,e[i]=o,s-=o)}for(let i=0;i<t.length;i++){const a=r[i];tr(a,`Panel constraints not found for index ${i}`);const{defaultSize:o}=a;if(o!=null)continue;const l=t.length-n,c=s/l;n++,e[i]=c,s-=c}return e}function Cc(t,e,r){e.forEach((n,s)=>{const i=t[s];tr(i,`Panel data not found for index ${s}`);const{callbacks:a,constraints:o,id:l}=i,{collapsedSize:c=0,collapsible:u}=o,d=r[l];if(d==null||n!==d){r[l]=n;const{onCollapse:h,onExpand:m,onResize:b}=a;b&&b(n,d),u&&(h||m)&&(m&&(d==null||ia(d,c))&&!ia(n,c)&&m(),h&&(d==null||!ia(d,c))&&ia(n,c)&&h())}})}function xf(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!=e[r])return!1;return!0}function Jz({defaultSize:t,dragState:e,layout:r,panelData:n,panelIndex:s,precision:i=3}){const a=r[s];let o;return a==null?o=t!=null?t.toPrecision(i):"1":n.length===1?o="1":o=a.toPrecision(i),{flexBasis:0,flexGrow:o,flexShrink:1,overflow:"hidden",pointerEvents:e!==null?"none":void 0}}function Qz(t,e=10){let r=null;return(...s)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{t(...s)},e)}}function vC(t){try{if(typeof localStorage<"u")t.getItem=e=>localStorage.getItem(e),t.setItem=(e,r)=>{localStorage.setItem(e,r)};else throw new Error("localStorage not supported in this environment")}catch(e){console.error(e),t.getItem=()=>null,t.setItem=()=>{}}}function VR(t){return`react-resizable-panels:${t}`}function GR(t){return t.map(e=>{const{constraints:r,id:n,idIsFromProps:s,order:i}=e;return s?n:i?`${i}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((e,r)=>e.localeCompare(r)).join(",")}function qR(t,e){try{const r=VR(t),n=e.getItem(r);if(n){const s=JSON.parse(n);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function Zz(t,e,r){var n,s;const i=(n=qR(t,r))!==null&&n!==void 0?n:{},a=GR(e);return(s=i[a])!==null&&s!==void 0?s:null}function eV(t,e,r,n,s){var i;const a=VR(t),o=GR(e),l=(i=qR(t,s))!==null&&i!==void 0?i:{};l[o]={expandToSizes:Object.fromEntries(r.entries()),layout:n};try{s.setItem(a,JSON.stringify(l))}catch(c){console.error(c)}}function yC({layout:t,panelConstraints:e}){const r=[...t],n=r.reduce((i,a)=>i+a,0);if(r.length!==e.length)throw Error(`Invalid ${e.length} panel layout: ${r.map(i=>`${i}%`).join(", ")}`);
48if(!Di(n,100)&&r.length>0)for(let i=0;i<e.length;i++){const a=r[i];tr(a!=null,`No layout data found for index ${i}`);const o=100/n*a;r[i]=o}let s=0;for(let i=0;i<e.length;i++){const a=r[i];tr(a!=null,`No layout data found for index ${i}`);const o=Wc({panelConstraints:e,panelIndex:i,size:a});a!=o&&(s+=a-o,r[i]=o)}if(!Di(s,0))for(let i=0;i<e.length;i++){const a=r[i];tr(a!=null,`No layout data found for index ${i}`);const o=a+s,l=Wc({panelConstraints:e,panelIndex:i,size:o});if(a!==l&&(s-=l-a,r[i]=l,Di(s,0)))break}return r}const tV=100,nd={getItem:t=>(vC(nd),nd.getItem(t)),setItem:(t,e)=>{vC(nd),nd.setItem(t,e)}},_C={};function KR({autoSaveId:t=null,children:e,className:r="",direction:n,forwardedRef:s,id:i=null,onLayout:a=null,keyboardResizeBy:o=null,storage:l=nd,style:c,tagName:u="div",...d}){const h=l0(i),m=x.useRef(null),[b,g]=x.useState(null),[p,y]=x.useState([]),v=Uz(),_=x.useRef({}),w=x.useRef(new Map),C=x.useRef(0),A=x.useRef({autoSaveId:t,direction:n,dragState:b,id:h,keyboardResizeBy:o,onLayout:a,storage:l}),E=x.useRef({layout:p,panelDataArray:[],panelDataArrayChanged:!1});x.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),x.useImperativeHandle(s,()=>({getId:()=>A.current.id,getLayout:()=>{const{layout:K}=E.current;return K},setLayout:K=>{const{onLayout:ie}=A.current,{layout:se,panelDataArray:fe}=E.current,Y=yC({layout:K,panelConstraints:fe.map(I=>I.constraints)});bC(se,Y)||(y(Y),E.current.layout=Y,ie&&ie(Y),Cc(fe,Y,_.current))}}),[]),Ql(()=>{A.current.autoSaveId=t,A.current.direction=n,A.current.dragState=b,A.current.id=h,A.current.onLayout=a,A.current.storage=l}),qz({committedValuesRef:A,eagerValuesRef:E,groupId:h,layout:p,panelDataArray:E.current.panelDataArray,setLayout:y,panelGroupElement:m.current}),x.useEffect(()=>{const{panelDataArray:K}=E.current;if(t){if(p.length===0||p.length!==K.length)return;let ie=_C[t];ie==null&&(ie=Qz(eV,tV),_C[t]=ie);const se=[...K],fe=new Map(w.current);ie(t,se,fe,p,l)}},[t,p,l]),x.useEffect(()=>{});const S=x.useCallback(K=>{const{onLayout:ie}=A.current,{layout:se,panelDataArray:fe}=E.current;if(K.constraints.collapsible){const Y=fe.map(ae=>ae.constraints),{collapsedSize:I=0,panelSize:z,pivotIndices:q}=Cl(fe,K,se);if(tr(z!=null,`Panel size not found for panel "${K.id}"`),!ia(z,I)){w.current.set(K.id,z);const ee=Rc(fe,K)===fe.length-1?z-I:I-z,le=rd({delta:ee,initialLayout:se,panelConstraints:Y,pivotIndices:q,prevLayout:se,trigger:"imperative-api"});xf(se,le)||(y(le),E.current.layout=le,ie&&ie(le),Cc(fe,le,_.current))}}},[]),k=x.useCallback((K,ie)=>{const{onLayout:se}=A.current,{layout:fe,panelDataArray:Y}=E.current;if(K.constraints.collapsible){const I=Y.map(ve=>ve.constraints),{collapsedSize:z=0,panelSize:q=0,minSize:ae=0,pivotIndices:ee}=Cl(Y,K,fe),le=ie??ae;if(ia(q,z)){const ve=w.current.get(K.id),ye=ve!=null&&ve>=le?ve:le,we=Rc(Y,K)===Y.length-1?q-ye:ye-q,pe=rd({delta:we,initialLayout:fe,panelConstraints:I,pivotIndices:ee,prevLayout:fe,trigger:"imperative-api"});xf(fe,pe)||(y(pe),E.current.layout=pe,se&&se(pe),Cc(Y,pe,_.current))}}},[]),O=x.useCallback(K=>{const{layout:ie,panelDataArray:se}=E.current,{panelSize:fe}=Cl(se,K,ie);return tr(fe!=null,`Panel size not found for panel "${K.id}"`),fe},[]),T=x.useCallback((K,ie)=>{const{panelDataArray:se}=E.current,fe=Rc(se,K);return Jz({defaultSize:ie,dragState:b,layout:p,panelData:se,panelIndex:fe})},[b,p]),R=x.useCallback(K=>{const{layout:ie,panelDataArray:se}=E.current,{collapsedSize:fe=0,collapsible:Y,panelSize:I}=Cl(se,K,ie);return tr(I!=null,`Panel size not found for panel "${K.id}"`),Y===!0&&ia(I,fe)},[]),N=x.useCallback(K=>{const{layout:ie,panelDataArray:se}=E.current,{collapsedSize:fe=0,collapsible:Y,panelSize:I}=Cl(se,K,ie);return tr(I!=null,`Panel size not found for panel "${K.id}"`),!Y||cc(I,fe)>0},[]),M=x.useCallback(K=>{const{panelDataArray:ie}=E.current;ie.push(K),ie.sort((se,fe)=>{const Y=se.order,I=fe.order;return Y==null&&I==null?0:Y==null?-1:I==null?1:Y-I}),E.current.panelDataArrayChanged=!0,v()},[v]);Ql(()=>{if(E.current.panelDataArrayChanged){E.current.panelDataArrayChanged=!1;const{autoSaveId:K,onLayout:ie,storage:se}=A.current,{layout:fe,panelDataArray:Y}=E.current;let I=null;if(K){const q=Zz(K,Y,se);
48q&&(w.current=new Map(Object.entries(q.expandToSizes)),I=q.layout)}I==null&&(I=Xz({panelDataArray:Y}));const z=yC({layout:I,panelConstraints:Y.map(q=>q.constraints)});bC(fe,z)||(y(z),E.current.layout=z,ie&&ie(z),Cc(Y,z,_.current))}}),Ql(()=>{const K=E.current;return()=>{K.layout=[]}},[]);const B=x.useCallback(K=>{let ie=!1;const se=m.current;return se&&window.getComputedStyle(se,null).getPropertyValue("direction")==="rtl"&&(ie=!0),function(Y){Y.preventDefault();const I=m.current;if(!I)return()=>null;const{direction:z,dragState:q,id:ae,keyboardResizeBy:ee,onLayout:le}=A.current,{layout:ve,panelDataArray:ye}=E.current,{initialLayout:Ae}=q??{},we=HR(ae,K,I);let pe=Yz(Y,K,z,q,ee,I);const Ye=z==="horizontal";Ye&&ie&&(pe=-pe);const ft=ye.map(nt=>nt.constraints),pt=rd({delta:pe,initialLayout:Ae??ve,panelConstraints:ft,pivotIndices:we,prevLayout:ve,trigger:NR(Y)?"keyboard":"mouse-or-touch"}),Lt=!xf(ve,pt);(LR(Y)||DR(Y))&&C.current!=pe&&(C.current=pe,!Lt&&pe!==0?Ye?yb(K,pe<0?OR:jR):yb(K,pe<0?$R:BR):yb(K,0)),Lt&&(y(pt),E.current.layout=pt,le&&le(pt),Cc(ye,pt,_.current))}},[]),U=x.useCallback((K,ie)=>{const{onLayout:se}=A.current,{layout:fe,panelDataArray:Y}=E.current,I=Y.map(ve=>ve.constraints),{panelSize:z,pivotIndices:q}=Cl(Y,K,fe);tr(z!=null,`Panel size not found for panel "${K.id}"`);const ee=Rc(Y,K)===Y.length-1?z-ie:ie-z,le=rd({delta:ee,initialLayout:fe,panelConstraints:I,pivotIndices:q,prevLayout:fe,trigger:"imperative-api"});xf(fe,le)||(y(le),E.current.layout=le,se&&se(le),Cc(Y,le,_.current))},[]),X=x.useCallback((K,ie)=>{const{layout:se,panelDataArray:fe}=E.current,{collapsedSize:Y=0,collapsible:I}=ie,{collapsedSize:z=0,collapsible:q,maxSize:ae=100,minSize:ee=0}=K.constraints,{panelSize:le}=Cl(fe,K,se);le!=null&&(I&&q&&ia(le,Y)?ia(Y,z)||U(K,z):le<ee?U(K,ee):le>ae&&U(K,ae))},[U]),oe=x.useCallback((K,ie)=>{const{direction:se}=A.current,{layout:fe}=E.current;if(!m.current)return;const Y=Mm(K,m.current);tr(Y,`Drag handle element not found for id "${K}"`);const I=zR(se,ie);g({dragHandleId:K,dragHandleRect:Y.getBoundingClientRect(),initialCursorPosition:I,initialLayout:fe})},[]),L=x.useCallback(()=>{g(null)},[]),F=x.useCallback(K=>{const{panelDataArray:ie}=E.current,se=Rc(ie,K);se>=0&&(ie.splice(se,1),delete _.current[K.id],E.current.panelDataArrayChanged=!0,v())},[v]),V=x.useMemo(()=>({collapsePanel:S,direction:n,dragState:b,expandPanel:k,getPanelSize:O,getPanelStyle:T,groupId:h,isPanelCollapsed:R,isPanelExpanded:N,reevaluatePanelConstraints:X,registerPanel:M,registerResizeHandle:B,resizePanel:U,startDragging:oe,stopDragging:L,unregisterPanel:F,panelGroupElement:m.current}),[S,b,n,k,O,T,h,R,N,X,M,B,U,oe,L,F]),Z={display:"flex",flexDirection:n==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return x.createElement(Nm.Provider,{value:V},x.createElement(u,{...d,children:e,className:r,id:i,ref:m,style:{...Z,...c},[Pn.group]:"",[Pn.groupDirection]:n,[Pn.groupId]:h}))}const wy=x.forwardRef((t,e)=>x.createElement(KR,{...t,forwardedRef:e}));KR.displayName="PanelGroup";wy.displayName="forwardRef(PanelGroup)";function Rc(t,e){return t.findIndex(r=>r===e||r.id===e.id)}function Cl(t,e,r){const n=Rc(t,e),i=n===t.length-1?[n-1,n]:[n,n+1],a=r[n];return{...e.constraints,panelSize:a,pivotIndices:i}}function rV({disabled:t,handleId:e,resizeHandler:r,panelGroupElement:n}){x.useEffect(()=>{if(t||r==null||n==null)return;const s=Mm(e,n);if(s==null)return;const i=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),r(a);break}case"F6":{a.preventDefault();const o=s.getAttribute(Pn.groupId);tr(o,`No group element found for id "${o}"`);const l=Vd(o,n),c=WR(o,e,n);tr(c!==null,`No resize element found for id "${e}"`);const u=a.shiftKey?c>0?c-1:l.length-1:c+1<l.length?c+1:0;l[u].focus();break}}};return s.addEventListener("keydown",i),()=>{s.removeEventListener("keydown",i)}},[n,t,e,r])}function Sy({children:t=null,className:e="",disabled:r=!1,hitAreaMargins:n,id:s,onBlur:i,onClick:a,onDragging:o,onFocus:l,onPointerDown:c,onPointerUp:u,style:d={},tabIndex:h=0,tagName:m="div",...b}){var g,p;const y=x.useRef(null),v=x.useRef({onClick:a,onDragging:o,onPointerDown:c,onPointerUp:u});x.useEffect(()=>{v.current.onClick=a,v.current.onDragging=o,v.current.onPointerDown=c,v.current.onPointerUp=u});const _=x.useContext(Nm);if(_===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:w,groupId:C,registerResizeHandle:A,startDragging:E,stopDragging:S,panelGroupElement:k}=_,O=l0(s),[T,R]=x.useState("inactive"),[N,M]=x.useState(!1),[B,U]=x.useState(null),X=x.useRef({state:T});Ql(()=>{X.current.state=T}),x.useEffect(()=>{if(r)U(null);else{const V=A(O);U(()=>V)}},[r,O,A]);const oe=(g=n?.coarse)!==null&&g!==void 0?g:15,L=(p=n?.fine)!==null&&p!==void 0?p:5;x.useEffect(()=>{if(r||B==null)return;const V=y.current;tr(V,"Element ref not attached");let Z=!1;return Wz(O,V,w,{coarse:oe,fine:L},(ie,se,fe)=>{if(!se){R("inactive");return}switch(ie){case"down":{R("drag"),Z=!1,tr(fe,'Expected event to be defined for "down" action'),E(O,fe);const{onDragging:Y,onPointerDown:I}=v.current;Y?.(!0),I?.();break}case"move":{const{state:Y}=X.current;Z=!0,Y!=="drag"&&R("hover"),tr(fe,'Expected event to be defined for "move" action'),B(fe);break}case"up":{R("hover"),S();const{onClick:Y,onDragging:I,onPointerUp:z}=v.current;I?.(!1),z?.(),Z||Y?.();break}}})},[oe,w,r,L,A,O,B,E,S]),rV({disabled:r,handleId:O,resizeHandler:B,panelGroupElement:k});const F={touchAction:"none",userSelect:"none"};return x.createElement(m,{...b,children:t,className:e,id:s,onBlur:()=>{M(!1),i?.()},onFocus:()=>{M(!0),l?.()},ref:y,role:"separator",style:{...F,...d},tabIndex:h,[Pn.groupDirection]:w,[Pn.groupId]:C,[Pn.resizeHandle]:"",[Pn.resizeHandleActive]:T==="drag"?"pointer":N?"keyboard":void 0,[Pn.resizeHandleEnabled]:!r,[Pn.resizeHandleId]:O,[Pn.resizeHandleState]:T})}Sy.displayName="PanelResizeHandle";const xC=x.memo(({className:t,children:e})=>f.jsx("div",{className:ue("flex items-center gap-2 bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary border-b border-bolt-elements-borderColor px-4 py-1 min-h-[34px] text-sm",t),children:e}));function nV(){return globalThis.innerWidth<640}var d0="ContextMenu",[sV]=fE(d0,[uE]),li=uE(),[iV,YR]=sV(d0),XR=t=>{const{__scopeContextMenu:e,children:r,onOpenChange:n,dir:s,modal:i=!0}=t,[a,o]=x.useState(!1),l=li(e),c=rO(n),u=x.useCallback(d=>{o(d),c(d)},[c]);return f.jsx(iV,{scope:e,open:a,onOpenChange:u,modal:i,children:f.jsx(N2,{...l,dir:s,open:a,onOpenChange:u,modal:i,children:r})})};XR.displayName=d0;var JR="ContextMenuTrigger",QR=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,disabled:n=!1,...s}=t,i=YR(JR,r),a=li(r),o=x.useRef({x:0,y:0}),l=x.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...o.current})}),c=x.useRef(0),u=x.useCallback(()=>window.clearTimeout(c.current),[]),d=h=>{o.current={x:h.clientX,y:h.clientY},i.onOpenChange(!0)};return x.useEffect(()=>u,[u]),x.useEffect(()=>void(n&&u()),[n,u]),f.jsxs(f.Fragment,{children:[f.jsx(L2,{...a,virtualRef:l}),f.jsx(i_.span,{"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,...s,ref:e,style:{WebkitTouchCallout:"none",...t.style},onContextMenu:n?t.onContextMenu:Lo(t.onContextMenu,h=>{u(),d(h),h.preventDefault()}),onPointerDown:n?t.onPointerDown:Lo(t.onPointerDown,wf(h=>{u(),c.current=window.setTimeout(()=>d(h),700)})),onPointerMove:n?t.onPointerMove:Lo(t.onPointerMove,wf(u)),onPointerCancel:n?t.onPointerCancel:Lo(t.onPointerCancel,wf(u)),onPointerUp:n?t.onPointerUp:Lo(t.onPointerUp,wf(u))})]})});QR.displayName=JR;var oV="ContextMenuPortal",ZR=t=>{const{__scopeContextMenu:e,...r}=t,n=li(e);return f.jsx(D2,{...n,...r})};ZR.displayName=oV;var eI="ContextMenuContent",tI=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=YR(eI,r),i=li(r),a=x.useRef(!1);return f.jsx(M2,{...i,...n,ref:e,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:o=>{t.onCloseAutoFocus?.(o),!o.defaultPrevented&&a.current&&o.preventDefault(),a.current=!1},onInteractOutside:o=>{t.onInteractOutside?.(o),!o.defaultPrevented&&!s.modal&&(a.current=!0)},style:{...t.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tI.displayName=eI;var aV="ContextMenuGroup",rI=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(O2,{...s,...n,ref:e})});rI.displayName=aV;var lV="ContextMenuLabel",cV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx($2,{...s,...n,ref:e})});cV.displayName=lV;var uV="ContextMenuItem",nI=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(j2,{...s,...n,ref:e})});nI.displayName=uV;var dV="ContextMenuCheckboxItem",hV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(B2,{...s,...n,ref:e})});hV.displayName=dV;var fV="ContextMenuRadioGroup",pV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(F2,{...s,...n,ref:e})});pV.displayName=fV;var mV="ContextMenuRadioItem",gV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(W2,{...s,...n,ref:e})});gV.displayName=mV;var bV="ContextMenuItemIndicator",vV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(H2,{...s,...n,ref:e})});vV.displayName=bV;var yV="ContextMenuSeparator",_V=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(U2,{...s,...n,ref:e})});_V.displayName=yV;var xV="ContextMenuArrow",wV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(z2,{...s,...n,ref:e})});wV.displayName=xV;var SV="ContextMenuSubTrigger",CV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(V2,{...s,...n,ref:e})});CV.displayName=SV;var AV="ContextMenuSubContent",EV=x.forwardRef((t,e)=>{const{__scopeContextMenu:r,...n}=t,s=li(r);return f.jsx(G2,{...s,...n,ref:e,style:{...t.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});EV.displayName=AV;function wf(t){return e=>e.pointerType!=="mouse"?t(e):void 0}var kV=XR,PV=QR,TV=ZR,RV=tI,Sf=rI,IV=nI;const Qo=ya("FileTree"),sI=8,NV=[/\/node_modules\//,/\/\.next/,/\/\.astro/,/(?:^|\/)\.cloudmysite(?:\/|$)/,/(?:^|\/)\.github(?:\/|$)/,/(?:^|\/)wrangler\.toml$/],iI=x.memo(({files:t={},onFileSelect:e,selectedFile:r,rootFolder:n,hideRoot:s=!1,collapsed:i=!1,allowFolderSelection:a=!1,hiddenFiles:o,className:l,unsavedFiles:c,fileHistory:u={}})=>{gu.trace("FileTree");const d=x.useMemo(()=>[...NV,...o??[]],[o]),h=x.useMemo(()=>
48MV(t,n,s,d),[t,n,s,d]),[m,b]=x.useState(()=>i?new Set(h.filter(_=>_.kind==="folder").map(_=>_.fullPath)):new Set);x.useEffect(()=>{if(i){b(new Set(h.filter(_=>_.kind==="folder").map(_=>_.fullPath)));return}b(_=>{const w=new Set;for(const C of h)C.kind==="folder"&&_.has(C.fullPath)&&w.add(C.fullPath);return w})},[h,i]);const g=x.useMemo(()=>{const _=[];let w=Number.MAX_SAFE_INTEGER;for(const C of h){const A=C.depth;w===A&&(w=Number.MAX_SAFE_INTEGER),m.has(C.fullPath)&&(w=Math.min(w,A)),!(w<A)&&_.push(C)}return _},[h,m]),p=_=>{b(w=>{const C=new Set(w);return C.has(_)?C.delete(_):C.add(_),C})},y=_=>{try{navigator.clipboard.writeText(_.fullPath)}catch(w){Qo.error(w)}},v=_=>{try{navigator.clipboard.writeText(_.fullPath.substring((n||"").length))}catch(w){Qo.error(w)}};return f.jsx("div",{className:ue("text-sm",l,"overflow-y-auto modern-scrollbar"),children:g.map(_=>{switch(_.kind){case"file":return f.jsx(DV,{selected:r===_.fullPath,file:_,unsavedChanges:c instanceof Set&&c.has(_.fullPath),fileHistory:u,onCopyPath:()=>{y(_)},onCopyRelativePath:()=>{v(_)},onClick:()=>{e?.(_.fullPath)}},_.id);case"folder":return f.jsx(LV,{folder:_,selected:a&&r===_.fullPath,collapsed:m.has(_.fullPath),onCopyPath:()=>{y(_)},onCopyRelativePath:()=>{v(_)},onClick:()=>{p(_.fullPath)}},_.id);default:return}})})});function Ko({onSelect:t,children:e}){return f.jsxs(IV,{onSelect:t,className:"flex items-center gap-2 px-2 py-1.5 outline-0 text-sm text-bolt-elements-textPrimary cursor-pointer ws-nowrap text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive hover:bg-bolt-elements-item-backgroundActive rounded-md",children:[f.jsx("span",{className:"size-4 shrink-0"}),f.jsx("span",{children:e})]})}function wC({depth:t,placeholder:e,initialValue:r="",onSubmit:n,onCancel:s}){const i=x.useRef(null);x.useEffect(()=>{const o=setTimeout(()=>{i.current&&(i.current.focus(),r&&(i.current.value=r,i.current.select()))},50);return()=>clearTimeout(o)},[r]);const a=o=>{if(o.key==="Enter"){const l=i.current?.value.trim();l&&n(l)}else o.key==="Escape"&&s()};return f.jsxs("div",{className:"flex items-center w-full px-2 bg-bolt-elements-background-depth-4 border border-bolt-elements-item-contentAccent py-0.5 text-bolt-elements-textPrimary",style:{paddingLeft:`${6+t*sI}px`},children:[f.jsx("div",{className:"scale-120 shrink-0 i-ph:file-plus text-bolt-elements-textTertiary"}),f.jsx("input",{ref:i,type:"text",className:"ml-2 flex-1 bg-transparent border-none outline-none py-0.5 text-sm text-bolt-elements-textPrimary placeholder:text-bolt-elements-textTertiary min-w-0",placeholder:e,onKeyDown:a,onBlur:()=>{setTimeout(()=>{document.activeElement!==i.current&&s()},100)}})]})}function oI({onCopyPath:t,onCopyRelativePath:e,fullPath:r,children:n}){const[s,i]=x.useState(!1),[a,o]=x.useState(!1),[l,c]=x.useState(!1),u=x.useMemo(()=>r.split("/").length,[r]),d=x.useMemo(()=>ta.basename(r),[r]),h=x.useMemo(()=>{const k=j.files.get()[r];return!k||k.type==="folder"},[r]),m=x.useMemo(()=>h?r:ta.dirname(r),[r,h]),b=x.useCallback(S=>{S.preventDefault(),S.stopPropagation(),c(!0)},[]),g=x.useCallback(S=>{S.preventDefault(),S.stopPropagation(),c(!1)},[]),p=x.useCallback(async S=>{S.preventDefault(),S.stopPropagation();const O=Array.from(S.dataTransfer.items).filter(T=>T.kind==="file");for(const T of O){const R=T.getAsFile();if(R)try{const N=ta.join(r,R.name),M=await R.arrayBuffer(),B=new Uint8Array(M);await j.createFile(N,B)?Se.success(`File ${R.name} uploaded successfully`):Se.error(`Failed to upload file ${R.name}`)}catch(N){Se.error(`Error uploading ${R.name}`),Qo.error(N)}}c(!1)},[r]),y=async S=>{const k=ta.join(m,S);await j.createFile(k,"")?Se.success("File created successfully"):Se.error("Failed to create file"),i(!1)},v=async S=>{const k=ta.join(m,S);await j.createFolder(k)?Se.success("Folder created successfully"):Se.error("Failed to create folder"),o(!1)},_=async()=>{try{if(!confirm(`Are you sure you want to delete ${h?"folder":"file"}: ${d}?`))return;let S;h?S=await j.deleteFolder(r):S=await j.deleteFile(r),S?Se.success(`${h?"Folder":"File"} deleted successfully`):Se.error(`Failed to delete ${h?"folder":"file"}`)}catch(S){Se.error(`Error deleting ${h?"folder":"file"}`),Qo.error(S)}},w=()=>{try{if(h)return;j.lockFile(r)?Se.success("File locked successfully"):Se.error("Failed to lock file")}catch(S){Se.error("Error locking file"),Qo.error(S)}},C=()=>{try{if(h)return;j.unlockFile(r)?Se.success("File unlocked successfully"):Se.error("Failed to unlock file")}catch(S){Se.error("Error unlocking file"),Qo.error(S)}},A=()=>{try{if(!h)return;j.lockFolder(r)?Se.success("Folder locked successfully"):Se.error("Failed to lock folder")}catch(S){Se.error("Error locking folder"),Qo.error(S)}},E=()=>{try{if(!h)return;j.unlockFolder(r)?Se.success("Folder unlocked successfully"):Se.error("Failed to unlock folder")}catch(S){Se.error("Error unlocking folder"),Qo.error(S)}};return f.jsxs(f.Fragment,{children:[f.jsxs(kV,{children:[f.jsx(PV,{children:f.jsx("div",{onDragOver:b,onDragLeave:g,onDrop:p,className:ue("relative",{"bg-bolt-elements-background-depth-2 border border-dashed border-bolt-elements-item-contentAccent rounded-md":l}),children:n})}),f.jsx(TV,{children:f.jsxs(RV,{style:{zIndex:998}
48,className:"border border-bolt-elements-borderColor rounded-md z-context-menu bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-2 data-[state=open]:animate-in animate-duration-100 data-[state=open]:fade-in-0 data-[state=open]:zoom-in-98 w-56",children:[f.jsxs(Sf,{className:"p-1 border-b-px border-solid border-bolt-elements-borderColor",children:[f.jsx(Ko,{onSelect:()=>i(!0),children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:file-plus"}),"New File"]})}),f.jsx(Ko,{onSelect:()=>o(!0),children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:folder-plus"}),"New Folder"]})})]}),f.jsxs(Sf,{className:"p-1",children:[f.jsx(Ko,{onSelect:t,children:"Copy path"}),f.jsx(Ko,{onSelect:e,children:"Copy relative path"})]}),f.jsx(Sf,{className:"p-1 border-t-px border-solid border-bolt-elements-borderColor",children:h?f.jsxs(f.Fragment,{children:[f.jsx(Ko,{onSelect:A,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:lock-simple"}),"Lock Folder"]})}),f.jsx(Ko,{onSelect:E,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:lock-key-open"}),"Unlock Folder"]})})]}):f.jsxs(f.Fragment,{children:[f.jsx(Ko,{onSelect:w,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:lock-simple"}),"Lock File"]})}),f.jsx(Ko,{onSelect:C,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:lock-key-open"}),"Unlock File"]})})]})}),f.jsx(Sf,{className:"p-1 border-t-px border-solid border-bolt-elements-borderColor",children:f.jsx(Ko,{onSelect:_,children:f.jsxs("div",{className:"flex items-center gap-2 text-red-500",children:[f.jsx("div",{className:"i-ph:trash"}),"Delete ",h?"Folder":"File"]})})})]})})]}),s&&f.jsx(wC,{depth:u,placeholder:"Enter file name...",onSubmit:y,onCancel:()=>i(!1)}),a&&f.jsx(wC,{depth:u,placeholder:"Enter folder name...",onSubmit:v,onCancel:()=>o(!1)})]})}function LV({folder:t,collapsed:e,selected:r=!1,onCopyPath:n,onCopyRelativePath:s,onClick:i}){const{isLocked:a}=j.isFolderLocked(t.fullPath);return f.jsx(oI,{onCopyPath:n,onCopyRelativePath:s,fullPath:t.fullPath,children:f.jsx(aI,{className:ue("group",{"bg-transparent text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive hover:bg-bolt-elements-item-backgroundActive":!r,"bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":r}),depth:t.depth,iconClasses:ue({"i-ph:caret-right scale-98":e,"i-ph:caret-down scale-98":!e}),onClick:i,children:f.jsxs("div",{className:"flex items-center w-full",children:[f.jsx("div",{className:"flex-1 truncate pr-2",children:t.name}),a&&f.jsx("span",{className:ue("shrink-0","i-ph:lock-simple scale-80 text-red-500"),title:"Folder is locked"})]})})})}function DV({file:t,onClick:e,onCopyPath:r,onCopyRelativePath:n,selected:s,unsavedChanges:i=!1,fileHistory:a={}}
48){const{depth:o,name:l,fullPath:c}=t,{locked:u}=j.isFileLocked(c),d=a[c],{additions:h,deletions:m}=x.useMemo(()=>{if(!d?.originalContent)return{additions:0,deletions:0};const g=d.originalContent.replace(/\r\n/g,` 49`),p=d.versions[d.versions.length-1]?.content.replace(/\r\n/g,` 50`)||"";return g===p?{additions:0,deletions:0}:H1(g,p,{newlineIsToken:!1,ignoreWhitespace:!0,ignoreCase:!1}).reduce((v,_)=>(_.added&&(v.additions+=_.value.split(` 51`).length),_.removed&&(v.deletions+=_.value.split(` 52`).length),v),{additions:0,deletions:0})},[d]),b=h>0||m>0;return f.jsx(oI,{onCopyPath:r,onCopyRelativePath:n,fullPath:c,children:f.jsx(aI,{className:ue("group",{"bg-transparent hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-item-contentDefault":!s,"bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":s}),depth:o,iconClasses:ue("i-ph:file-duotone scale-98",{"group-hover:text-bolt-elements-item-contentActive":!s}),onClick:e,children:f.jsxs("div",{className:ue("flex items-center",{"group-hover:text-bolt-elements-item-contentActive":!s}),children:[f.jsx("div",{className:"flex-1 truncate pr-2",children:l}),f.jsxs("div",{className:"flex items-center gap-1",children:[b&&f.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[h>0&&f.jsxs("span",{className:"text-green-500",children:["+",h]}),m>0&&f.jsxs("span",{className:"text-red-500",children:["-",m]})]}),u&&f.jsx("span",{className:ue("shrink-0","i-ph:lock-simple scale-80 text-red-500"),title:"File is locked"}),i&&f.jsx("span",{className:"i-ph:circle-fill scale-68 shrink-0 text-orange-500"})]})]})})})}function aI({depth:t,iconClasses:e,onClick:r,className:n,children:s}){return f.jsxs("button",{className:ue("flex items-center gap-1.5 w-full pr-2 border-2 border-transparent text-faded py-0.5",n),style:{paddingLeft:`${6+t*sI}px`},onClick:()=>r?.(),children:[f.jsx("div",{className:ue("scale-120 shrink-0",e)}),f.jsx("div",{className:"truncate w-full text-left",children:s})]})}function MV(t,e="/",r,n){const s=new Set,i=[];let a=0;e==="/"&&!r&&(a=1,i.push({kind:"folder",name:"/",depth:0,id:0,fullPath:"/"}));for(const[o,l]of Object.entries(t)){const c=o.split("/").filter(b=>b),u=c.at(-1);if(!u||OV(o,u,n))continue;let d="",h=0,m=0;for(;h<c.length;){const b=c[h],g=d+=`/${b}`;if(!g.startsWith(e)||r&&g===e){h++;continue}h===c.length-1&&l?.type==="file"?i.push({kind:"file",id:i.length,name:b,fullPath:g,depth:m+a}):s.has(g)||(s.add(g),i.push({kind:"folder",id:i.length,name:b,fullPath:g,depth:m+a})),h++,m++}}return jV(e,i,r)}function OV(t,e,r){const n=t.replace(/\\/g,"/");return r.some(s=>typeof s=="string"?e===s:s.test(n))}function jV(t,e,r){Qo.trace("sortFileList");const n=new Map,s=new Map;e.sort((o,l)=>$V(o,l));for(const o of e){n.set(o.fullPath,o);const l=o.fullPath.slice(0,o.fullPath.lastIndexOf("/"));l!==t.slice(0,t.lastIndexOf("/"))&&(s.has(l)||s.set(l,[]),s.get(l)?.push(o))}const i=[],a=o=>{const l=n.get(o);l&&i.push(l);const c=s.get(o);if(c)for(const u of c)u.kind==="folder"?a(u.fullPath):i.push(u)};if(r){const o=s.get(t)||[];for(const l of o)a(l.fullPath)}else a(t);return i}function $V(t,e){return t.kind!==e.kind?t.kind==="folder"?-1:1:t.name.localeCompare(e.name,void 0,{numeric:!0,sensitivity:"base"})}const BV=new RegExp(`^${Za.split("/").slice(0,-1).join("/").replaceAll("/","\\/")}/`),FV={open:{y:0,opacity:1,transition:{duration:.15,ease:Ds}},close:{y:6,opacity:0,transition:{duration:.15,ease:Ds}}},WV=x.memo(({files:t,pathSegments:e=[],onFileSelect:r})=>{gu.trace("FileBreadcrumb");const[n,s]=x.useState(null),i=x.useRef(null),a=x.useRef([]),o=l=>{s(c=>c===l?null:l)};return x.useEffect(()=>{const l=c=>{n!==null&&!i.current?.contains(c.target)&&!a.current.some(u=>u?.contains(c.target))&&s(null)};return document.addEventListener("mousedown",l),()=>{document.removeEventListener("mousedown",l)}},[n]),t===void 0||e.length===0?null:f.jsx("div",{className:"flex",children:e.map((l,c)=>{const u=c===e.length-1,d=e.slice(0,c).join("/");if(!BV.test(d))return null;const h=n===c;return f.jsx("div",{className:"relative flex items-center",children:f.jsxs(q2,{open:h,modal:!1,children:[f.jsx(K2,{asChild:!0,children:f.jsxs("span",{ref:m=>{a.current[c]=m},className:ue("flex items-center gap-1.5 cursor-pointer shrink-0",{"text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary":!h,"text-bolt-elements-textPrimary underline":h,"pr-4":u}),onClick:()=>o(c),children:[u&&f.jsx("div",{className:"i-ph:file-duotone"}),l]})}),c>0&&!u&&f.jsx("span",{className:"i-ph:caret-right inline-block mx-1"}),f.jsx(Si,{children:h&&f.jsx(Y2,{children:f.jsx(X2,{className:"z-file-tree-breadcrumb",asChild:!0,align:"start",side:"bottom",avoidCollisions:!1,children:f.jsxs(ar.div,{ref:i,initial:"close",animate:"open",exit:"close",variants:FV,children:[f.jsx("div",{className:"rounded-lg overflow-hidden",children:f.jsx("div",{className:"max-h-[50vh] min-w-[300px] overflow-scroll bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor shadow-sm rounded-lg",children:f.jsx(iI,{files:t,hideRoot:!0,rootFolder:d,collapsed:!0,allowFolderSelection:!0,selectedFile:`${d}/${l}`,onFileSelect:m=>{s(null),r?.(m)}})})}),f.jsx(J2,{className:"fill-bolt-elements-borderColor"})]})})})})]})},c)})})});var lI={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(self,()=>(()=>{var r={};return(()=>{var n=r;Object.defineProperty(n,"__esModule",{value:!0}),n.FitAddon=void 0,n.FitAddon=class{activate(s){this._terminal=s}dispose(){}fit(){const s=this.proposeDimensions();if(!s||!this._terminal||isNaN(s.cols)||isNaN(s.rows))return;
52const i=this._terminal._core;this._terminal.rows===s.rows&&this._terminal.cols===s.cols||(i._renderService.clear(),this._terminal.resize(s.cols,s.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const s=this._terminal._core,i=s._renderService.dimensions;if(i.css.cell.width===0||i.css.cell.height===0)return;const a=this._terminal.options.scrollback===0?0:s.viewport.scrollBarWidth,o=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(o.getPropertyValue("height")),c=Math.max(0,parseInt(o.getPropertyValue("width"))),u=window.getComputedStyle(this._terminal.element),d=l-(parseInt(u.getPropertyValue("padding-top"))+parseInt(u.getPropertyValue("padding-bottom"))),h=c-(parseInt(u.getPropertyValue("padding-right"))+parseInt(u.getPropertyValue("padding-left")))-a;return{cols:Math.max(2,Math.floor(h/i.css.cell.width)),rows:Math.max(1,Math.floor(d/i.css.cell.height))}}}})(),r})())})(lI);var HV=lI.exports,cI={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(self,()=>(()=>{var r={6:(a,o)=>{function l(u){try{const d=new URL(u),h=d.password&&d.username?`${d.protocol}//${d.username}:${d.password}@${d.host}`:d.username?`${d.protocol}//${d.username}@${d.host}`:`${d.protocol}//${d.host}`;return u.toLocaleLowerCase().startsWith(h.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(o,"__esModule",{value:!0}),o.LinkComputer=o.WebLinkProvider=void 0,o.WebLinkProvider=class{constructor(u,d,h,m={}){this._terminal=u,this._regex=d,this._handler=h,this._options=m}provideLinks(u,d){const h=c.computeLink(u,this._regex,this._terminal,this._handler);d(this._addCallbacks(h))}_addCallbacks(u){return u.map(d=>(d.leave=this._options.leave,d.hover=(h,m)=>{if(this._options.hover){const{range:b}=d;this._options.hover(h,m,b)}},d))}};class c{static computeLink(d,h,m,b){const g=new RegExp(h.source,(h.flags||"")+"g"),[p,y]=c._getWindowedLineStrings(d-1,m),v=p.join("");let _;const w=[];for(;_=g.exec(v);){const C=_[0];if(!l(C))continue;const[A,E]=c._mapStrIdx(m,y,0,_.index),[S,k]=c._mapStrIdx(m,A,E,C.length);if(A===-1||E===-1||S===-1||k===-1)continue;const O={start:{x:E+1,y:A+1},end:{x:k,y:S+1}};w.push({range:O,text:C,activate:b})}return w}static _getWindowedLineStrings(d,h){let m,b=d,g=d,p=0,y="";const v=[];if(m=h.buffer.active.getLine(d)){const _=m.translateToString(!0);if(m.isWrapped&&_[0]!==" "){for(p=0;(m=h.buffer.active.getLine(--b))&&p<2048&&(y=m.translateToString(!0),p+=y.length,v.push(y),m.isWrapped&&y.indexOf(" ")===-1););v.reverse()}for(v.push(_),p=0;(m=h.buffer.active.getLine(++g))&&m.isWrapped&&p<2048&&(y=m.translateToString(!0),p+=y.length,v.push(y),y.indexOf(" ")===-1););}return[v,b]}static _mapStrIdx(d,h,m,b){const g=d.buffer.active,p=g.getNullCell();let y=m;for(;b;){const v=g.getLine(h);if(!v)return[-1,-1];for(let _=y;_<v.length;++_){v.getCell(_,p);const w=p.getChars();if(p.getWidth()&&(b-=w.length||1,_===v.length-1&&w==="")){const C=g.getLine(h+1);C&&C.isWrapped&&(C.getCell(0,p),p.getWidth()===2&&(b+=1))}if(b<0)return[h,_]}h++,y=0}return[h,y]}}o.LinkComputer=c}},n={};function s(a){var o=n[a];if(o!==void 0)return o.exports;var l=n[a]={exports:{}};return r[a](l,l.exports,s),l.exports}var i={};return(()=>{var a=i;Object.defineProperty(a,"__esModule",{value:!0}),a.WebLinksAddon=void 0;const o=s(6),l=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function c(u,d){const h=window.open();if(h){try{h.opener=null}catch{}h.location.href=d}else console.warn("Opening link blocked as opener could not be cleared")}a.WebLinksAddon=class{constructor(u=c,d={}){this._handler=u,this._options=d}activate(u){this._terminal=u;const d=this._options,h=d.urlRegex||l;this._linkProvider=this._terminal.registerLinkProvider(new o.WebLinkProvider(this._terminal,h,this._handler,d))}dispose(){this._linkProvider?.dispose()}}})(),i})())})(cI);var UV=cI.exports,uI={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(globalThis,()=>(()=>{var r={4567:function(a,o,l){var c=this&&this.__decorate||function(v,_,w,C){var A,E=arguments.length,S=E<3?_:C===null?C=Object.getOwnPropertyDescriptor(_,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,_,w,C);else for(var k=v.length-1;k>=0;k--)(A=v[k])&&(S=(E<3?A(S):E>3?A(_,w,S):A(_,w))||S);return E>3&&S&&Object.defineProperty(_,w,S),S},u=this&&this.__param||function(v,_){return function(w,C){_(w,C,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.AccessibilityManager=void 0;const d=l(9042),h=l(9924),m=l(844),b=l(4725),g=l(2585),p=l(3656);let y=o.AccessibilityManager=class extends m.Disposable{constructor(v,_,w,C){super(),this._terminal=v,this._coreBrowserService=w,this._renderService=C,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce
52="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let A=0;A<this._terminal.rows;A++)this._rowElements[A]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[A]);if(this._topBoundaryFocusListener=A=>this._handleBoundaryFocus(A,0),this._bottomBoundaryFocusListener=A=>this._handleBoundaryFocus(A,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new h.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(A=>this._handleResize(A.rows))),this.register(this._terminal.onRender(A=>this._refreshRows(A.start,A.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(A=>this._handleChar(A))),this.register(this._terminal.onLineFeed(()=>this._handleChar(` 53`))),this.register(this._terminal.onA11yTab(A=>this._handleTab(A))),this.register(this._terminal.onKey(A=>this._handleKey(A.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this.register((0,p.addDisposableDomListener)(document,"selectionchange",()=>this._handleSelectionChange())),this.register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,m.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(v){for(let _=0;_<v;_++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===` 54`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=d.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),/\p{Control}/u.test(v)||this._charsToConsume.push(v)}_refreshRows(v,_){this._liveRegionDebouncer.refresh(v,_,this._terminal.rows)}_renderRows(v,_){const w=this._terminal.buffer,C=w.lines.length.toString();for(let A=v;A<=_;A++){const E=w.lines.get(w.ydisp+A),S=[],k=E?.translateToString(!0,void 0,void 0,S)||"",O=(w.ydisp+A+1).toString(),T=this._rowElements[A];T&&(k.length===0?(T.innerText="Â ",this._rowColumns.set(T,[0,1])):(T.textContent=k,this._rowColumns.set(T,S)),T.setAttribute("aria-posinset",O),T.setAttribute("aria-setsize",C))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,_){const w=v.target,C=this._rowElements[_===0?1:this._rowElements.length-2];if(w.getAttribute("aria-posinset")===(_===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==C)return;let A,E;if(_===0?(A=w,E=this._rowElements.pop(),this._rowContainer.removeChild(E)):(A=this._rowElements.shift(),E=w,this._rowContainer.removeChild(A)),A.removeEventListener("focus",this._topBoundaryFocusListener),E.removeEventListener("focus",this._bottomBoundaryFocusListener),_===0){const S=this._createAccessibilityTreeNode();this._rowElements.unshift(S),this._rowContainer.insertAdjacentElement("afterbegin",S)}else{const S=this._createAccessibilityTreeNode();this._rowElements.push(S),this._rowContainer.appendChild(S)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(_===0?-1:1),this._rowElements[_===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let _={node:v.anchorNode,offset:v.anchorOffset},w={node:v.focusNode,offset:v.focusOffset};if((_.node.compareDocumentPosition(w.node)&Node.DOCUMENT_POSITION_PRECEDING||_.node===w.node&&_.offset>w.offset)&&([_,w]=[w,_]),_.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(_={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(_.node))return;const C=this._rowElements.slice(-1)[0];if(w.node.compareDocumentPosition(C)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(w={node:C,offset:C.textContent?.length??0}),!this._rowContainer.contains(w.node))return;const A=({node:k,offset:O})=>{const T=k instanceof Text?k.parentNode:k;let R=parseInt(T?.getAttribute("aria-posinset"),10)-1;
vendor: 23,821 bytes, lines 54-56
54if(isNaN(R))return console.warn("row is invalid. Race condition?"),null;const N=this._rowColumns.get(T);if(!N)return console.warn("columns is null. Race condition?"),null;let M=O<N.length?N[O]:N.slice(-1)[0]+1;return M>=this._terminal.cols&&(++R,M=0),{row:R,column:M}},E=A(_),S=A(w);if(E&&S){if(E.row>S.row||E.row===S.row&&E.column>=S.column)throw new Error("invalid range");this._terminal.select(E.column,E.row,(S.row-E.row)*this._terminal.cols-E.column+S.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let _=this._rowContainer.children.length;_<this._terminal.rows;_++)this._rowElements[_]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[_]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};o.AccessibilityManager=y=c([u(1,g.IInstantiationService),u(2,b.ICoreBrowserService),u(3,b.IRenderService)],y)},3614:(a,o)=>{function l(h){return h.replace(/\r?\n/g,"\r")}function c(h,m){return m?"\x1B[200~"+h+"\x1B[201~":h}function u(h,m,b,g){h=c(h=l(h),b.decPrivateModes.bracketedPasteMode&&g.rawOptions.ignoreBracketedPasteMode!==!0),b.triggerDataEvent(h,!0),m.value=""}function d(h,m,b){const g=b.getBoundingClientRect(),p=h.clientX-g.left-10,y=h.clientY-g.top-10;m.style.width="20px",m.style.height="20px",m.style.left=`${p}px`,m.style.top=`${y}px`,m.style.zIndex="1000",m.focus()}Object.defineProperty(o,"__esModule",{value:!0}),o.rightClickHandler=o.moveTextAreaUnderMouseCursor=o.paste=o.handlePasteEvent=o.copyHandler=o.bracketTextForPaste=o.prepareTextForTerminal=void 0,o.prepareTextForTerminal=l,o.bracketTextForPaste=c,o.copyHandler=function(h,m){h.clipboardData&&h.clipboardData.setData("text/plain",m.selectionText),h.preventDefault()},o.handlePasteEvent=function(h,m,b,g){h.stopPropagation(),h.clipboardData&&u(h.clipboardData.getData("text/plain"),m,b,g)},o.paste=u,o.moveTextAreaUnderMouseCursor=d,o.rightClickHandler=function(h,m,b,g,p){d(h,m,b),p&&g.rightClickSelect(h),m.value=g.selectionText,m.select()}},7239:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorContrastCache=void 0;const c=l(1505);o.ColorContrastCache=class{constructor(){this._color=new c.TwoKeyMap,this._css=new c.TwoKeyMap}setCss(u,d,h){this._css.set(u,d,h)}getCss(u,d){return this._css.get(u,d)}setColor(u,d,h){this._color.set(u,d,h)}getColor(u,d){return this._color.get(u,d)}clear(){this._color.clear(),this._css.clear()}}},3656:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.addDisposableDomListener=void 0,o.addDisposableDomListener=function(l,c,u,d){l.addEventListener(c,u,d);let h=!1;return{dispose:()=>{h||(h=!0,l.removeEventListener(c,u,d))}}}},3551:function(a,o,l){var c=this&&this.__decorate||function(y,v,_,w){var C,A=arguments.length,E=A<3?v:w===null?w=Object.getOwnPropertyDescriptor(v,_):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(y,v,_,w);else for(var S=y.length-1;S>=0;S--)(C=y[S])&&(E=(A<3?C(E):A>3?C(v,_,E):C(v,_))||E);return A>3&&E&&Object.defineProperty(v,_,E),E},u=this&&this.__param||function(y,v){return function(_,w){v(_,w,y)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Linkifier=void 0;const d=l(3656),h=l(8460),m=l(844),b=l(2585),g=l(4725);let p=o.Linkifier=class extends m.Disposable{get currentLink(){return this._currentLink}constructor(y,v,_,w,C){super(),this._element=y,this._mouseService=v,this._renderService=_,this._bufferService=w,this._linkProviderService=C,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new h.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new h.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,m.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,m.toDisposable)(()=>{this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this.register((0,d.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,d.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(y){this._lastMouseEvent=y;const v=this._positionFromMouseEvent(y,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const _=y.composedPath();for(let w=0;w<_.length;w++){const C=_[w];if(C.classList.contains("xterm"))break;if(C.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(y){if(this._activeLine!==y.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(y,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,y)||(this._clearCurrentLink(),this._askForLink(y,!0))}_askForLink(y,v){this._activeProviderReplies&&v||(this._activeProviderReplies?.forEach(w=>{w?.forEach(C=>{C.link.dispose&&C.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=y.y);let _=!1;for(const[w,C]of this._linkProviderService.linkProviders.entries())v?this._activeProviderReplies?.get(w)&&(_=this._checkLinkProviderResult(w,y,_)):C.provideLinks(y.y,A=>{if(this._isMouseOut)return;const E=A?.map(S=>({link:S}));this._activeProviderReplies?.set(w,E),_=this._checkLinkProviderResult(w,y,_),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(y.y,this._activeProviderReplies)})}_removeIntersectingLinks(y,v){const _=new Set;for(let w=0;w<v.size;w++){const C=v.get(w);if(C)for(let A=0;A<C.length;A++){const E=C[A],S=E.link.range.start.y<y?0:E.link.range.start.x,k=E.link.range.end.y>y?this._bufferService.cols:E.link.range.end.x;for(let O=S;O<=k;O++){if(_.has(O)){C.splice(A--,1);break}_.add(O)}}}}_checkLinkProviderResult(y,v,_){if(!this._activeProviderReplies)return _;const w=this._activeProviderReplies.get(y);let C=!1;for(let A=0;A<y;A++)this._activeProviderReplies.has(A)&&!this._activeProviderReplies.get(A)||(C=!0);if(!C&&w){const A=w.find(E=>this._linkAtPosition(E.link,v));A&&(_=!0,this._handleNewLink(A))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!_)for(let A=0;A<this._activeProviderReplies.size;A++){const E=this._activeProviderReplies.get(A)?.find(S=>this._linkAtPosition(S.link,v));if(E){_=!0,this._handleNewLink(E);break}}return _}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(y){if(!this._currentLink)return;const v=this._positionFromMouseEvent(y,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(y,this._currentLink.link.text)}_clearCurrentLink(y,v){this._currentLink&&this._lastMouseEvent&&(!y||!v||this._currentLink.link.range.start.y>=y&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,m.disposeArray)(this._linkCacheDisposables))}_handleNewLink(y){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(y.link,v)&&(this._currentLink=y,this._currentLink.state={decorations:{underline:y.link.decorations===void 0||y.link.decorations.underline,pointerCursor:y.link.decorations===void 0||y.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,y.link,this._lastMouseEvent),y.link.decorations={},Object.defineProperties(y.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:_=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==_&&(this._currentLink.state.decorations.pointerCursor=_,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",_))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:_=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==_&&(this._currentLink.state.decorations.underline=_,this._currentLink.state.isHovered&&this._fireUnderlineEvent(y.link,_))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(_=>{if(!this._currentLink)return;const w=_.start===0?0:_.start+1+this._bufferService.buffer.ydisp,C=this._bufferService.buffer.ydisp+1+_.end;if(this._currentLink.link.range.start.y>=w&&this._currentLink.link.range.end.y<=C&&(this._clearCurrentLink(w,C),this._lastMouseEvent)){const A=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);A&&this._askForLink(A,!1)}})))}_linkHover(y,v,_){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&y.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(_,v.text)}_fireUnderlineEvent(y,v){const _=y.range,w=this._bufferService.buffer.ydisp,C=this._createLinkUnderlineEvent(_.start.x-1,_.start.y-w-1,_.end.x,_.end.y-w-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(C)}_linkLeave(y,v,_){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&y.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(_,v.text)}_linkAtPosition(y,v){const _=y.range.start.y*this._bufferService.cols+y.range.start.x,w=y.range.end.y*this._bufferService.cols+y.range.end.x,C=v.y*this._bufferService.cols+v.x;return _<=C&&C<=w}_positionFromMouseEvent(y,v,_){const w=_.getCoords(y,v,this._bufferService.cols,this._bufferService.rows);if(w)return{x:w[0],y:w[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(y,v,_,w,C){return{x1:y,y1:v,x2:_,y2:w,cols:this._bufferService.cols,fg:C}}};o.Linkifier=p=c([u(1,g.IMouseService),u(2,g.IRenderService),u(3,b.IBufferService),u(4,g.ILinkProviderService)],p)},9042:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.tooMuchOutput=o.promptLabel=void 0,o.promptLabel="Terminal input",o.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(a,o,l){var c=this&&this.__decorate||function(g,p,y,v){var _,w=arguments.length,C=w<3?p:v===null?v=Object.getOwnPropertyDescriptor(p,y):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,p,y,v);else for(var A=g.length-1;A>=0;A--)(_=g[A])&&(C=(w<3?_(C):w>3?_(p,y,C):_(p,y))||C);return w>3&&C&&Object.defineProperty(p,y,C),C},u=this&&this.__param||function(g,p){return function(y,v){p(y,v,g)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkProvider=void 0;const d=l(511),h=l(2585);let m=o.OscLinkProvider=class{constructor(g,p,y){this._bufferService=g,this._optionsService=p,this._oscLinkService=y}provideLinks(g,p){const y=this._bufferService.buffer.lines.get(g-1);if(!y)return void p(void 0);const v=[],_=this._optionsService.rawOptions.linkHandler,w=new d.CellData,C=y.getTrimmedLength();let A=-1,E=-1,S=!1;for(let k=0;k<C;k++)if(E!==-1||y.hasContent(k)){if(y.loadCell(k,w),w.hasExtendedAttrs()&&w.extended.urlId){if(E===-1){E=k,A=w.extended.urlId;continue}S=w.extended.urlId!==A}else E!==-1&&(S=!0);if(S||E!==-1&&k===C-1){const O=this._oscLinkService.getLinkData(A)?.uri;if(O){const T={start:{x:E+1,y:g},end:{x:k+(S||k!==C-1?0:1),y:g}};let R=!1;if(!_?.allowNonHttpProtocols)try{const N=new URL(O);["http:","https:"].includes(N.protocol)||(R=!0)}catch{R=!0}R||v.push({text:O,range:T,activate:(N,M)=>_?_.activate(N,M,T):b(0,M),hover:(N,M)=>_?.hover?.(N,M,T),leave:(N,M)=>_?.leave?.(N,M,T)})}S=!1,w.hasExtendedAttrs()&&w.extended.urlId?(E=k,A=w.extended.urlId):(E=-1,A=-1)}}p(v)}};function b(g,p){if(confirm(`Do you want to navigate to ${p}? 55 56WARNING: This link could potentially be dangerous`)){const y=window.open();if(y){try{y.opener=null}catch{}y.location.href=p}else console.warn("Opening link blocked as opener could not be cleared")}}o.OscLinkProvider=m=c([u(0,h.IBufferService),u(1,h.IOptionsService),u(2,h.IOscLinkService)],m)},6193:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.RenderDebouncer=void 0,o.RenderDebouncer=class{constructor(l,c){this._renderCallback=l,this._coreBrowserService=c,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(l){return this._refreshCallbacks.push(l),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(l,c,u){this._rowCount=u,l=l!==void 0?l:0,c=c!==void 0?c:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,c):c,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const l=Math.max(this._rowStart,0),c=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,c),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const l of this._refreshCallbacks)l(0);this._refreshCallbacks=[]}}},3236:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const c=l(3614),u=l(3656),d=l(3551),h=l(9042),m=l(3730),b=l(1680),g=l(3107),p=l(5744),y=l(2950),v=l(1296),_=l(428),w=l(4269),C=l(5114),A=l(8934),E=l(3230),S=l(9312),k=l(4725),O=l(6731),T=l(8055),R=l(8969),N=l(8460),M=l(844),B=l(6114),U=l(8437),X=l(2584),oe=l(7399),L=l(5941),F=l(9074),V=l(2585),Z=l(5435),K=l(4567),ie=l(779);class se extends R.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(Y={}){super(Y),this.browser=B,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new M.MutableDisposable),this._onCursorMove=this.register(new N.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new N.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new N.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new N.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new N.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new N.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new N.EventEmitter),this._onBlur=this.register(new N.EventEmitter),this._onA11yCharEmitter=this.register(new N.EventEmitter),this._onA11yTabEmitter=this.register(new N.EventEmitter),this._onWillOpen=this.register(new N.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(F.DecorationService),this._instantiationService.setService(V.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(ie.LinkProviderService),this._instantiationService.setService(k.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(m.OscLinkProvider)),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((I,z)=>this.refresh(I,z))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(I=>this._reportWindowsOptions(I))),this.register(this._inputHandler.onColor(I=>this._handleColorEvent(I))),this.register((0,N.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,N.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,N.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,N.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(I=>this._afterResize(I.cols,I.rows))),this.register((0,M.toDisposable)(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}_handleColorEvent(Y){if(this._themeService)for(const I of Y){let z,q="";switch(I.index){case 256:z="foreground",q="10";break;case 257:z="background",q="11";break;case 258:z="cursor",q="12";break;default:z="ansi",q="4;"+I.index}switch(I.type){case 0:const ae=T.color.toColorRGB(z==="ansi"?this._themeService.colors.ansi[I.index]:this._themeService.colors[z]);this.coreService.triggerDataEvent(`${X.C0.ESC}]${q};${(0,L.toRgbString)(ae)}${X.C1_ESCAPED.ST}`);break;case 1:if(z==="ansi")this._themeService.modifyColors(ee=>ee.ansi[I.index]=T.channels.toColor(...I.color));else{const ee=z;this._themeService.modifyColors(le=>le[ee]=T.channels.toColor(...I.color))}break;case 2:this._themeService.restoreColor(I.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(Y){Y?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(K.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(Y){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const Y=this.buffer.ybase+this.buffer.y,I=this.buffer.lines.get(Y);if(!I)return;const z=Math.min(this.buffer.x,this.cols-1),q=this._renderService.dimensions.css.cell.height,ae=I.getWidth(z),ee=this._renderService.dimensions.css.cell.width*ae,le=this.buffer.y*this._renderService.dimensions.css.cell.height,ve=z*this._renderService.dimensions.css.cell.width;this.textarea.style.left=ve+"px",this.textarea.style.top=le+"px",this.textarea.style.width=ee+"px",this.textarea.style.height=q+"px",this.textarea.style.lineHeight=q+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,u.addDisposableDomListener)(this.element,"copy",I=>{this.hasSelection()&&(0,c.copyHandler)(I,this._selectionService)}));const Y=I=>(0,c.handlePasteEvent)(I,this.textarea,this.coreService,this.optionsService);this.register((0,u.addDisposableDomListener)(this.textarea,"paste",Y)),this.register((0,u.addDisposableDomListener)(this.element,"paste",Y)),B.isFirefox?this.register((0,u.addDisposableDomListener)(this.element,"mousedown",I=>{I.button===2&&(0,c.rightClickHandler)(I,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,u.addDisposableDomListener)(this.element,"contextmenu",I=>{(0,c.rightClickHandler)(I,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),B.isLinux&&this.register((0,u.addDisposableDomListener)(this.element,"auxclick",I=>{I.button===1&&(0,c.moveTextAreaUnderMouseCursor)(I,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,u.addDisposableDomListener)(this.textarea,"keyup",Y=>this._keyUp(Y),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keydown",Y=>this._keyDown(Y),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keypress",Y=>this._keyPress(Y),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionupdate",Y=>this._compositionHelper.compositionupdate(Y))),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,u.addDisposableDomListener)(this.textarea,"input",Y=>this._inputEvent(Y),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(Y){if(!Y)throw new Error("Terminal requires a parent element.");if(Y.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=Y.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),Y.appendChild(this.element);const I=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),I.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,u.addDisposableDomListener)(this.screenElement,"mousemove",z=>this.updateCursorStyle(z))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),I.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",h.promptLabel),B.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","fal
56se"),this.textarea.tabIndex=0,this._coreBrowserService=this.register(this._instantiationService.createInstance(C.CoreBrowserService,this.textarea,Y.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(k.ICoreBrowserService,this._coreBrowserService),this.register((0,u.addDisposableDomListener)(this.textarea,"focus",z=>this._handleTextAreaFocus(z))),this.register((0,u.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(k.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(O.ThemeService),this._instantiationService.setService(k.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(w.CharacterJoinerService),this._instantiationService.setService(k.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(E.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(k.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(z=>this._onRender.fire(z))),this.onResize(z=>this._renderService.resize(z.cols,z.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(y.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(A.MouseService),this._instantiationService.setService(k.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(d.Linkifier,this.screenElement)),this.element.appendChild(I);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(b.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(z=>this.scrollLines(z.amount,z.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),this.register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this.register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this.register(this.onBlur(()=>this._renderService.handleBlur())),this.register(this.onFocus(()=>this._renderService.handleFocus())),this.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(S.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(k.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(z=>this.scrollLines(z.amount,z.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(z=>this._renderService.handleSelectionChanged(z.start,z.end,z.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(z=>{this.textarea.value=z,this.textarea.focus(),this.textarea.select()}
56)),this.register(this._onScroll.event(z=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,u.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.register(this._instantiationService.createInstance(g.BufferDecorationRenderer,this.screenElement)),this.register((0,u.addDisposableDomListener)(this.element,"mousedown",z=>this._selectionService.handleMouseDown(z))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(K.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",z=>this._handleScreenReaderModeOptionChange(z))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",z=>{!this._overviewRulerRenderer&&z&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(v.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const Y=this,I=this.element;function z(ee){const le=Y._mouseService.getMouseReportCoords(ee,Y.screenElement);if(!le)return!1;let ve,ye;switch(ee.overrideType||ee.type){case"mousemove":ye=32,ee.buttons===void 0?(ve=3,ee.button!==void 0&&(ve=ee.button<3?ee.button:3)):ve=1&ee.buttons?0:4&ee.buttons?1:2&ee.buttons?2:3;break;case"mouseup":ye=0,ve=ee.button<3?ee.button:3;break;case"mousedown":ye=1,ve=ee.button<3?ee.button:3;break;case"wheel":if(Y._customWheelEventHandler&&Y._customWheelEventHandler(ee)===!1||Y.viewport.getLinesScrolled(ee)===0)return!1;ye=ee.deltaY<0?0:1,ve=4;break;default:return!1}return!(ye===void 0||ve===void 0||ve>4)&&Y.coreMouseService.triggerMouseEvent({col:le.col,row:le.row,x:le.x,y:le.y,button:ve,action:ye,ctrl:ee.ctrlKey,alt:ee.altKey,shift:ee.shiftKey})}const q={mouseup:null,wheel:null,mousedrag:null,mousemove:null},ae={mouseup:ee=>(z(ee),ee.buttons||(this._document.removeEventListener("mouseup",q.mouseup),q.mousedrag&&this._document.removeEventListener("mousemove",q.mousedrag)),this.cancel(ee)),wheel:ee=>(z(ee),this.cancel(ee,!0)),mousedrag:ee=>{ee.buttons&&z(ee)},mousemove:ee=>{ee.buttons||z(ee)}};this.register(this.coreMouseService.onProtocolChange(ee=>{ee?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(ee)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&ee?q.mousemove||(I.addEventListener("mousemove",ae.mousemove),q.mousemove=ae.mousemove):(I.removeEventListener("mousemove",q.mousemove),q.mousemove=null),16&ee?q.wheel||(I.addEventListener("wheel",ae.wheel,{passive:!1}),q.wheel=ae.wheel):(I.removeEventListener("wheel",q.wheel),q.wheel=null),2&ee?q.mouseup||(q.mouseup=ae.mouseup):(this._document.removeEventListener("mouseup",q.mouseup),q.mouseup=null),4&ee?q.mousedrag||(q.mousedrag=ae.mousedrag):(this._document.removeEventListener("mousemove",q.mousedrag),q.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,u.addDisposableDomListener)(I,"mousedown",ee=>{if(ee.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(ee))return z(ee),q.mouseup&&this._document.addEventListener("mouseup",q.mouseup),q.mousedrag&&this._document.addEventListener("mousemove",q.mousedrag),this.cancel(ee)})),this.register((0,u.addDisposableDomListener)(I,"wheel",ee=>{if(!q.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(ee)===!1)return!1;if(!this.buffer.hasScrollback){const le=this.viewport.getLinesScrolled(ee);if(le===0)return;const ve=X.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(ee.deltaY<0?"A":"B");let ye="";for(let Ae=0;Ae<Math.abs(le);Ae++)ye+=ve;return this.coreService.triggerDataEvent(ye,!0),this.cancel(ee,!0)}return this.viewport.handleWheel(ee)?this.cancel(ee):void 0}},{passive:!1})),this.register((0,u.addDisposableDomListener)(I,"touchstart",ee=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(ee),this.cancel(ee)},{passive:!0})),this.register((0,u.addDisposableDomListener)(I,"touchmove",ee=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(ee)?void 0:this.cancel(ee)},{passive:!1}))}refresh(Y,I){this._renderService?.refreshRows(Y,I)}updateCursorStyle(Y){this._selectionService?.shouldColumnSelect(Y)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(Y,I,z=0){z===1?(super.scrollLines(Y,I,z),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(Y)}paste(Y){(0,c.paste)(Y,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(Y){this._customKeyEventHandler=Y}attachCustomWheelEventHandler(Y){this._customWheelEventHandler=Y}registerLinkProvider(Y){return this._linkProviderService.registerLinkProvider(Y)}registerCharacterJoiner(Y){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const I=this._characterJoinerService.register(Y);return this.refresh(0,this.rows-1),I}
vendor: 4,984 bytes, line 56
56deregisterCharacterJoiner(Y){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(Y)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(Y){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+Y)}registerDecoration(Y){return this._decorationService.registerDecoration(Y)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(Y,I,z){this._selectionService.setSelection(Y,I,z)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(Y,I){this._selectionService?.selectLines(Y,I)}_keyDown(Y){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(Y)===!1)return!1;const I=this.browser.isMac&&this.options.macOptionIsMeta&&Y.altKey;if(!I&&!this._compositionHelper.keydown(Y))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;I||Y.key!=="Dead"&&Y.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const z=(0,oe.evaluateKeyboardEvent)(Y,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(Y),z.type===3||z.type===2){const q=this.rows-1;return this.scrollLines(z.type===2?-q:q),this.cancel(Y,!0)}return z.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,Y)||(z.cancel&&this.cancel(Y,!0),!z.key||!!(Y.key&&!Y.ctrlKey&&!Y.altKey&&!Y.metaKey&&Y.key.length===1&&Y.key.charCodeAt(0)>=65&&Y.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(z.key!==X.C0.ETX&&z.key!==X.C0.CR||(this.textarea.value=""),this._onKey.fire({key:z.key,domEvent:Y}),this._showCursor(),this.coreService.triggerDataEvent(z.key,!0),!this.optionsService.rawOptions.screenReaderMode||Y.altKey||Y.ctrlKey?this.cancel(Y,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(Y,I){const z=Y.isMac&&!this.options.macOptionIsMeta&&I.altKey&&!I.ctrlKey&&!I.metaKey||Y.isWindows&&I.altKey&&I.ctrlKey&&!I.metaKey||Y.isWindows&&I.getModifierState("AltGraph");return I.type==="keypress"?z:z&&(!I.keyCode||I.keyCode>47)}_keyUp(Y){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(Y)===!1||(function(I){return I.keyCode===16||I.keyCode===17||I.keyCode===18}(Y)||this.focus(),this.updateCursorStyle(Y),this._keyPressHandled=!1)}_keyPress(Y){let I;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(Y)===!1)return!1;if(this.cancel(Y),Y.charCode)I=Y.charCode;else if(Y.which===null||Y.which===void 0)I=Y.keyCode;else{if(Y.which===0||Y.charCode===0)return!1;I=Y.which}return!(!I||(Y.altKey||Y.ctrlKey||Y.metaKey)&&!this._isThirdLevelShift(this.browser,Y)||(I=String.fromCharCode(I),this._onKey.fire({key:I,domEvent:Y}),this._showCursor(),this.coreService.triggerDataEvent(I,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(Y){if(Y.data&&Y.inputType==="insertText"&&(!Y.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const I=Y.data;return this.coreService.triggerDataEvent(I,!0),this.cancel(Y),!0}return!1}resize(Y,I){Y!==this.cols||I!==this.rows?super.resize(Y,I):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(Y,I){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let Y=1;Y<this.rows;Y++)this.buffer.lines.push(this.buffer.getBlankLine(U.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),this.viewport?.reset(),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;const Y=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this.viewport?.reset(),this._customKeyEventHandler=Y,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(X.C0.ESC+"[I"):this.coreService.triggerDataEvent(X.C0.ESC+"[O")}_reportWindowsOptions(Y){if(this._renderService)switch(Y){case Z.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const I=this._renderService.dimensions.css.
56canvas.width.toFixed(0),z=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[4;${z};${I}t`);break;case Z.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const q=this._renderService.dimensions.css.cell.width.toFixed(0),ae=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[6;${ae};${q}t`)}}cancel(Y,I){if(this.options.cancelEvents||I)return Y.preventDefault(),Y.stopPropagation(),!1}}o.Terminal=se},9924:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TimeBasedDebouncer=void 0,o.TimeBasedDebouncer=class{constructor(l,c=1e3){this._renderCallback=l,this._debounceThresholdMS=c,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(l,c,u){this._rowCount=u,l=l!==void 0?l:0,c=c!==void 0?c:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,c):c;const d=Date.now();if(d-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=d,this._innerRefresh();else if(!this._additionalRefreshRequested){const h=d-this._lastRefreshMs,m=this._debounceThresholdMS-h;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},m)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const l=Math.max(this._rowStart,0),c=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,c)}}},1680:function(a,o,l){var c=this&&this.__decorate||function(y,v,_,w){var C,A=arguments.length,E=A<3?v:w===null?w=Object.getOwnPropertyDescriptor(v,_):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(y,v,_,w);else for(var S=y.length-1;S>=0;S--)(C=y[S])&&(E=(A<3?C(E):A>3?C(v,_,E):C(v,_))||E);return A>3&&E&&Object.defineProperty(v,_,E),E},u=this&&this.__param||function(y,v){return function(_,w){v(_,w,y)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Viewport=void 0;const d=l(3656),h=l(4725),m=l(8460),b=l(844),g=l(2585);let p=o.Viewport=class extends b.Disposable{constructor(y,v,_,w,C,A,E,S){super(),this._viewportElement=y,this._scrollArea=v,this._bufferService=_,this._optionsService=w,this._charSizeService=C,this._renderService=A,this._coreBrowserService=E,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new m.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,d.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(k=>this._activeBuffer=k.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(k=>this._renderDimensions=k)),this._handleThemeChange(S.colors),this.register(S.onChangeColors(k=>this._handleThemeChange(k))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(y){this._viewportElement.style.backgroundColor=y.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(y){if(y)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>
56this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const v=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==v&&(this._lastRecordedBufferHeight=v,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const y=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==y&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=y),this._refreshAnimationFrame=null}syncScrollArea(y=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(y);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(y)}_handleScroll(y){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const v=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:v,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const y=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(y*(this._smoothScrollState.target-this._smoothScrollState.origin)),y<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(y,v){const _=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(v<0&&this._viewportElement.scrollTop!==0||v>0&&_<this._lastRecordedBufferHeight)||(y.cancelable&&y.preventDefault(),!1)}handleWheel(y){const v=this._getPixelsScrolled(y);return v!==0&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target===-1?this._smoothScrollState.target=this._viewportElement.scrollTop+v:this._smoothScrollState.target+=v,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=v,this._bubbleScroll(y,v))}scrollLines(y){if(y!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const v=y*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+v,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:y,suppressScrollEvent:!1})}_getPixelsScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let v=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_LINE?v*=this._currentRowHeight:y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(v*=this._currentRowHeight*this._bufferService.rows),v}getBufferElements(y,v){let _,w="";const C=[],A=v??this._bufferService.buffer.lines.length,E=this._bufferService.buffer.lines;for(let S=y;S<A;S++){const k=E.get(S);if(!k)continue;const O=E.get(S+1)?.isWrapped;
56if(w+=k.translateToString(!O),!O||S===E.length-1){const T=document.createElement("div");T.textContent=w,C.push(T),w.length>0&&(_=T),w=""}}return{bufferElements:C,cursorElement:_}}getLinesScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let v=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(v/=this._currentRowHeight+0,this._wheelPartialScroll+=v,v=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(v*=this._bufferService.rows),v}_applyScrollModifier(y,v){const _=this._optionsService.rawOptions.fastScrollModifier;return _==="alt"&&v.altKey||_==="ctrl"&&v.ctrlKey||_==="shift"&&v.shiftKey?y*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:y*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(y){this._lastTouchY=y.touches[0].pageY}handleTouchMove(y){const v=this._lastTouchY-y.touches[0].pageY;return this._lastTouchY=y.touches[0].pageY,v!==0&&(this._viewportElement.scrollTop+=v,this._bubbleScroll(y,v))}};o.Viewport=p=c([u(2,g.IBufferService),u(3,g.IOptionsService),u(4,h.ICharSizeService),u(5,h.IRenderService),u(6,h.ICoreBrowserService),u(7,h.IThemeService)],p)},3107:function(a,o,l){var c=this&&this.__decorate||function(g,p,y,v){var _,w=arguments.length,C=w<3?p:v===null?v=Object.getOwnPropertyDescriptor(p,y):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,p,y,v);else for(var A=g.length-1;A>=0;A--)(_=g[A])&&(C=(w<3?_(C):w>3?_(p,y,C):_(p,y))||C);return w>3&&C&&Object.defineProperty(p,y,C),C},u=this&&this.__param||function(g,p){return function(y,v){p(y,v,g)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferDecorationRenderer=void 0;const d=l(4725),h=l(844),m=l(2585);let b=o.BufferDecorationRenderer=class extends h.Disposable{constructor(g,p,y,v,_){super(),this._screenElement=g,this._bufferService=p,this._coreBrowserService=y,this._decorationService=v,this._renderService=_,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this.register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this.register(this._coreBrowserService.onDprChange(()=>
vendor: 15,360 bytes, line 56
56this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this.register(this._decorationService.onDecorationRemoved(w=>this._removeDecoration(w))),this.register((0,h.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const g of this._decorationService.decorations)this._renderDecoration(g);this._dimensionsChanged=!1}_renderDecoration(g){this._refreshStyle(g),this._dimensionsChanged&&this._refreshXPosition(g)}_createElement(g){const p=this._coreBrowserService.mainDocument.createElement("div");p.classList.add("xterm-decoration"),p.classList.toggle("xterm-decoration-top-layer",g?.options?.layer==="top"),p.style.width=`${Math.round((g.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,p.style.height=(g.options.height||1)*this._renderService.dimensions.css.cell.height+"px",p.style.top=(g.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",p.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const y=g.options.x??0;return y&&y>this._bufferService.cols&&(p.style.display="none"),this._refreshXPosition(g,p),p}_refreshStyle(g){const p=g.marker.line-this._bufferService.buffers.active.ydisp;if(p<0||p>=this._bufferService.rows)g.element&&(g.element.style.display="none",g.onRenderEmitter.fire(g.element));else{let y=this._decorationElements.get(g);y||(y=this._createElement(g),g.element=y,this._decorationElements.set(g,y),this._container.appendChild(y),g.onDispose(()=>{this._decorationElements.delete(g),y.remove()})),y.style.top=p*this._renderService.dimensions.css.cell.height+"px",y.style.display=this._altBufferIsActive?"none":"block",g.onRenderEmitter.fire(y)}}_refreshXPosition(g,p=g.element){if(!p)return;const y=g.options.x??0;(g.options.anchor||"left")==="right"?p.style.right=y?y*this._renderService.dimensions.css.cell.width+"px":"":p.style.left=y?y*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(g){this._decorationElements.get(g)?.remove(),this._decorationElements.delete(g),g.dispose()}};o.BufferDecorationRenderer=b=c([u(1,m.IBufferService),u(2,d.ICoreBrowserService),u(3,m.IDecorationService),u(4,d.IRenderService)],b)},5871:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorZoneStore=void 0,o.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(l){if(l.options.overviewRulerOptions){for(const c of this._zones)if(c.color===l.options.overviewRulerOptions.color&&c.position===l.options.overviewRulerOptions.position){if(this._lineIntersectsZone(c,l.marker.line))return;if(this._lineAdjacentToZone(c,l.marker.line,l.options.overviewRulerOptions.position))return void this._addLineToZone(c,l.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=l.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=l.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=l.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=l.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:l.options.overviewRulerOptions.color,position:l.options.overviewRulerOptions.position,startBufferLine:l.marker.line,endBufferLine:l.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(l){this._linePadding=l}_lineIntersectsZone(l,c){return c>=l.startBufferLine&&c<=l.endBufferLine}_lineAdjacentToZone(l,c,u){return c>=l.startBufferLine-this._linePadding[u||"full"]&&c<=l.endBufferLine+this._linePadding[u||"full"]}_addLineToZone(l,c){l.startBufferLine=Math.min(l.startBufferLine,c),l.endBufferLine=Math.max(l.endBufferLine,c)}}},5744:function(a,o,l){var c=this&&this.__decorate||function(_,w,C,A){var E,S=arguments.length,k=S<3?w:A===null?A=Object.getOwnPropertyDescriptor(w,C):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(_,w,C,A);else for(var O=_.length-1;O>=0;O--)(E=_[O])&&(k=(S<3?E(k):S>3?E(w,C,k):E(w,C))||k);return S>3&&k&&Object.defineProperty(w,C,k),k},u=this&&this.__param||function(_,w){return function(C,A){w(C,A,_)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OverviewRulerRenderer=void 0;const d=l(5871),h=l(4725),m=l(844),b=l(2585),g={full:0,left:0,center:0,right:0},p={full:0,left:0,center:0,right:0},y={full:0,left:0,center:0,right:0};let v=o.OverviewRulerRenderer=class extends m.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(_,w,C,A,E,S,k){super(),this._viewportElement=_,this._screenElement=w,this._bufferService=C,this._decorationService=A,this._renderService=E,this._optionsService=S,this._coreBrowserService=k,this._colorZoneStore=new d.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement);const O=this._canvas.getContext("2d");if(!O)throw new Error("Ctx cannot be null");this._ctx=O,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,m.toDisposable)(()=>{this._canvas?.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this.register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const _=Math.floor(this._canvas.width/3),w=Math.ceil(this._canvas.width/3);p.full=this._canvas.width,p.left=_,p.center=w,p.right=_,this._refreshDrawHeightConstants(),y.full=0,y.left=0,y.center=p.left,y.right=p.left+p.center}_refreshDrawHeightConstants(){g.full=Math.round(2*this._coreBrowserService.dpr);const _=this._canvas.height/this._bufferService.buffer.lines.length,w=Math.round(Math.max(Math.min(_,12),6)*this._coreBrowserService.dpr);g.left=w,g.center=w,g.right=w}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const w of this._decorationService.decorations)this._colorZoneStore.addDecoration(w);this._ctx.lineWidth=1;const _=this._colorZoneStore.zones;for(const w of _)w.position!=="full"&&this._renderColorZone(w);for(const w of _)w.position==="full"&&this._renderColorZone(w);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(_){this._ctx.fillStyle=_.color,this._ctx.fillRect(y[_.position||"full"],Math.round((this._canvas.height-1)*(_.startBufferLine/this._bufferService.buffers.active.lines.length)-g[_.position||"full"]/2),p[_.position||"full"],Math.round((this._canvas.height-1)*((_.endBufferLine-_.startBufferLine)/this._bufferService.buffers.active.lines.length)+g[_.position||"full"]))}_queueRefresh(_,w){this._shouldUpdateDimensions=_||this._shouldUpdateDimensions,this._shouldUpdateAnchor=w||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};o.OverviewRulerRenderer=v=c([u(2,b.IBufferService),u(3,b.IDecorationService),u(4,h.IRenderService),u(5,b.IOptionsService),u(6,h.ICoreBrowserService)],v)},2950:function(a,o,l){var c=this&&this.__decorate||function(g,p,y,v){var _,w=arguments.length,C=w<3?p:v===null?v=Object.getOwnPropertyDescriptor(p,y):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,p,y,v);else for(var A=g.length-1;A>=0;A--)(_=g[A])&&(C=(w<3?_(C):w>3?_(p,y,C):_(p,y))||C);return w>3&&C&&Object.defineProperty(p,y,C),C},u=this&&this.__param||function(g,p){return function(y,v){p(y,v,g)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CompositionHelper=void 0;const d=l(4725),h=l(2585),m=l(2584);let b=o.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(g,p,y,v,_,w){this._textarea=g,this._compositionView=p,this._bufferService=y,this._optionsService=v,this._coreService=_,this._renderService=w,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(g){this._compositionView.textContent=g.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(g){if(this._isComposing||this._isSendingComposition){if(g.keyCode===229||g.keyCode===16||g.keyCode===17||g.keyCode===18)return!1;this._finalizeComposition(!1)}return g.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(g){if(this._compositionView.classList.remove("active"),this._isComposing=!1,g){const p={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let y;this._isSendingComposition=!1,p.start+=this._dataAlreadySent.length,y=this._isComposing?this._textarea.value.substring(p.start,p.end):this._textarea.value.substring(p.start),y.length>0&&this._coreService.triggerDataEvent(y,!0)}},0)}else{this._isSendingComposition=!1;const p=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(p,!0)}}_handleAnyTextareaChanges(){const g=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const p=this._textarea.value,y=p.replace(g,"");this._dataAlreadySent=y,p.length>g.length?this._coreService.triggerDataEvent(y,!0):p.length<g.length?this._coreService.triggerDataEvent(`${m.C0.DEL}`,!0):p.length===g.length&&p!==g&&this._coreService.triggerDataEvent(p,!0)}},0)}updateCompositionElements(g){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const p=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),y=this._renderService.dimensions.css.cell.height,v=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,_=p*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=_+"px",this._compositionView.style.top=v+"px",this._compositionView.style.height=y+"px",this._compositionView.style.lineHeight=y+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const w=this._compositionView.getBoundingClientRect();this._textarea.style.left=_+"px",this._textarea.style.top=v+"px",this._textarea.style.width=Math.max(w.width,1)+"px",this._textarea.style.height=Math.max(w.height,1)+"px",this._textarea.style.lineHeight=w.height+"px"}g||setTimeout(()=>this.updateCompositionElements(!0),0)}}};o.CompositionHelper=b=c([u(2,h.IBufferService),u(3,h.IOptionsService),u(4,h.ICoreService),u(5,d.IRenderService)],b)},9806:(a,o)=>{function l(c,u,d){const h=d.getBoundingClientRect(),m=c.getComputedStyle(d),b=parseInt(m.getPropertyValue("padding-left")),g=parseInt(m.getPropertyValue("padding-top"));return[u.clientX-h.left-b,u.clientY-h.top-g]}Object.defineProperty(o,"__esModule",{value:!0}),o.getCoords=o.getCoordsRelativeToElement=void 0,o.getCoordsRelativeToElement=l,o.getCoords=function(c,u,d,h,m,b,g,p,y){if(!b)return;const v=l(c,u,d);return v?(v[0]=Math.ceil((v[0]+(y?g/2:0))/g),v[1]=Math.ceil(v[1]/p),v[0]=Math.min(Math.max(v[0],1),h+(y?1:0)),v[1]=Math.min(Math.max(v[1],1),m),v):void 0}},9504:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.moveToCellSequence=void 0;const c=l(2584);function u(p,y,v,_){const w=p-d(p,v),C=y-d(y,v),A=Math.abs(w-C)-function(E,S,k){let O=0;const T=E-d(E,k),R=S-d(S,k);for(let N=0;N<Math.abs(T-R);N++){const M=h(E,S)==="A"?-1:1;k.buffer.lines.get(T+M*N)?.isWrapped&&O++}return O}(p,y,v);return g(A,b(h(p,y),_))}function d(p,y){let v=0,_=y.buffer.lines.get(p),w=_?.isWrapped;for(;w&&p>=0&&p<y.rows;)v++,_=y.buffer.lines.get(--p),w=_?.isWrapped;return v}function h(p,y){return p>y?"A":"B"}function m(p,y,v,_,w,C){let A=p,E=y,S="";for(;A!==v||E!==_;)A+=w?1:-1,w&&A>C.cols-1?(S+=C.buffer.translateBufferLineToString(E,!1,p,A),A=0,p=0,E++):!w&&A<0&&(S+=C.buffer.translateBufferLineToString(E,!1,0,p+1),A=C.cols-1,p=A,E--);return S+C.buffer.translateBufferLineToString(E,!1,p,A)}function b(p,y){const v=y?"O":"[";return c.C0.ESC+v+p}function g(p,y){p=Math.floor(p);let v="";for(let _=0;_<p;_++)v+=y;return v}o.moveToCellSequence=function(p,y,v,_){const w=v.buffer.x,C=v.buffer.y;if(!v.buffer.hasScrollback)return function(S,k,O,T,R,N){return u(k,T,R,N).length===0?"":g
56(m(S,k,S,k-d(k,R),!1,R).length,b("D",N))}(w,C,0,y,v,_)+u(C,y,v,_)+function(S,k,O,T,R,N){let M;M=u(k,T,R,N).length>0?T-d(T,R):k;const B=T,U=function(X,oe,L,F,V,Z){let K;return K=u(L,F,V,Z).length>0?F-d(F,V):oe,X<L&&K<=F||X>=L&&K<F?"C":"D"}(S,k,O,T,R,N);return g(m(S,M,O,B,U==="C",R).length,b(U,N))}(w,C,p,y,v,_);let A;if(C===y)return A=w>p?"D":"C",g(Math.abs(w-p),b(A,_));A=C>y?"D":"C";const E=Math.abs(C-y);return g(function(S,k){return k.cols-S}(C>y?p:w,v)+(E-1)*v.cols+1+((C>y?w:p)-1),b(A,_))}},1296:function(a,o,l){var c=this&&this.__decorate||function(N,M,B,U){var X,oe=arguments.length,L=oe<3?M:U===null?U=Object.getOwnPropertyDescriptor(M,B):U;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(N,M,B,U);else for(var F=N.length-1;F>=0;F--)(X=N[F])&&(L=(oe<3?X(L):oe>3?X(M,B,L):X(M,B))||L);return oe>3&&L&&Object.defineProperty(M,B,L),L},u=this&&this.__param||function(N,M){return function(B,U){M(B,U,N)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRenderer=void 0;const d=l(3787),h=l(2550),m=l(2223),b=l(6171),g=l(6052),p=l(4725),y=l(8055),v=l(8460),_=l(844),w=l(2585),C="xterm-dom-renderer-owner-",A="xterm-rows",E="xterm-fg-",S="xterm-bg-",k="xterm-focus",O="xterm-selection";let T=1,R=o.DomRenderer=class extends _.Disposable{constructor(N,M,B,U,X,oe,L,F,V,Z,K,ie,se){super(),this._terminal=N,this._document=M,this._element=B,this._screenElement=U,this._viewportElement=X,this._helperContainer=oe,this._linkifier2=L,this._charSizeService=V,this._optionsService=Z,this._bufferService=K,this._coreBrowserService=ie,this._themeService=se,this._terminalClass=T++,this._rowElements=[],this._selectionRenderModel=(0,g.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new v.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(A),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(O),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,b.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(fe=>this._injectCss(fe))),this._injectCss(this._themeService.colors),this._rowFactory=F.createInstance(d.DomRendererRowFactory,document),this._element.classList.add(C+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(fe=>this._handleLinkHover(fe))),this.register(this._linkifier2.onHideLinkUnderline(fe=>this._handleLinkLeave(fe))),this.register((0,_.toDisposable)(()=>{this._element.classList.remove(C+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new h.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const N=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*N,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*N),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.
vendor: 8,577 bytes, line 56
56canvas.width=Math.round(this.dimensions.device.canvas.width/N),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/N),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const B of this._rowElements)B.style.width=`${this.dimensions.css.canvas.width}px`,B.style.height=`${this.dimensions.css.cell.height}px`,B.style.lineHeight=`${this.dimensions.css.cell.height}px`,B.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const M=`${this._terminalSelector} .${A} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=M,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(N){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let M=`${this._terminalSelector} .${A} { color: ${N.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;M+=`${this._terminalSelector} .${A} .xterm-dim { color: ${y.color.multiplyOpacity(N.foreground,.5).css};}`,M+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const B=`blink_underline_${this._terminalClass}`,U=`blink_bar_${this._terminalClass}`,X=`blink_block_${this._terminalClass}`;M+=`@keyframes ${B} { 50% { border-bottom-style: hidden; }}`,M+=`@keyframes ${U} { 50% { box-shadow: none; }}`,M+=`@keyframes ${X} { 0% { background-color: ${N.cursor.css}; color: ${N.cursorAccent.css}; } 50% { background-color: inherit; color: ${N.cursor.css}; }}`,M+=`${this._terminalSelector} .${A}.${k} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${B} 1s step-end infinite;}${this._terminalSelector} .${A}.${k} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${U} 1s step-end infinite;}${this._terminalSelector} .${A}.${k} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${X} 1s step-end infinite;}${this._terminalSelector} .${A} .xterm-cursor.xterm-cursor-block { background-color: ${N.cursor.css}; color: ${N.cursorAccent.css};}${this._terminalSelector} .${A} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${N.cursor.css} !important; color: ${N.cursorAccent.css} !important;}${this._terminalSelector} .${A} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${N.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${A} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${N.cursor.css} inset;}${this._terminalSelector} .${A} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${N.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,M+=`${this._terminalSelector} .${O} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${O} div { position: absolute; background-color: ${N.selectionBackgroundOpaque.css};}${this._terminalSelector} .${O} div { position: absolute; background-color: ${N.selectionInactiveBackgroundOpaque.css};}`;for(const[oe,L]of N.ansi.entries())M+=`${this._terminalSelector} .${E}${oe} { color: ${L.css}; }${this._terminalSelector} .${E}${oe}.xterm-dim { color: ${y.color.multiplyOpacity(L,.5).css}; }${this._terminalSelector} .${S}${oe} { background-color: ${L.css}; }`;M+=`${this._terminalSelector} .${E}${m.INVERTED_DEFAULT_COLOR} { color: ${y.color.opaque(N.background).css}; }${this._terminalSelector} .${E}${m.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${y.color.multiplyOpacity(y.color.opaque(N.background),.5).css}; }${this._terminalSelector} .${S}${m.INVERTED_DEFAULT_COLOR} { background-color: ${N.foreground.css}; }`,this._themeStyleElement.textContent=M}_setDefaultSpacing(){const N=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${N}px`,this._rowFactory.defaultSpacing=N}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(N,M){for(let B=this._rowElements.length;B<=M;B++){const U=this._document.createElement("div");this._rowContainer.appendChild(U),this._rowElements.push(U)}for(;this._rowElements.length>M;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(N,M){this._refreshRowElements(N,M),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(k),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(k),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(N,M,B){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(N,M,B),this.renderRows(0,this._bufferService.rows-1),!N||!M)return;this._selectionRenderModel.update(this._terminal,N,M,B);const U=this._selectionRenderModel.viewportStartRow,X=this._selectionRenderModel.viewportEndRow,oe=this._selectionRenderModel.viewportCappedStartRow,L=this._selectionRenderModel.viewportCappedEndRow;if(oe>=this._bufferService.rows||L<0)return;const F=this._document.createDocumentFragment();if(B){const V=N[0]>M[0];F.appendChild(this._createSelectionElement(oe,V?M[0]:N[0],V?N[0]:M[0],L-oe+1))}else{const V=U===oe?N[0]:0,Z=oe===X?M[0]:this._bufferService.cols;F.appendChild(this._createSelectionElement(oe,V,Z));const K=L-oe-1;if(F.appendChild(this._createSelectionElement(oe+1,0,this._bufferService.cols,K)),oe!==L){const ie=X===L?M[0]:this._bufferService.cols;F.appendChild(this._createSelectionElement(L,0,ie))}}this._selectionContainer.appendChild(F)}_createSelectionElement(N,M,B,U=1){const X=this._document.createElement("div"),oe=M*this.dimensions.css.cell.width;let L=this.dimensions.css.cell.width*(B-M);return oe+L>this.dimensions.css.canvas.width&&(L=this.dimensions.css.canvas.width-oe),X.style.height=U*this.dimensions.css.cell.height+"px",X.style.top=N*this.dimensions.css.cell.height+"px",X.style.left=`${oe}px`,X.style.width=`${L}px`,X}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const N of this._rowElements)N.replaceChildren()}renderRows(N,M){const B=this._bufferService.buffer,U=B.ybase+B.y,X=Math.min(B.x,this._bufferService.cols-1),oe=this._optionsService.rawOptions.cursorBlink,L=this._optionsService.rawOptions.cursorStyle,F=this._optionsService.rawOptions.cursorInactiveStyle;for(let V=N;V<=M;V++){const Z=V+B.ydisp,K=this._rowElements[V],ie=B.lines.get(Z);if(!K||!ie)break;K.replaceChildren(...this._rowFactory.createRow(ie,Z,Z===U,L,F,X,oe,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${C}${this._terminalClass}`}_handleLinkHover(N){this._setCellUnderline(N.x1,N.x2,N.y1,N.y2,N.cols,!0)}_handleLinkLeave(N){this._setCellUnderline(N.x1,N.x2,N.y1,N.y2,N.cols,!1)}_setCellUnderline(N,M,B,U,X,oe){B<0&&(N=0),U<0&&(M=0);const L=this._bufferService.rows-1;B=Math.max(Math.min(B,L),0),U=Math.max(Math.min(U,L),0),X=Math.min(X,this._bufferService.cols);const F=this._bufferService.buffer,V=F.ybase+F.y,Z=Math.min(F.x,X-1),K=this._optionsService.rawOptions.cursorBlink,ie=this._optionsService.rawOptions.cursorStyle,se=this._optionsService.rawOptions.cursorInactiveStyle;for(let fe=B;fe<=U;++fe){const Y=fe+F.ydisp,I=this._rowElements[fe],z=F.lines.get(Y);if(!I||!z)break;I.replaceChildren(...this._rowFactory.createRow(z,Y,Y===V,ie,se,Z,K,this.dimensions.css.
56cell.width,this._widthCache,oe?fe===B?N:0:-1,oe?(fe===U?M:X)-1:-1))}}};o.DomRenderer=R=c([u(7,w.IInstantiationService),u(8,p.ICharSizeService),u(9,w.IOptionsService),u(10,w.IBufferService),u(11,p.ICoreBrowserService),u(12,p.IThemeService)],R)},3787:function(a,o,l){var c=this&&this.__decorate||function(A,E,S,k){var O,T=arguments.length,R=T<3?E:k===null?k=Object.getOwnPropertyDescriptor(E,S):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(A,E,S,k);else for(var N=A.length-1;N>=0;N--)(O=A[N])&&(R=(T<3?O(R):T>3?O(E,S,R):O(E,S))||R);return T>3&&R&&Object.defineProperty(E,S,R),R},u=this&&this.__param||function(A,E){return function(S,k){E(S,k,A)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRendererRowFactory=void 0;const d=l(2223),h=l(643),m=l(511),b=l(2585),g=l(8055),p=l(4725),y=l(4269),v=l(6171),_=l(3734);let w=o.DomRendererRowFactory=class{constructor(A,E,S,k,O,T,R){this._document=A,this._characterJoinerService=E,this._optionsService=S,this._coreBrowserService=k,this._coreService=O,this._decorationService=T,this._themeService=R,this._workCell=new m.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(A,E,S){this._selectionStart=A,this._selectionEnd=E,this._columnSelectMode=S}createRow(A,E,S,k,O,T,R,N,M,B,U){const X=[],oe=this._characterJoinerService.getJoinedCharacters(E),L=this._themeService.colors;let F,V=A.getNoBgTrimmedLength();S&&V<T+1&&(V=T+1);let Z=0,K="",ie=0,se=0,fe=0,Y=!1,I=0,z=!1,q=0;const ae=[],ee=B!==-1&&U!==-1;for(let le=0;le<V;le++){A.loadCell(le,this._workCell);let ve=this._workCell.getWidth();if(ve===0)continue;let ye=!1,Ae=le,we=this._workCell;if(oe.length>0&&le===oe[0][0]){ye=!0;const Fe=oe.shift();we=new y.JoinedCellData(this._workCell,A.translateToString(!0,Fe[0],Fe[1]),Fe[1]-Fe[0]),Ae=Fe[1]-1,ve=we.getWidth()}const pe=this._isCellInSelection(le,E),Ye=S&&le===T,ft=ee&&le>=B&&le<=U;let pt=!1;this._decorationService.forEachDecorationAtCell(le,E,void 0,Fe=>{pt=!0});let Lt=we.getChars()||h.WHITESPACE_CELL_CHAR;if(Lt===" "&&(we.isUnderline()||we.isOverline())&&(Lt="Â "),q=ve*N-M.get(Lt,we.isBold(),we.isItalic()),F){if(Z&&(pe&&z||!pe&&!z&&we.bg===ie)&&(pe&&z&&L.selectionForeground||we.fg===se)&&we.extended.ext===fe&&ft===Y&&q===I&&!Ye&&!ye&&!pt){we.isInvisible()?K+=h.WHITESPACE_CELL_CHAR:K+=Lt,Z++;continue}Z&&(F.textContent=K),F=this._document.createElement("span"),Z=0,K=""}else F=this._document.createElement("span");if(ie=we.bg,se=we.fg,fe=we.extended.ext,Y=ft,I=q,z=pe,ye&&T>=le&&T<=Ae&&(T=le),!this._coreService.isCursorHidden&&Ye&&this._coreService.isCursorInitialized){if(ae.push("xterm-cursor"),this._coreBrowserService.isFocused)R&&ae.push("xterm-cursor-blink"),ae.push(k==="bar"?"xterm-cursor-bar":k==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(O)switch(O){case"outline":ae.push("xterm-cursor-outline");break;case"block":ae.push("xterm-cursor-block");break;case"bar":ae.push("xterm-cursor-bar");break;case"underline":ae.push("xterm-cursor-underline")}}if(we.isBold()&&ae.push("xterm-bold"),we.isItalic()&&ae.push("xterm-italic"),we.isDim()&&ae.push("xterm-dim"),K=we.isInvisible()?h.WHITESPACE_CELL_CHAR:we.getChars()||h.WHITESPACE_CELL_CHAR,we.isUnderline()&&(ae.push(`xterm-underline-${we.extended.underlineStyle}`),K===" "&&(K="Â "),!we.isUnderlineColorDefault()))if(we.isUnderlineColorRGB())F.style.textDecorationColor=`rgb(${_.AttributeData.toColorRGB(we.getUnderlineColor()).join(",")})`;else{let Fe=we.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&we.isBold()&&Fe<8&&(Fe+=8),F.style.textDecorationColor=L.ansi[Fe].css}we.isOverline()&&(ae.push("xterm-overline"),K===" "&&(K="Â ")),we.isStrikethrough()&&ae.push("xterm-strikethrough"),ft&&(F.style.textDecoration="underline");let nt=we.getFgColor(),xt=we.getFgColorMode(),ct=we.getBgColor(),_r=we.getBgColorMode();const ht=!!we.isInverse();if(ht){const Fe=nt;nt=ct,ct=Fe;const Fr=xt;xt=_r,_r=Fr}let Pe,be,Te,Ne=!1;switch(this._decorationService.forEachDecorationAtCell(le,E,void 0,Fe=>{Fe.options.layer!=="top"&&Ne||(Fe.backgroundColorRGB&&(_r=50331648,ct=Fe.backgroundColorRGB.rgba>>8&16777215,Pe=Fe.backgroundColorRGB),Fe.foregroundColorRGB&&(xt=50331648,nt=Fe.foregroundColorRGB.rgba>>8&16777215,be=Fe.foregroundColorRGB),Ne=Fe.options.layer==="top")}),!Ne&&pe&&(Pe=this._coreBrowserService.isFocused?L.selectionBackgroun
vendor: 5,248 bytes, line 56
56dOpaque:L.selectionInactiveBackgroundOpaque,ct=Pe.rgba>>8&16777215,_r=50331648,Ne=!0,L.selectionForeground&&(xt=50331648,nt=L.selectionForeground.rgba>>8&16777215,be=L.selectionForeground)),Ne&&ae.push("xterm-decoration-top"),_r){case 16777216:case 33554432:Te=L.ansi[ct],ae.push(`xterm-bg-${ct}`);break;case 50331648:Te=g.channels.toColor(ct>>16,ct>>8&255,255&ct),this._addStyle(F,`background-color:#${C((ct>>>0).toString(16),"0",6)}`);break;default:ht?(Te=L.foreground,ae.push(`xterm-bg-${d.INVERTED_DEFAULT_COLOR}`)):Te=L.background}switch(Pe||we.isDim()&&(Pe=g.color.multiplyOpacity(Te,.5)),xt){case 16777216:case 33554432:we.isBold()&&nt<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(nt+=8),this._applyMinimumContrast(F,Te,L.ansi[nt],we,Pe,void 0)||ae.push(`xterm-fg-${nt}`);break;case 50331648:const Fe=g.channels.toColor(nt>>16&255,nt>>8&255,255&nt);this._applyMinimumContrast(F,Te,Fe,we,Pe,be)||this._addStyle(F,`color:#${C(nt.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(F,Te,L.foreground,we,Pe,be)||ht&&ae.push(`xterm-fg-${d.INVERTED_DEFAULT_COLOR}`)}ae.length&&(F.className=ae.join(" "),ae.length=0),Ye||ye||pt?F.textContent=K:Z++,q!==this.defaultSpacing&&(F.style.letterSpacing=`${q}px`),X.push(F),le=Ae}return F&&Z&&(F.textContent=K),X}_applyMinimumContrast(A,E,S,k,O,T){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,v.treatGlyphAsBackgroundColor)(k.getCode()))return!1;const R=this._getContrastCache(k);let N;if(O||T||(N=R.getColor(E.rgba,S.rgba)),N===void 0){const M=this._optionsService.rawOptions.minimumContrastRatio/(k.isDim()?2:1);N=g.color.ensureContrastRatio(O||E,T||S,M),R.setColor((O||E).rgba,(T||S).rgba,N??null)}return!!N&&(this._addStyle(A,`color:${N.css}`),!0)}_getContrastCache(A){return A.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(A,E){A.setAttribute("style",`${A.getAttribute("style")||""}${E};`)}_isCellInSelection(A,E){const S=this._selectionStart,k=this._selectionEnd;return!(!S||!k)&&(this._columnSelectMode?S[0]<=k[0]?A>=S[0]&&E>=S[1]&&A<k[0]&&E<=k[1]:A<S[0]&&E>=S[1]&&A>=k[0]&&E<=k[1]:E>S[1]&&E<k[1]||S[1]===k[1]&&E===S[1]&&A>=S[0]&&A<k[0]||S[1]<k[1]&&E===k[1]&&A<k[0]||S[1]<k[1]&&E===S[1]&&A>=S[0])}};function C(A,E,S){for(;A.length<S;)A=E+A;return A}o.DomRendererRowFactory=w=c([u(1,p.ICharacterJoinerService),u(2,b.IOptionsService),u(3,p.ICoreBrowserService),u(4,b.ICoreService),u(5,b.IDecorationService),u(6,p.IThemeService)],w)},2550:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WidthCache=void 0,o.WidthCache=class{constructor(l,c){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=l.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const u=l.createElement("span");u.classList.add("xterm-char-measure-element");const d=l.createElement("span");d.classList.add("xterm-char-measure-element"),d.style.fontWeight="bold";const h=l.createElement("span");h.classList.add("xterm-char-measure-element"),h.style.fontStyle="italic";const m=l.createElement("span");m.classList.add("xterm-char-measure-element"),m.style.fontWeight="bold",m.style.fontStyle="italic",this._measureElements=[u,d,h,m],this._container.appendChild(u),this._container.appendChild(d),this._container.appendChild(h),this._container.appendChild(m),c.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(l,c,u,d){l===this._font&&c===this._fontSize&&u===this._weight&&d===this._weightBold||(this._font=l,this._fontSize=c,this._weight=u,this._weightBold=d,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${u}`,this._measureElements[1].style.fontWeight=`${d}`,this._measureElements[2].style.fontWeight=`${u}`,this._measureElements[3].style.fontWeight=`${d}`,this.clear())}get(l,c,u){let d=0;if(!c&&!u&&l.length===1&&(d=l.charCodeAt(0))<256){if(this._flat[d]!==-9999)return this._flat[d];const b=this._measure(l,0);return b>0&&(this._flat[d]=b),b}let h=l;c&&(h+="B"),u&&(h+="I");let m=this._holey.get(h);if(m===void 0){let b=0;c&&(b|=1),u&&(b|=2),m=this._measure(l,b),m>0&&this._holey.set(h,m)}return m}_measure(l,c){const u=this._measureElements[c];return u.textContent=l.repeat(32),u.offsetWidth/32}}},2223:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TEXT_BASELINE=o.DIM_OPACITY=o.INVERTED_DEFAULT_COLOR=void 0;const c=l(6114);o.INVERTED_DEFAULT_COLOR=257,o.DIM_OPACITY=.5,o.TEXT_BASELINE=c.isFirefox||c.isLegacyEdge?"bottom":"ideographic"},6171:(a,o)=>{function l(u){return 57508<=u&&u<=57558}function c(u){return u>=128512&&u<=128591||u>=127744&&u<=128511||u>=128640&&u<=128767||u>=9728&&u<=9983||u>=9984&&u<=10175||u>=65024&&u<=65039||u>=129280&&u<=129535||u>=127462&&u<=127487}Object.defineProperty(o,"__esModule",{value:!0}),o.computeNextVariantOffset=o.createRenderDimensions=o.treatGlyphAsBackgroun
vendor: 6,268 bytes, line 56
56dColor=o.allowRescaling=o.isEmoji=o.isRestrictedPowerlineGlyph=o.isPowerlineGlyph=o.throwIfFalsy=void 0,o.throwIfFalsy=function(u){if(!u)throw new Error("value must not be falsy");return u},o.isPowerlineGlyph=l,o.isRestrictedPowerlineGlyph=function(u){return 57520<=u&&u<=57527},o.isEmoji=c,o.allowRescaling=function(u,d,h,m){return d===1&&h>Math.ceil(1.5*m)&&u!==void 0&&u>255&&!c(u)&&!l(u)&&!function(b){return 57344<=b&&b<=63743}(u)},o.treatGlyphAsBackgroundColor=function(u){return l(u)||function(d){return 9472<=d&&d<=9631}(u)},o.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},o.computeNextVariantOffset=function(u,d,h=0){return(u-(2*Math.round(d)-h))%(2*Math.round(d))}},6052:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createSelectionRenderModel=void 0;class l{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(u,d,h,m=!1){if(this.selectionStart=d,this.selectionEnd=h,!d||!h||d[0]===h[0]&&d[1]===h[1])return void this.clear();const b=u.buffers.active.ydisp,g=d[1]-b,p=h[1]-b,y=Math.max(g,0),v=Math.min(p,u.rows-1);y>=u.rows||v<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=m,this.viewportStartRow=g,this.viewportEndRow=p,this.viewportCappedStartRow=y,this.viewportCappedEndRow=v,this.startCol=d[0],this.endCol=h[0])}isCellSelected(u,d,h){return!!this.hasSelection&&(h-=u.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?d>=this.startCol&&h>=this.viewportCappedStartRow&&d<this.endCol&&h<=this.viewportCappedEndRow:d<this.startCol&&h>=this.viewportCappedStartRow&&d>=this.endCol&&h<=this.viewportCappedEndRow:h>this.viewportStartRow&&h<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&h===this.viewportStartRow&&d>=this.startCol&&d<this.endCol||this.viewportStartRow<this.viewportEndRow&&h===this.viewportEndRow&&d<this.endCol||this.viewportStartRow<this.viewportEndRow&&h===this.viewportStartRow&&d>=this.startCol)}}o.createSelectionRenderModel=function(){return new l}},456:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionModel=void 0,o.SelectionModel=class{constructor(l){this._bufferService=l,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?l%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)-1]:[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[l,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[Math.max(l,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const l=this.selectionStart,c=this.selectionEnd;return!(!l||!c)&&(l[1]>c[1]||l[1]===c[1]&&l[0]>c[0])}handleTrim(l){return this.selectionStart&&(this.selectionStart[1]-=l),this.selectionEnd&&(this.selectionEnd[1]-=l),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(a,o,l){var c=this&&this.__decorate||function(v,_,w,C){var A,E=arguments.length,S=E<3?_:C===null?C=Object.getOwnPropertyDescriptor(_,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,_,w,C);else for(var k=v.length-1;k>=0;k--)(A=v[k])&&(S=(E<3?A(S):E>3?A(_,w,S):A(_,w))||S);return E>3&&S&&Object.defineProperty(_,w,S),S},u=this&&this.__param||function(v,_){return function(w,C){_(w,C,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharSizeService=void 0;const d=l(2585),h=l(8460),m=l(844);let b=o.CharSizeService=class extends m.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(v,_,w){super(),this._optionsService=w,this.width=0,this.height=0,this._onCharSizeChange=this.register(new h.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new y(this._optionsService))}catch{this._measureStrategy=this.register(new p(v,_,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const v=this._measureStrategy.measure();v.width===this.width&&v.height===this.height||(this.width=v.width,this.height=v.height,this._onCharSizeChange.fire())}};o.CharSizeService=b=c([u(2,d.IOptionsService)],b);class g extends m.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(_,w){_!==void 0&&_>0&&w!==void 0&&w>0&&(this._result.width=_,this._result.height=w)}}class p extends g{constructor(_,w,C){super(),this._document=_,this._parentElement=w,this._optionsService=C,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}
56px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class y extends g{constructor(_){super(),this._optionsService=_,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const w=this._ctx.measureText("W");if(!("width"in w&&"fontBoundingBoxAscent"in w&&"fontBoundingBoxDescent"in w))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const _=this._ctx.measureText("W");return this._validateAndSet(_.width,_.fontBoundingBoxAscent+_.fontBoundingBoxDescent),this._result}}},4269:function(a,o,l){var c=this&&this.__decorate||function(y,v,_,w){var C,A=arguments.length,E=A<3?v:w===null?w=Object.getOwnPropertyDescriptor(v,_):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(y,v,_,w);else for(var S=y.length-1;S>=0;S--)(C=y[S])&&(E=(A<3?C(E):A>3?C(v,_,E):C(v,_))||E);return A>3&&E&&Object.defineProperty(v,_,E),E},u=this&&this.__param||function(y,v){return function(_,w){v(_,w,y)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharacterJoinerService=o.JoinedCellData=void 0;const d=l(3734),h=l(643),m=l(511),b=l(2585);class g extends d.AttributeData{constructor(v,_,w){super(),this.content=0,this.combinedData="",this.fg=v.fg,this.bg=v.bg,this.combinedData=_,this._width=w}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(v){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.JoinedCellData=g;let p=o.CharacterJoinerService=class dI{constructor(v){this._bufferService=v,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new m.CellData}register(v){const _={id:this._nextCharacterJoinerId++,handler:v};return this._characterJoiners.push(_),_.id}deregister(v){for(let _=0;_<this._characterJoiners.length;_++)if(this._characterJoiners[_].id===v)return this._characterJoiners.splice(_,1),!0;return!1}getJoinedCharacters(v){if(this._characterJoiners.length===0)return[];const _=this._bufferService.buffer.lines.get(v);if(!_||_.length===0)return[];const w=[],C=_.translateToString(!0);let A=0,E=0,S=0,k=_.getFg(0),O=_.getBg(0);for(let T=0;T<_.getTrimmedLength();T++)if(_.loadCell(T,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==k||this._workCell.bg!==O){if(T-A>1){const R=this._getJoinedRanges(C,S,E,_,A);for(let N=0;N<R.length;N++)w.push(R[N])}A=T,S=E,k=this._workCell.fg,O=this._workCell.bg}E+=this._workCell.getChars().length||h.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-A>1){const T=this._getJoinedRanges(C,S,E,_,A);for(let R=0;R<T.length;R++)w.push(T[R])}return w}_getJoinedRanges(v,_,w,C,A){const E=v.substring(_,w);let S=[];try{S=this._characterJoiners[0].handler(E)}catch(k){console.error(k)}for(let k=1;k<this._characterJoiners.length;k++)try{const O=this._characterJoiners[k].handler(E);for(let T=0;T<O.length;T++)dI._mergeRanges(S,O[T])}catch(O){console.error(O)}return this._stringRangesToCellRanges(S,C,A),S}_stringRangesToCellRanges(v,_,w){let C=0,A=!1,E=0,S=v[C];if(S){for(let k=w;k<this._bufferService.cols;k++){const O=_.getWidth(k),T=_.getString(k).length||h.WHITESPACE_CELL_CHAR.length;if(O!==0){if(!A&&S[0]<=E&&(S[0]=k,A=!0),S[1]<=E){if(S[1]=k,S=v[++C],!S)break;S[0]<=E?(S[0]=k,A=!0):A=!1}E+=T}}S&&(S[1]=this._bufferService.cols)}}static _mergeRanges(v,_){let w=!1;for(let C=0;C<v.length;C++){const A=v[C];if(w){if(_[1]<=A[0])return v[C-1][1]=_[1],v;if(_[1]<=A[1])return v[C-1][1]=Math.max(_[1],A[1]),v.splice(C,1),v;v.splice(C,1),C--}else{if(_[1]<=A[0])return v.splice(C,0,_),v;if(_[1]<=A[1])return A[0]=Math.min(_[0],A[0]),v;_[0]<A[1]&&(A[0]=Math.min(_[0],A[0]),w=!0)}}return w?v[v.length-1][1]=_[1]:v.push(_),v}};o.CharacterJoinerService=p=c([u(0,b.IBufferService)],p)},5114:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreBrowserService=void 0;const c=l(844),u=l(8460),d=l(3656);class h extends c.Disposable{constructor(g,p,y){super(),this._textarea=g,this._window=p,this.mainDocument=y,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new m(this._window),this._onDprChange=this.register(new u.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new u.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange(v=>this._screenDprMonitor.setWindow(v))),this.register((0,u.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get window(){return this._window}set window(g){this._window!==g&&(this._window=g,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}}o.CoreBrowserService=h;class m extends c.Disposable{constructor(g){super(),this._parentWindow=g,this._windowResizeListener=this.register(new c.MutableDisposable),this._onDprChange=this.register(new u.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,c.toDisposable)(()=>this.clearListener()))}setWindow(g){this._parentWindow=g,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,d.addDisposableDomListener)(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},779:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.LinkProviderService=void 0;const c=l(844);class u extends c.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,c.toDisposable)(()=>this.linkProviders.length=0))}registerLinkProvider(h){return this.linkProviders.push(h),{dispose:()=>{const m=this.linkProviders.indexOf(h);m!==-1&&this.linkProviders.splice(m,1)}}}}o.LinkProviderService=u},8934:function(a,o,l){var c=this&&this.__decorate||function(b,g,p,y){var v,_=arguments.length,w=_<3?g:y===null?y=Object.getOwnPropertyDescriptor(g,p):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(b,g,p,y);else for(var C=b.length-1;C>=0;C--)(v=b[C])&&(w=(_<3?v(w):_>3?v(g,p,w):v(g,p))||w);return _>3&&w&&Object.defineProperty(g,p,w),w},u=this&&this.__param||function(b,g){return function(p,y){g(p,y,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.MouseService=void 0;const d=l(4725),h=l(9806);let m=o.MouseService=class{constructor(b,g){this._renderService=b,this._charSizeService=g}getCoords(b,g,p,y,v){return(0,h.getCoords)(window,b,g,p,y,this._charSizeService.hasValidSize,this._renderService.dimensions.css.
56cell.width,this._renderService.dimensions.css.cell.height,v)}getMouseReportCoords(b,g){const p=(0,h.getCoordsRelativeToElement)(window,b,g);if(this._charSizeService.hasValidSize)return p[0]=Math.min(Math.max(p[0],0),this._renderService.dimensions.css.canvas.width-1),p[1]=Math.min(Math.max(p[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(p[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(p[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(p[0]),y:Math.floor(p[1])}}};o.MouseService=m=c([u(0,d.IRenderService),u(1,d.ICharSizeService)],m)},3230:function(a,o,l){var c=this&&this.__decorate||function(v,_,w,C){var A,E=arguments.length,S=E<3?_:C===null?C=Object.getOwnPropertyDescriptor(_,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,_,w,C);else for(var k=v.length-1;k>=0;k--)(A=v[k])&&(S=(E<3?A(S):E>3?A(_,w,S):A(_,w))||S);return E>3&&S&&Object.defineProperty(_,w,S),S},u=this&&this.__param||function(v,_){return function(w,C){_(w,C,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.RenderService=void 0;const d=l(6193),h=l(4725),m=l(8460),b=l(844),g=l(7226),p=l(2585);let y=o.RenderService=class extends b.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(v,_,w,C,A,E,S,k){super(),this._rowCount=v,this._charSizeService=C,this._renderer=this.register(new b.MutableDisposable),this._pausedResizeTask=new g.DebouncedIdleTask,this._observerDisposable=this.register(new b.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new m.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new m.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new m.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new m.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new d.RenderDebouncer((O,T)=>this._renderRows(O,T),S),this.register(this._renderDebouncer),this.register(S.onDprChange(()=>this.handleDevicePixelRatioChange())),this.register(E.onResize(()=>
vendor: 7,564 bytes, lines 56-58
56this._fullRefresh())),this.register(E.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this.register(w.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(A.onDecorationRegistered(()=>this._fullRefresh())),this.register(A.onDecorationRemoved(()=>this._fullRefresh())),this.register(w.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(E.cols,E.rows),this._fullRefresh()})),this.register(w.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(E.buffer.y,E.buffer.y,!0))),this.register(k.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(S.window,_),this.register(S.onWindowChange(O=>this._registerIntersectionObserver(O,_)))}_registerIntersectionObserver(v,_){if("IntersectionObserver"in v){const w=new v.IntersectionObserver(C=>this._handleIntersectionChange(C[C.length-1]),{threshold:0});w.observe(_),this._observerDisposable.value=(0,b.toDisposable)(()=>w.disconnect())}}_handleIntersectionChange(v){this._isPaused=v.isIntersecting===void 0?v.intersectionRatio===0:!v.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(v,_,w=!1){this._isPaused?this._needsFullRefresh=!0:(w||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(v,_,this._rowCount))}_renderRows(v,_){this._renderer.value&&(v=Math.min(v,this._rowCount-1),_=Math.min(_,this._rowCount-1),this._renderer.value.renderRows(v,_),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:v,end:_}),this._onRender.fire({start:v,end:_}),this._isNextRenderRedrawOnly=!0)}resize(v,_){this._rowCount=_,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(v){this._renderer.value=v,this._renderer.value&&(this._renderer.value.onRequestRedraw(_=>this.refreshRows(_.start,_.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(v){return this._renderDebouncer.addRefreshCallback(v)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(v,_){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(v,_)):this._renderer.value.handleResize(v,_),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(v,_,w){this._selectionState.start=v,this._selectionState.end=_,this._selectionState.columnSelectMode=w,this._renderer.value?.handleSelectionChanged(v,_,w)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};o.RenderService=y=c([u(2,p.IOptionsService),u(3,h.ICharSizeService),u(4,p.IDecorationService),u(5,p.IBufferService),u(6,h.ICoreBrowserService),u(7,h.IThemeService)],y)},9312:function(a,o,l){var c=this&&this.__decorate||function(S,k,O,T){var R,N=arguments.length,M=N<3?k:T===null?T=Object.getOwnPropertyDescriptor(k,O):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(S,k,O,T);else for(var B=S.length-1;B>=0;B--)(R=S[B])&&(M=(N<3?R(M):N>3?R(k,O,M):R(k,O))||M);return N>3&&M&&Object.defineProperty(k,O,M),M},u=this&&this.__param||function(S,k){return function(O,T){k(O,T,S)}};Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionService=void 0;const d=l(9806),h=l(9504),m=l(456),b=l(4725),g=l(8460),p=l(844),y=l(6114),v=l(4841),_=l(511),w=l(2585),C="Â ",A=new RegExp(C,"g");let E=o.SelectionService=class extends p.Disposable{constructor(S,k,O,T,R,N,M,B,U){super(),this._element=S,this._screenElement=k,this._linkifier=O,this._bufferService=T,this._coreService=R,this._mouseService=N,this._optionsService=M,this._renderService=B,this._coreBrowserService=U,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new _.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new g.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new g.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new g.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new g.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=X=>this._handleMouseMove(X),this._mouseUpListener=X=>this._handleMouseUp(X),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(X=>this._handleTrim(X)),this.register(this._bufferService.buffers.onBufferActivate(X=>this._handleBufferActivate(X))),this.enable(),this._model=new m.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,p.toDisposable)(()=>{this._removeMouseDownListeners()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const S=this._model.finalSelectionStart,k=this._model.finalSelectionEnd;return!(!S||!k||S[0]===k[0]&&S[1]===k[1])}get selectionText(){const S=this._model.finalSelectionStart,k=this._model.finalSelectionEnd;if(!S||!k)return"";const O=this._bufferService.buffer,T=[];if(this._activeSelectionMode===3){if(S[0]===k[0])return"";const R=S[0]<k[0]?S[0]:k[0],N=S[0]<k[0]?k[0]:S[0];for(let M=S[1];M<=k[1];M++){const B=O.translateBufferLineToString(M,!0,R,N);T.push(B)}}else{const R=S[1]===k[1]?k[0]:void 0;T.push(O.translateBufferLineToString(S[1],!0,S[0],R));for(let N=S[1]+1;N<=k[1]-1;N++){const M=O.lines.get(N),B=O.translateBufferLineToString(N,!0);M?.isWrapped?T[T.length-1]+=B:T.push(B)}if(S[1]!==k[1]){const N=O.lines.get(k[1]),M=O.translateBufferLineToString(k[1],!0,0,k[0]);N&&N.isWrapped?T[T.length-1]+=M:T.push(M)}}return T.map(R=>R.replace(A," ")).join(y.isWindows?`\r 57`:` 58`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(S){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>
vendor: 5,279 bytes, line 58
58this._refresh())),y.isLinux&&S&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(S){const k=this._getMouseBufferCoords(S),O=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!!(O&&T&&k)&&this._areCoordsInSelection(k,O,T)}isCellInSelection(S,k){const O=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!(!O||!T)&&this._areCoordsInSelection([S,k],O,T)}_areCoordsInSelection(S,k,O){return S[1]>k[1]&&S[1]<O[1]||k[1]===O[1]&&S[1]===k[1]&&S[0]>=k[0]&&S[0]<O[0]||k[1]<O[1]&&S[1]===O[1]&&S[0]<O[0]||k[1]<O[1]&&S[1]===k[1]&&S[0]>=k[0]}_selectWordAtCursor(S,k){const O=this._linkifier.currentLink?.link?.range;if(O)return this._model.selectionStart=[O.start.x-1,O.start.y-1],this._model.selectionStartLength=(0,v.getRangeLength)(O,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const T=this._getMouseBufferCoords(S);return!!T&&(this._selectWordAt(T,k),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(S,k){this._model.clearSelection(),S=Math.max(S,0),k=Math.min(k,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,S],this._model.selectionEnd=[this._bufferService.cols,k],this.refresh(),this._onSelectionChange.fire()}_handleTrim(S){this._model.handleTrim(S)&&this.refresh()}_getMouseBufferCoords(S){const k=this._mouseService.getCoords(S,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(k)return k[0]--,k[1]--,k[1]+=this._bufferService.buffer.ydisp,k}_getMouseEventScrollAmount(S){let k=(0,d.getCoordsRelativeToElement)(this._coreBrowserService.window,S,this._screenElement)[1];const O=this._renderService.dimensions.css.canvas.height;return k>=0&&k<=O?0:(k>O&&(k-=O),k=Math.min(Math.max(k,-50),50),k/=50,k/Math.abs(k)+Math.round(14*k))}shouldForceSelection(S){return y.isMac?S.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:S.shiftKey}handleMouseDown(S){if(this._mouseDownTimeStamp=S.timeStamp,(S.button!==2||!this.hasSelection)&&S.button===0){if(!this._enabled){if(!this.shouldForceSelection(S))return;S.stopPropagation()}S.preventDefault(),this._dragScrollAmount=0,this._enabled&&S.shiftKey?this._handleIncrementalClick(S):S.detail===1?this._handleSingleClick(S):S.detail===2?this._handleDoubleClick(S):S.detail===3&&this._handleTripleClick(S),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(S){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(S))}_handleSingleClick(S){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(S)?3:0,this._model.selectionStart=this._getMouseBufferCoords(S),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const k=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);k&&k.length!==this._model.selectionStart[0]&&k.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(S){this._selectWordAtCursor(S,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(S){const k=this._getMouseBufferCoords(S);k&&(this._activeSelectionMode=2,this._selectLineAt(k[1]))}shouldColumnSelect(S){return S.altKey&&!(y.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(S){if(S.stopImmediatePropagation(),!this._model.selectionStart)return;const k=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(S),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(S),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const O=this._bufferService.buffer;if(this._model.selectionEnd[1]<O.lines.length){const T=O.lines.get(this._model.selectionEnd[1]);T&&T.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}
58k&&k[0]===this._model.selectionEnd[0]&&k[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const S=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(S.ydisp+this._bufferService.rows,S.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=S.ydisp),this.refresh()}}_handleMouseUp(S){const k=S.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&k<500&&S.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const O=this._mouseService.getCoords(S,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(O&&O[0]!==void 0&&O[1]!==void 0){const T=(0,h.moveToCellSequence)(O[0]-1,O[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(T,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const S=this._model.finalSelectionStart,k=this._model.finalSelectionEnd,O=!(!S||!k||S[0]===k[0]&&S[1]===k[1]);O?S&&k&&(this._oldSelectionStart&&this._oldSelectionEnd&&S[0]===this._oldSelectionStart[0]&&S[1]===this._oldSelectionStart[1]&&k[0]===this._oldSelectionEnd[0]&&k[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(S,k,O)):this._oldHasSelection&&this._fireOnSelectionChange(S,k,O)}_fireOnSelectionChange(S,k,O){this._oldSelectionStart=S,this._oldSelectionEnd=k,this._oldHasSelection=O,this._onSelectionChange.fire()}_handleBufferActivate(S){this.clearSelection(),this._trimListener.dispose(),this._trimListener=S.activeBuffer.lines.onTrim(k=>this._handleTrim(k))}_convertViewportColToCharacterIndex(S,k){let O=k;for(let T=0;k>=T;T++){const R=S.loadCell(T,this._workCell).getChars().length;this._workCell.getWidth()===0?O--:R>1&&k!==T&&(O+=R-1)}return O}setSelection(S,k,O){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[S,k],this._model.selectionStartLength=O,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(S){this._isClickInSelection(S)||(this._selectWordAtCursor(S,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(S,k,O=!0,T=!0){if(S[0]>=this._bufferService.cols)return;const R=this._bufferService.buffer,N=R.lines.get(S[1]);if(!N)return;const M=R.translateBufferLineToString(S[1],!1);let B=this._convertViewportColToCharacterIndex(N,S[0]),U=B;const X=S[0]-B;let oe=0,L=0,F=0,V=0;if(M.charAt(B)===" "){for(;B>0&&M.charAt(B-1)===" ";)B--;for(;U<M.length&&M.charAt(U+1)===" ";)U++}else{let ie=S[0],se=S[0];N.getWidth(ie)===0&&(oe++,ie--),N.getWidth(se)===2&&(L++,se++);const fe=N.getString(se).length;for(fe>1&&(V+=fe-1,U+=fe-1);ie>0&&B>0&&!this._isCharWordSeparator(N.loadCell(ie-1,this._workCell));){N.loadCell(ie-1,this._workCell);const Y=this._workCell.getChars().length;this._workCell.getWidth()===0?(oe++,ie--):Y>1&&(F+=Y-1,B-=Y-1),B--,ie--}for(;se<N.length&&U+1<M.length&&!this._isCharWordSeparator(N.loadCell(se+1,this._workCell));){N.loadCell(se+1,this._workCell);const Y=this._workCell.getChars().length;this._workCell.getWidth()===2?(L++,se++):Y>1&&(V+=Y-1,U+=Y-1),U++,se++}}U++;let Z=B+X-oe+F,K=Math.min(this._bufferService.cols,U-B+oe+L-F-V);if(k||M.slice(B,U).trim()!==""){if(O&&Z===0&&N.getCodePoint(0)!==32){const ie=R.lines.get(S[1]-1);if(ie&&N.isWrapped&&ie.getCodePoint(this._bufferService.cols-1)!==32){const se=this._getWordAt([this._bufferService.cols-1,S[1]-1],!1,!0,!1);if(se){const fe=this._bufferService.cols-se.start;Z-=fe,K+=fe}}}if(T&&Z+K===this._bufferService.cols&&N.getCodePoint(this._bufferService.cols-1)!==32){const ie=R.lines.get(S[1]+1);if(ie?.isWrapped&&ie.getCodePoint(0)!==32){const se=this._getWordAt([0,S[1]+1],!1,!1,!0);se&&(K+=se.length)}}return{start:Z,length:K}}}_selectWordAt(S,k){const O=this._getWordAt(S,k);if(O){for(;O.start<0;)O.start+=this._bufferService.cols,S[1]--;this._model.selectionStart=[O.start,S[1]],this._model.selectionStartLength=O.length}}_selectToWordAt(S){const k=this._getWordAt(S,!0);if(k){let O=S[1];for(;k.start<0;)k.start+=this._bufferService.cols,O--;
vendor: 19,900 bytes, line 58
58if(!this._model.areSelectionValuesReversed())for(;k.start+k.length>this._bufferService.cols;)k.length-=this._bufferService.cols,O++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?k.start:k.start+k.length,O]}}_isCharWordSeparator(S){return S.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(S.getChars())>=0}_selectLineAt(S){const k=this._bufferService.buffer.getWrappedRangeForLine(S),O={start:{x:0,y:k.first},end:{x:this._bufferService.cols-1,y:k.last}};this._model.selectionStart=[0,k.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,v.getRangeLength)(O,this._bufferService.cols)}};o.SelectionService=E=c([u(3,w.IBufferService),u(4,w.ICoreService),u(5,b.IMouseService),u(6,w.IOptionsService),u(7,b.IRenderService),u(8,b.ICoreBrowserService)],E)},4725:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ILinkProviderService=o.IThemeService=o.ICharacterJoinerService=o.ISelectionService=o.IRenderService=o.IMouseService=o.ICoreBrowserService=o.ICharSizeService=void 0;const c=l(8343);o.ICharSizeService=(0,c.createDecorator)("CharSizeService"),o.ICoreBrowserService=(0,c.createDecorator)("CoreBrowserService"),o.IMouseService=(0,c.createDecorator)("MouseService"),o.IRenderService=(0,c.createDecorator)("RenderService"),o.ISelectionService=(0,c.createDecorator)("SelectionService"),o.ICharacterJoinerService=(0,c.createDecorator)("CharacterJoinerService"),o.IThemeService=(0,c.createDecorator)("ThemeService"),o.ILinkProviderService=(0,c.createDecorator)("LinkProviderService")},6731:function(a,o,l){var c=this&&this.__decorate||function(E,S,k,O){var T,R=arguments.length,N=R<3?S:O===null?O=Object.getOwnPropertyDescriptor(S,k):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(E,S,k,O);else for(var M=E.length-1;M>=0;M--)(T=E[M])&&(N=(R<3?T(N):R>3?T(S,k,N):T(S,k))||N);return R>3&&N&&Object.defineProperty(S,k,N),N},u=this&&this.__param||function(E,S){return function(k,O){S(k,O,E)}};Object.defineProperty(o,"__esModule",{value:!0}),o.ThemeService=o.DEFAULT_ANSI_COLORS=void 0;const d=l(7239),h=l(8055),m=l(8460),b=l(844),g=l(2585),p=h.css.toColor("#ffffff"),y=h.css.toColor("#000000"),v=h.css.toColor("#ffffff"),_=h.css.toColor("#000000"),w={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};o.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const E=[h.css.toColor("#2e3436"),h.css.toColor("#cc0000"),h.css.toColor("#4e9a06"),h.css.toColor("#c4a000"),h.css.toColor("#3465a4"),h.css.toColor("#75507b"),h.css.toColor("#06989a"),h.css.toColor("#d3d7cf"),h.css.toColor("#555753"),h.css.toColor("#ef2929"),h.css.toColor("#8ae234"),h.css.toColor("#fce94f"),h.css.toColor("#729fcf"),h.css.toColor("#ad7fa8"),h.css.toColor("#34e2e2"),h.css.toColor("#eeeeec")],S=[0,95,135,175,215,255];for(let k=0;k<216;k++){const O=S[k/36%6|0],T=S[k/6%6|0],R=S[k%6];E.push({css:h.channels.toCss(O,T,R),rgba:h.channels.toRgba(O,T,R)})}for(let k=0;k<24;k++){const O=8+10*k;E.push({css:h.channels.toCss(O,O,O),rgba:h.channels.toRgba(O,O,O)})}return E})());let C=o.ThemeService=class extends b.Disposable{get colors(){return this._colors}constructor(E){super(),this._optionsService=E,this._contrastCache=new d.ColorContrastCache,this._halfContrastCache=new d.ColorContrastCache,this._onChangeColors=this.register(new m.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:p,background:y,cursor:v,cursorAccent:_,selectionForeground:void 0,selectionBackgroundTransparent:w,selectionBackgroundOpaque:h.color.blend(y,w),selectionInactiveBackgroundTransparent:w,selectionInactiveBackgroundOpaque:h.color.blend(y,w),ansi:o.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this.register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}_setTheme(E={}){const S=this._colors;if(S.foreground=A(E.foreground,p),S.background=A(E.background,y),S.cursor=A(E.cursor,v),S.cursorAccent=A(E.cursorAccent,_),S.selectionBackgroundTransparent=A(E.selectionBackground,w),S.selectionBackgroundOpaque=h.color.blend(S.background,S.selectionBackgroundTransparent),S.selectionInactiveBackgroundTransparent=A(E.selectionInactiveBackground,S.selectionBackgroundTransparent),S.selectionInactiveBackgroundOpaque=h.color.blend(S.background,S.selectionInactiveBackgroundTransparent),S.selectionForeground=E.selectionForeground?A(E.selectionForeground,h.NULL_COLOR):void 0,S.selectionForeground===h.NULL_COLOR&&(S.selectionForeground=void 0),h.color.isOpaque(S.selectionBackgroundTransparent)&&(S.selectionBackgroundTransparent=h.color.opacity(S.selectionBackgroundTransparent,.3)),h.color.isOpaque(S.selectionInactiveBackgroundTransparent)&&(S.selectionInactiveBackgroundTransparent=h.color.opacity(S.selectionInactiveBackgroundTransparent,.3)),S.ansi=o.DEFAULT_ANSI_COLORS.slice(),S.ansi[0]=A(E.black,o.DEFAULT_ANSI_COLORS[0]),S.ansi[1]=A(E.red,o.DEFAULT_ANSI_COLORS[1]),S.ansi[2]=A(E.green,o.DEFAULT_ANSI_COLORS[2]),S.ansi[3]=A(E.yellow,o.DEFAULT_ANSI_COLORS[3]),S.ansi[4]=A(E.blue,o.DEFAULT_ANSI_COLORS[4]),S.ansi[5]=A(E.magenta,o.DEFAULT_ANSI_COLORS[5]),S.ansi[6]=A(E.cyan,o.DEFAULT_ANSI_COLORS[6]),S.ansi[7]=A(E.white,o.DEFAULT_ANSI_COLORS[7]),S.ansi[8]=A(E.brightBlack,o.DEFAULT_ANSI_COLORS[8]),S.ansi[9]=A(E.brightRed,o.DEFAULT_ANSI_COLORS[9]),S.ansi[10]=A(E.brightGreen,o.DEFAULT_ANSI_COLORS[10]),S.ansi[11]=A(E.brightYellow,o.DEFAULT_ANSI_COLORS[11]),S.ansi[12]=A(E.brightBlue,o.DEFAULT_ANSI_COLORS[12]),S.ansi[13]=A(E.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),S.ansi[14]=A(E.brightCyan,o.DEFAULT_ANSI_COLORS[14]),S.ansi[15]=A(E.brightWhite,o.DEFAULT_ANSI_COLORS[15]),E.extendedAnsi){const k=Math.min(S.ansi.length-16,E.extendedAnsi.length);for(let O=0;O<k;O++)S.ansi[O+16]=A(E.extendedAnsi[O],o.DEFAULT_ANSI_COLORS[O+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(E){this._restoreColor(E),this._onChangeColors.fire(this.colors)}_restoreColor(E){if(E!==void 0)switch(E){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[E]=this._restoreColors.ansi[E]}else for(let S=0;S<this._restoreColors.ansi.length;++S)this._colors.ansi[S]=this._restoreColors.ansi[S]}modifyColors(E){E(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function A(E,S){if(E!==void 0)try{return h.css.toColor(E)}catch{}return S}o.ThemeService=C=c([u(0,g.IOptionsService)],C)},6349:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CircularList=void 0;const c=l(8460),u=l(844);class d extends u.Disposable{constructor(m){super(),this._maxLength=m,this.onDeleteEmitter=this.register(new c.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new c.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new c.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(m){if(this._maxLength===m)return;const b=new Array(m);for(let g=0;g<Math.min(m,this.length);g++)b[g]=this._array[this._getCyclicIndex(g)];this._array=b,this._maxLength=m,this._startIndex=0}get length(){return this._length}set length(m){if(m>this._length)for(let b=this._length;b<m;b++)this._array[b]=void 0;this._length=m}get(m){return this._array[this._getCyclicIndex(m)]}set(m,b){this._array[this._getCyclicIndex(m)]=b}push(m){this._array[this._getCyclicIndex(this._length)]=m,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(m,b,...g){if(b){for(let p=m;p<this._length-b;p++)this._array[this._getCyclicIndex(p)]=this._array[this._getCyclicIndex(p+b)];this._length-=b,this.onDeleteEmitter.fire({index:m,amount:b})}for(let p=this._length-1;p>=m;p--)this._array[this._getCyclicIndex(p+g.length)]=this._array[this._getCyclicIndex(p)];for(let p=0;p<g.length;p++)this._array[this._getCyclicIndex(m+p)]=g[p];if(g.length&&this.onInsertEmitter.fire({index:m,amount:g.length}),this._length+g.length>this._maxLength){const p=this._length+g.length-this._maxLength;this._startIndex+=p,this._length=this._maxLength,this.onTrimEmitter.fire(p)}else this._length+=g.length}trimStart(m){m>this._length&&(m=this._length),this._startIndex+=m,this._length-=m,this.onTrimEmitter.fire(m)}shiftElements(m,b,g){if(!(b<=0)){if(m<0||m>=this._length)throw new Error("start argument out of range");if(m+g<0)throw new Error("Cannot shift elements in list beyond index 0");if(g>0){for(let y=b-1;y>=0;y--)this.set(m+y+g,this.get(m+y));const p=m+b+g-this._length;if(p>0)for(this._length+=p;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let p=0;p<b;p++)this.set(m+p+g,this.get(m+p))}}_getCyclicIndex(m){return(this._startIndex+m)%this._maxLength}}o.CircularList=d},1439:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.clone=void 0,o.clone=function l(c,u=5){if(typeof c!="object")return c;const d=Array.isArray(c)?[]:{};for(const h in c)d[h]=u<=1?c[h]:c[h]&&l(c[h],u-1);return d}},8055:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.contrastRatio=o.toPaddedHex=o.rgba=o.rgb=o.css=o.color=o.channels=o.NULL_COLOR=void 0;let l=0,c=0,u=0,d=0;var h,m,b,g,p;function y(_){const w=_.toString(16);return w.length<2?"0"+w:w}function v(_,w){return _<w?(w+.05)/(_+.05):(_+.05)/(w+.05)}o.NULL_COLOR={css:"#00000000",rgba:0},function(_){_.toCss=function(w,C,A,E){return E!==void 0?`#${y(w)}${y(C)}${y(A)}${y(E)}`:`#${y(w)}${y(C)}${y(A)}`},_.toRgba=function(w,C,A,E=255){return(w<<24|C<<16|A<<8|E)>>>0},_.toColor=function(w,C,A,E){return{css:_.toCss(w,C,A,E),rgba:_.toRgba(w,C,A,E)}}}(h||(o.channels=h={})),function(_){function w(C,A){return d=Math.round(255*A),[l,c,u]=p.toChannels(C.rgba),{css:h.toCss(l,c,u,d),rgba:h.toRgba(l,c,u,d)}}_.blend=function(C,A){if(d=(255&A.rgba)/255,d===1)return{css:A.css,rgba:A.rgba};const E=A.rgba>>24&255,S=A.rgba>>16&255,k=A.rgba>>8&255,O=C.rgba>>24&255,T=C.rgba>>16&255,R=C.rgba>>8&255;return l=O+Math.round((E-O)*d),c=T+Math.round((S-T)*d),u=R+Math.round((k-R)*d),{css:h.toCss(l,c,u),rgba:h.toRgba(l,c,u)}},_.isOpaque=function(C){return(255&C.rgba)==255},_.ensureContrastRatio=function(C,A,E){const S=p.ensureContrastRatio(C.rgba,A.rgba,E);if(S)return h.toColor(S>>24&255,S>>16&255,S>>8&255)},_.opaque=function(C){const A=(255|C.rgba)>>>0;return[l,c,u]=p.toChannels(A),{css:h.toCss(l,c,u),rgba:A}},_.opacity=w,_.multiplyOpacity=function(C,A){return d=255&C.rgba,w(C,d*A/255)},_.toColorRGB=function(C){return[C.rgba>>24&255,C.rgba>>16&255,C.rgba>>8&255]}}(m||(o.color=m={})),function(_){let w,C;try{const A=document.createElement("canvas");A.width=1,A.height=1;const E=A.getContext("2d",{willReadFrequently:!0});E&&(w=E,w.globalCompositeOperation="copy",C=w.createLinearGradient(0,0,1,1))}catch{}_.toColor=function(A){if(A.match(/#[\da-f]{3,8}/i))switch(A.length){case 4:return l=parseInt(A.slice(1,2).repeat(2),16),c=parseInt(A.slice(2,3).repeat(2),16),u=parseInt(A.slice(3,4).repeat(2),16),h.toColor(l,c,u);case 5:return l=parseInt(A.slice(1,2).repeat(2),16),c=parseInt(A.slice(2,3).repeat(2),16),u=parseInt(A.slice(3,4).repeat(2),16),d=parseInt(A.slice(4,5).repeat(2),16),h.toColor(l,c,u,d);case 7:return{css:A,rgba:(parseInt(A.slice(1),16)<<8|255)>>>0};case 9:return{css:A,rgba:parseInt(A.slice(1),16)>>>0}}const E=A.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(E)return l=parseInt(E[1]),c=parseInt(E[2]),u=parseInt(E[3]),d=Math.round(255*(E[5]===void 0?1:parseFloat(E[5]))),h.toColor(l,c,u,d);if(!w||!C)throw new Error("css.toColor: Unsupported css format");if(w.fillStyle=C,w.fillStyle=A,typeof w.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(w.fillRect(0,0,1,1),[l,c,u,d]=w.getImageData(0,0,1,1).data,d!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:h.toRgba(l,c,u,d),css:A}}}(b||(o.css=b={})),function(_){function w(C,A,E){const S=C/255,k=A/255,O=E/255;return .2126*(S<=.03928?S/12.92:Math.pow((S+.055)/1.055,2.4))+.7152*(k<=.03928?k/12.92:Math.pow((k+.055)/1.055,2.4))+.0722*(O<=.03928?O/12.92:Math.pow((O+.055)/1.055,2.4))}_.relativeLuminance=function(C){return w(C>>16&255,C>>8&255,255&C)},_.relativeLuminance2=w}(g||(o.rgb=g={})),function(_){function w(A,E,S){const k=A>>24&255,O=A>>16&255,T=A>>8&255;let R=E>>24&255,N=E>>16&255,M=E>>8&255,B=v(g.relativeLuminance2(R,N,M),g.relativeLuminance2(k,O,T));for(;B<S&&(R>0||N>0||M>0);)R-=Math.max(0,Math.ceil(.1*R)),N-=Math.max(0,Math.ceil(.1*N)),M-=Math.max(0,Math.ceil(.1*M)),B=v(g.relativeLuminance2(R,N,M),g.relativeLuminance2(k,O,T));return(R<<24|N<<16|M<<8|255)>>>0}function C(A,E,S){const k=A>>24&255,O=A>>16&255,T=A>>8&255;let R=E>>24&255,N=E>>16&255,M=E>>8&255,B=v(g.relativeLuminance2(R,N,M),g.relativeLuminance2(k,O,T));for(;B<S&&(R<255||N<255||M<255);)R=Math.min(255,R+Math.ceil(.1*(255-R))),N=Math.min(255,N+Math.ceil(.1*(255-N))),M=Math.min(255,M+Math.ceil(.1*(255-M))),B=v(g.relativeLuminance2(R,N,M),g.relativeLuminance2(k,O,T));return(R<<24|N<<16|M<<8|255)>>>0}_.blend=function(A,E){if(d=(255&E)/255,d===1)return E;const S=E>>24&255,k=E>>16&255,O=E>>8&255,T=A>>24&255,R=A>>16&255,N=A>>8&255;return l=T+Math.round((S-T)*d),c=R+Math.round((k-R)*d),u=N+Math.round((O-N)*d),h.toRgba(l,c,u)},_.ensureContrastRatio=function(A,E,S){const k=g.relativeLuminance(A>>8),O=g.relativeLuminance(E>>8);if(v(k,O)<S){if(O<k){const N=w(A,E,S),M=v(k,g.relativeLuminance(N>>8));if(M<S){const B=C(A,E,S);return M>v(k,g.relativeLuminance(B>>8))?N:B}return N}const T=C(A,E,S),R=v(k,g.relativeLuminance(T>>8));if(R<S){const N=w(A,E,S);return R>v(k,g.relativeLuminance(N>>8))?T:N}return T}},_.reduceLuminance=w,_.increaseLuminance=C,_.toChannels=function(A){return[A>>24&255,A>>16&255,A>>8&255,255&A]}}(p||(o.rgba=p={})),o.toPaddedHex=y,o.contrastRatio=v},8969:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreTerminal=void 0;const c=l(844),u=l(2585),d=l(4348),h=l(7866),m=l(744),b=l(7302),g=l(6975),p=l(8460),y=l(1753),v=l(1480),_=l(7994),w=l(9282),C=l(5435),A=l(5981),E=l(2660);let S=!1;class k extends c.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new p.EventEmitter),this._onScroll.event(T=>{this._onScrollApi?.fire(T.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(T){for(const R in T)this.optionsService.options[R]=T[R]}constructor(T){super(),this._windowsWrappingHeuristics=this.register(new c.MutableDisposable),this._onBinary=this.register(new p.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new p.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new p.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new p.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new p.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new p.EventEmitter),this._instantiationService=new d.InstantiationService,this.optionsService=this.register(new b.OptionsService(T)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(m.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(h.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(g.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(y.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(v.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(E.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new C.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,p.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,p.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,p.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,p.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(R=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(R=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new A.WriteBuffer((R,N)=>this._inputHandler.parse(R,N))),this.register((0,p.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(T,R){this._writeBuffer.write(T,R)}writeSync(T,R){this._logService.logLevel<=u.LogLevelEnum.WARN&&!S&&(this._logService.warn("writeSync is unreliable and will be removed soon."),S=!0),this._writeBuffer.writeSync(T,R)}input(T,R=!0){this.coreService.triggerDataEvent(T,R)}resize(T,R){isNaN(T)||isNaN(R)||(T=Math.max(T,m.MINIMUM_COLS),R=Math.max(R,m.MINIMUM_ROWS),this._bufferService.resize(T,R))}scroll(T,R=!1){this._bufferService.scroll(T,R)}scrollLines(T,R,N){this._bufferService.scrollLines(T,R,N)}scrollPages(T){this.scrollLines(T*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(T){const R=T-this._bufferService.buffer.ydisp;R!==0&&this.scrollLines(R)}registerEscHandler(T,R){return this._inputHandler.registerEscHandler(T,R)}registerDcsHandler(T,R){return this._inputHandler.registerDcsHandler(T,R)}
58registerCsiHandler(T,R){return this._inputHandler.registerCsiHandler(T,R)}registerOscHandler(T,R){return this._inputHandler.registerOscHandler(T,R)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let T=!1;const R=this.optionsService.rawOptions.windowsPty;R&&R.buildNumber!==void 0&&R.buildNumber!==void 0?T=R.backend==="conpty"&&R.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(T=!0),T?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const T=[];T.push(this.onLineFeed(w.updateWindowsModeWrappedState.bind(null,this._bufferService))),T.push(this.registerCsiHandler({final:"H"},()=>((0,w.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,c.toDisposable)(()=>{for(const R of T)R.dispose()})}}}o.CoreTerminal=k},8460:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=l=>(this._listeners.push(l),{dispose:()=>{if(!this._disposed){for(let c=0;c<this._listeners.length;c++)if(this._listeners[c]===l)return void this._listeners.splice(c,1)}}})),this._event}fire(l,c){const u=[];for(let d=0;d<this._listeners.length;d++)u.push(this._listeners[d]);for(let d=0;d<u.length;d++)u[d].call(void 0,l,c)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},o.forwardEvent=function(l,c){return l(u=>c.fire(u))},o.runAndSubscribe=function(l,c){return c(void 0),l(u=>c(u))}},5435:function(a,o,l){var c=this&&this.__decorate||function(oe,L,F,V){var Z,K=arguments.length,ie=K<3?L:V===null?V=Object.getOwnPropertyDescriptor(L,F):V;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")ie=Reflect.decorate(oe,L,F,V);else for(var se=oe.length-1;se>=0;se--)(Z=oe[se])&&(ie=(K<3?Z(ie):K>3?Z(L,F,ie):Z(L,F))||ie);return K>3&&ie&&Object.defineProperty(L,F,ie),ie},u=this&&this.__param||function(oe,L){return function(F,V){L(F,V,oe)}};Object.defineProperty(o,"__esModule",{value:!0}),o.InputHandler=o.WindowsOptionsReportType=void 0;const d=l(2584),h=l(7116),m=l(2015),b=l(844),g=l(482),p=l(8437),y=l(8460),v=l(643),_=l(511),w=l(3734),C=l(2585),A=l(1480),E=l(6242),S=l(6351),k=l(5941),O={"(":0,")":1,"*":2,"+":3,"-":1,".":2},T=131072;function R(oe,L){if(oe>24)return L.setWinLines||!1;switch(oe){case 1:return!!L.restoreWin;case 2:return!!L.minimizeWin;case 3:return!!L.setWinPosition;case 4:return!!L.setWinSizePixels;case 5:return!!L.raiseWin;case 6:return!!L.lowerWin;case 7:return!!L.refreshWin;case 8:return!!L.setWinSizeChars;case 9:return!!L.maximizeWin;case 10:return!!L.fullscreenWin;case 11:return!!L.getWinState;case 13:return!!L.getWinPosition;case 14:return!!L.getWinSizePixels;case 15:return!!L.getScreenSizePixels;case 16:return!!L.getCellSizePixels;case 18:return!!L.getWinSizeChars;case 19:return!!L.getScreenSizeChars;case 20:return!!L.getIconTitle;case 21:return!!L.getWinTitle;case 22:return!!L.pushTitle;case 23:return!!L.popTitle;case 24:return!!L.setWinLines}return!1}var N;(function(oe){oe[oe.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",oe[oe.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(N||(o.WindowsOptionsReportType=N={}));let M=0;class B extends b.Disposable{getAttrData(){return this._curAttrData}constructor(L,F,V,Z,K,ie,se,fe,Y=new m.EscapeSequenceParser){super(),this._bufferService=L,this._charsetService=F,this._coreService=V,this._logService=Z,this._optionsService=K,this._oscLinkService=ie,this._coreMouseService=se,this._unicodeService=fe,this._parser=Y,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new g.StringToUtf32,this._utf8Decoder=new g.Utf8ToUtf32,this._workCell=new _.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new y.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new y.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new y.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new y.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new y.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new y.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new y.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new y.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new y.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new y.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new y.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new U(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(I=>
vendor: 9,464 bytes, line 58
58this._activeBuffer=I.activeBuffer)),this._parser.setCsiHandlerFallback((I,z)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:z.toArray()})}),this._parser.setEscHandlerFallback(I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})}),this._parser.setExecuteHandlerFallback(I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})}),this._parser.setOscHandlerFallback((I,z,q)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:z,data:q})}),this._parser.setDcsHandlerFallback((I,z,q)=>{z==="HOOK"&&(q=q.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:z,payload:q})}),this._parser.setPrintHandler((I,z,q)=>this.print(I,z,q)),this._parser.registerCsiHandler({final:"@"},I=>this.insertChars(I)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},I=>this.scrollLeft(I)),this._parser.registerCsiHandler({final:"A"},I=>this.cursorUp(I)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},I=>this.scrollRight(I)),this._parser.registerCsiHandler({final:"B"},I=>this.cursorDown(I)),this._parser.registerCsiHandler({final:"C"},I=>this.cursorForward(I)),this._parser.registerCsiHandler({final:"D"},I=>this.cursorBackward(I)),this._parser.registerCsiHandler({final:"E"},I=>this.cursorNextLine(I)),this._parser.registerCsiHandler({final:"F"},I=>this.cursorPrecedingLine(I)),this._parser.registerCsiHandler({final:"G"},I=>this.cursorCharAbsolute(I)),this._parser.registerCsiHandler({final:"H"},I=>this.cursorPosition(I)),this._parser.registerCsiHandler({final:"I"},I=>this.cursorForwardTab(I)),this._parser.registerCsiHandler({final:"J"},I=>this.eraseInDisplay(I,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},I=>this.eraseInDisplay(I,!0)),this._parser.registerCsiHandler({final:"K"},I=>this.eraseInLine(I,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},I=>this.eraseInLine(I,!0)),this._parser.registerCsiHandler({final:"L"},I=>this.insertLines(I)),this._parser.registerCsiHandler({final:"M"},I=>this.deleteLines(I)),this._parser.registerCsiHandler({final:"P"},I=>this.deleteChars(I)),this._parser.registerCsiHandler({final:"S"},I=>this.scrollUp(I)),this._parser.registerCsiHandler({final:"T"},I=>this.scrollDown(I)),this._parser.registerCsiHandler({final:"X"},I=>this.eraseChars(I)),this._parser.registerCsiHandler({final:"Z"},I=>this.cursorBackwardTab(I)),this._parser.registerCsiHandler({final:"`"},I=>this.charPosAbsolute(I)),this._parser.registerCsiHandler({final:"a"},I=>this.hPositionRelative(I)),this._parser.registerCsiHandler({final:"b"},I=>this.repeatPrecedingCharacter(I)),this._parser.registerCsiHandler({final:"c"},I=>this.sendDeviceAttributesPrimary(I)),this._parser.registerCsiHandler({prefix:">",final:"c"},I=>this.sendDeviceAttributesSecondary(I)),this._parser.registerCsiHandler({final:"d"},I=>this.linePosAbsolute(I)),this._parser.registerCsiHandler({final:"e"},I=>this.vPositionRelative(I)),this._parser.registerCsiHandler({final:"f"},I=>this.hVPosition(I)),this._parser.registerCsiHandler({final:"g"},I=>this.tabClear(I)),this._parser.registerCsiHandler({final:"h"},I=>this.setMode(I)),this._parser.registerCsiHandler({prefix:"?",final:"h"},I=>this.setModePrivate(I)),this._parser.registerCsiHandler({final:"l"},I=>this.resetMode(I)),this._parser.registerCsiHandler({prefix:"?",final:"l"},I=>this.resetModePrivate(I)),this._parser.registerCsiHandler({final:"m"},I=>this.charAttributes(I)),this._parser.registerCsiHandler({final:"n"},I=>this.deviceStatus(I)),this._parser.registerCsiHandler({prefix:"?",final:"n"},I=>this.deviceStatusPrivate(I)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},I=>this.softReset(I)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},I=>this.setCursorStyle(I)),this._parser.registerCsiHandler({final:"r"},I=>this.setScrollRegion(I)),this._parser.registerCsiHandler({final:"s"},I=>this.saveCursor(I)),this._parser.registerCsiHandler({final:"t"},I=>this.windowOptions(I)),this._parser.registerCsiHandler({final:"u"},I=>this.restoreCursor(I)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},I=>this.insertColumns(I)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},I=>this.deleteColumns(I)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},I=>this.selectProtected(I)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},I=>this.requestMode(I,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},I=>this.requestMode(I,!1)),this._parser.setExecuteHandler(d.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(d.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(d.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(d.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(d.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(d.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(d.C1.IND,()=>this.index()),this._parser.setExecuteHandler(d.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(d.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new E.OscHandler(I=>(this.setTitle(I),this.setIconName(I),!0))),this._parser.registerOscHandler(1,new E.OscHandler(I=>this.setIconName(I))),this._parser.registerOscHandler(2,new E.OscHandler(I=>this.setTitle(I))),this._parser.registerOscHandler(4,new E.OscHandler(I=>this.setOrReportIndexedColor(I))),this._parser.registerOscHandler(8,new E.OscHandler(I=>this.setHyperlink(I))),this._parser.registerOscHandler(10,new E.OscHandler(I=>this.setOrReportFgColor(I))),this._parser.registerOscHandler(11,new E.OscHandler(I=>this.setOrReportBgColor(I))),this._parser.registerOscHandler(12,new E.OscHandler(I=>this.setOrReportCursorColor(I))),this._parser.registerOscHandler(104,new E.OscHandler(I=>this.restoreIndexedColor(I))),this._parser.registerOscHandler(110,new E.OscHandler(I=>this.restoreFgColor(I))),this._parser.registerOscHandler(111,new E.OscHandler(I=>this.restoreBgColor(I))),this._parser.registerOscHandler(112,new E.OscHandler(I=>this.restoreCursorColor(I))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(const I in h.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},()=>this.selectCharset("("+I)),this._parser.registerEscHandler({intermediates:")",final:I},()=>this.selectCharset(")"+I)),this._parser.registerEscHandler({intermediates:"*",final:I},()=>this.selectCharset("*"+I)),this._parser.registerEscHandler({intermediates:"+",final:I},()=>this.selectCharset("+"+I)),this._parser.registerEscHandler({intermediates:"-",final:I},()=>this.selectCharset("-"+I)),this._parser.registerEscHandler({intermediates:".",final:I},()=>this.selectCharset("."+I)),this._parser.registerEscHandler({intermediates:"/",final:I},()=>this.selectCharset("/"+I));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(I=>(this._logService.error("Parsing error: ",I),I)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new S.DcsHandler((I,z)=>this.requestStatusString(I,z)))}_preserveStack(L,F,V,Z){this._parseStack.paused=!0,this._parseStack.cursorStartX=L,this._parseStack.cursorStartY=F,this._parseStack.decodedLength=V,this._parseStack.position=Z}_logSlowResolvingAsync(L){this._logService.logLevel<=C.LogLevelEnum.WARN&&Promise.race([L,new Promise((F,V)=>setTimeout(()=>V("#SLOW_TIMEOUT"),5e3))]).catch(F=>{if(F!=="#SLOW_TIMEOUT")throw F;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(L,F){let V,Z=this._activeBuffer.x,K=this._activeBuffer.y,ie=0;const se=this._parseStack.paused;if(se){if(V=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,F))return this._logSlowResolvingAsync(V),V;Z=this._parseStack.cursorStartX,K=this._parseStack.cursorStartY,this._parseStack.paused=!1,L.length>T&&(ie=this._parseStack.position+T)}if(this._logService.logLevel<=C.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof L=="string"?` "${L}"`:` "${Array.prototype.map.call(L,I=>String.fromCharCode(I)).join("")}"`),typeof L=="string"?L.split("").map(I=>
58I.charCodeAt(0)):L),this._parseBuffer.length<L.length&&this._parseBuffer.length<T&&(this._parseBuffer=new Uint32Array(Math.min(L.length,T))),se||this._dirtyRowTracker.clearRange(),L.length>T)for(let I=ie;I<L.length;I+=T){const z=I+T<L.length?I+T:L.length,q=typeof L=="string"?this._stringDecoder.decode(L.substring(I,z),this._parseBuffer):this._utf8Decoder.decode(L.subarray(I,z),this._parseBuffer);if(V=this._parser.parse(this._parseBuffer,q))return this._preserveStack(Z,K,q,I),this._logSlowResolvingAsync(V),V}else if(!se){const I=typeof L=="string"?this._stringDecoder.decode(L,this._parseBuffer):this._utf8Decoder.decode(L,this._parseBuffer);if(V=this._parser.parse(this._parseBuffer,I))return this._preserveStack(Z,K,I,0),this._logSlowResolvingAsync(V),V}this._activeBuffer.x===Z&&this._activeBuffer.y===K||this._onCursorMove.fire();const fe=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),Y=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);Y<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(Y,this._bufferService.rows-1),Math.min(fe,this._bufferService.rows-1))}print(L,F,V){let Z,K;const ie=this._charsetService.charset,se=this._optionsService.rawOptions.screenReaderMode,fe=this._bufferService.cols,Y=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,z=this._curAttrData;let q=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&V-F>0&&q.getWidth(this._activeBuffer.x-1)===2&&q.setCellFromCodepoint(this._activeBuffer.x-1,0,1,z);let ae=this._parser.precedingJoinState;for(let ee=F;ee<V;++ee){if(Z=L[ee],Z<127&&ie){const Ae=ie[String.fromCharCode(Z)];Ae&&(Z=Ae.charCodeAt(0))}const le=this._unicodeService.charProperties(Z,ae);K=A.UnicodeService.extractWidth(le);const ve=A.UnicodeService.extractShouldJoin(le),ye=ve?A.UnicodeService.extractWidth(ae):0;if(ae=le,se&&this._onA11yChar.fire((0,g.stringFromCodePoint)(Z)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+K-ye>fe){if(Y){const Ae=q;let we=this._activeBuffer.x-ye;for(this._activeBuffer.x=ye,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),q=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),ye>0&&q instanceof p.BufferLine&&q.copyCellsFrom(Ae,we,0,ye,!1);we<fe;)Ae.setCellFromCodepoint(we++,0,1,z)}else if(this._activeBuffer.x=fe-1,K===2)continue}if(ve&&this._activeBuffer.x){const Ae=q.getWidth(this._activeBuffer.x-1)?1:2;q.addCodepointToCell(this._activeBuffer.x-Ae,Z,K);for(let we=K-ye;--we>=0;)q.setCellFromCodepoint(this._activeBuffer.x++,0,0,z)}else if(I&&(q.insertCells(this._activeBuffer.x,K-ye,this._activeBuffer.getNullCell(z)),q.getWidth(fe-1)===2&&q.setCellFromCodepoint(fe-1,v.NULL_CELL_CODE,v.NULL_CELL_WIDTH,z)),q.setCellFromCodepoint(this._activeBuffer.x++,Z,K,z),K>0)for(;--K;)q.setCellFromCodepoint(this._activeBuffer.x++,0,0,z)}this._parser.precedingJoinState=ae,this._activeBuffer.x<fe&&V-F>0&&q.getWidth(this._activeBuffer.x)===0&&!q.hasContent(this._activeBuffer.x)&&q.setCellFromCodepoint(this._activeBuffer.x,0,1,z),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(L,F){return L.final!=="t"||L.prefix||L.intermediates?this._parser.registerCsiHandler(L,F):this._parser.registerCsiHandler(L,V=>!R(V.params[0],this._optionsService.rawOptions.windowOptions)||F(V))}registerDcsHandler(L,F){return this._parser.registerDcsHandler(L,new S.DcsHandler(F))}registerEscHandler(L,F){return this._parser.registerEscHandler(L,F)}registerOscHandler(L,F){return this._parser.registerOscHandler(L,new E.OscHandler(F))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>
vendor: 15,552 bytes, line 58
58=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const L=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);L.hasWidth(this._activeBuffer.x)&&!L.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const L=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-L),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(L=this._bufferService.cols-1){this._activeBuffer.x=Math.min(L,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(L,F){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=L,this._activeBuffer.y=this._activeBuffer.scrollTop+F):(this._activeBuffer.x=L,this._activeBuffer.y=F),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(L,F){this._restrictCursor(),this._setCursor(this._activeBuffer.x+L,this._activeBuffer.y+F)}cursorUp(L){const F=this._activeBuffer.y-this._activeBuffer.scrollTop;return F>=0?this._moveCursor(0,-Math.min(F,L.params[0]||1)):this._moveCursor(0,-(L.params[0]||1)),!0}cursorDown(L){const F=this._activeBuffer.scrollBottom-this._activeBuffer.y;return F>=0?this._moveCursor(0,Math.min(F,L.params[0]||1)):this._moveCursor(0,L.params[0]||1),!0}cursorForward(L){return this._moveCursor(L.params[0]||1,0),!0}cursorBackward(L){return this._moveCursor(-(L.params[0]||1),0),!0}cursorNextLine(L){return this.cursorDown(L),this._activeBuffer.x=0,!0}cursorPrecedingLine(L){return this.cursorUp(L),this._activeBuffer.x=0,!0}cursorCharAbsolute(L){return this._setCursor((L.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(L){return this._setCursor(L.length>=2?(L.params[1]||1)-1:0,(L.params[0]||1)-1),!0}charPosAbsolute(L){return this._setCursor((L.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(L){return this._moveCursor(L.params[0]||1,0),!0}linePosAbsolute(L){return this._setCursor(this._activeBuffer.x,(L.params[0]||1)-1),!0}vPositionRelative(L){return this._moveCursor(0,L.params[0]||1),!0}hVPosition(L){return this.cursorPosition(L),!0}tabClear(L){const F=L.params[0];return F===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:F===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(L){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let F=L.params[0]||1;for(;F--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(L){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let F=L.params[0]||1;for(;F--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(L){const F=L.params[0];return F===1&&(this._curAttrData.bg|=536870912),F!==2&&F!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(L,F,V,Z=!1,K=!1){const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);ie.replaceCells(F,V,this._activeBuffer.getNullCell(this._eraseAttrData()),K),Z&&(ie.isWrapped=!1)}_resetBufferLine(L,F=!1){const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);V&&(V.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),F),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+L),V.isWrapped=!1)}eraseInDisplay(L,F=!1){let V;switch(this._restrictCursor(this._bufferService.cols),L.params[0]){case 0:for(V=this._activeBuffer.y,this._dirtyRowTracker.markDirty(V),this._eraseInBufferLine(V++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,F);V<this._bufferService.rows;V++)this._resetBufferLine(V,F);this._dirtyRowTracker.markDirty(V);break;case 1:for(V=this._activeBuffer.y,this._dirtyRowTracker.markDirty(V),this._eraseInBufferLine(V,0,this._activeBuffer.x+1,!0,F),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(V+1).isWrapped=!1);V--;)this._resetBufferLine(V,F);this._dirtyRowTracker.markDirty(0);break;case 2:for(V=this._bufferService.rows,this._dirtyRowTracker.markDirty(V-1);V--;)this._resetBufferLine(V,F);this._dirtyRowTracker.markDirty(0);break;case 3:const Z=this._activeBuffer.lines.length-this._bufferService.rows;Z>0&&(this._activeBuffer.lines.trimStart(Z),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-Z,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-Z,0),this._onScroll.fire(0))}return!0}eraseInLine(L,F=!1){switch(this._restrictCursor(this._bufferService.cols),L.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,F);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,F);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,F)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(L){this._restrictCursor();let F=L.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=this._activeBuffer.ybase+this._activeBuffer.y,Z=this._bufferService.rows-1-this._activeBuffer.scrollBottom,K=this._bufferService.rows-1+this._activeBuffer.ybase-Z+1;for(;F--;)this._activeBuffer.lines.splice(K-1,1),this._activeBuffer.lines.splice(V,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(L){this._restrictCursor();let F=L.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=this._activeBuffer.ybase+this._activeBuffer.y;let Z;for(Z=this._bufferService.rows-1-this._activeBuffer.scrollBottom,Z=this._bufferService.rows-1+this._activeBuffer.ybase-Z;F--;)this._activeBuffer.lines.splice(V,1),this._activeBuffer.lines.splice(Z,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(L){this._restrictCursor();const F=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return F&&(F.insertCells(this._activeBuffer.x,L.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(L){this._restrictCursor();const F=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return F&&(F.deleteCells(this._activeBuffer.x,L.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(L){let F=L.params[0]||1;for(;F--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(L){let F=L.params[0]||1;for(;F--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(p.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const F=L.params[0]||1;for(let V=this._activeBuffer.scrollTop;V<=this._activeBuffer.scrollBottom;++V){const Z=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);Z.deleteCells(0,F,this._activeBuffer.getNullCell(this._eraseAttrData())),Z.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const F=L.params[0]||1;for(let V=this._activeBuffer.scrollTop;V<=this._activeBuffer.scrollBottom;++V){const Z=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);Z.insertCells(0,F,this._activeBuffer.getNullCell(this._eraseAttrData())),Z.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const F=L.params[0]||1;for(let V=this._activeBuffer.scrollTop;V<=this._activeBuffer.scrollBottom;++V){const Z=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);Z.insertCells(this._activeBuffer.x,F,this._activeBuffer.getNullCell(this._eraseAttrData())),Z.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const F=L.params[0]||1;for(let V=this._activeBuffer.scrollTop;V<=this._activeBuffer.scrollBottom;++V){const Z=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);Z.deleteCells(this._activeBuffer.x,F,this._activeBuffer.getNullCell(this._eraseAttrData())),Z.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(L){this._restrictCursor();const F=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return F&&(F.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(L.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(L){const F=this._parser.precedingJoinState;if(!F)return!0;const V=L.params[0]||1,Z=A.UnicodeService.extractWidth(F),K=this._activeBuffer.x-Z,ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(K),se=new Uint32Array(ie.length*V);let fe=0;for(let I=0;I<ie.length;){const z=ie.codePointAt(I)||0;se[fe++]=z,I+=z>65535?2:1}let Y=fe;for(let I=1;I<V;++I)se.copyWithin(Y,0,fe),Y+=fe;return this.print(se,0,Y),!0}sendDeviceAttributesPrimary(L){return L.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(d.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(d.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(L){return L.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(d.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(d.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(L.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(d.C0.ESC+"[>83;40003;0c")),!0}_is(L){return(this._optionsService.rawOptions.termName+"").indexOf(L)===0}setMode(L){for(let F=0;F<L.length;F++)switch(L.params[F]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(L){for(let F=0;F<L.length;F++)switch(L.params[F]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,h.DEFAULT_CHARSET),this._charsetService.setgCharset(1,h.DEFAULT_CHARSET),this._charsetService.setgCharset(2,h.DEFAULT_CHARSET),this._charsetService.setgCharset(3,h.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(L){for(let F=0;F<L.length;F++)switch(L.params[F]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(L){for(let F=0;F<L.length;F++)switch(L.params[F]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;
vendor: 5,121 bytes, line 58
58case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),L.params[F]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(L,F){const V=this._coreService.decPrivateModes,{activeProtocol:Z,activeEncoding:K}=this._coreMouseService,ie=this._coreService,{buffers:se,cols:fe}=this._bufferService,{active:Y,alt:I}=se,z=this._optionsService.rawOptions,q=ve=>ve?1:2,ae=L.params[0];return ee=ae,le=F?ae===2?4:ae===4?q(ie.modes.insertMode):ae===12?3:ae===20?q(z.convertEol):0:ae===1?q(V.applicationCursorKeys):ae===3?z.windowOptions.setWinLines?fe===80?2:fe===132?1:0:0:ae===6?q(V.origin):ae===7?q(V.wraparound):ae===8?3:ae===9?q(Z==="X10"):ae===12?q(z.cursorBlink):ae===25?q(!ie.isCursorHidden):ae===45?q(V.reverseWraparound):ae===66?q(V.applicationKeypad):ae===67?4:ae===1e3?q(Z==="VT200"):ae===1002?q(Z==="DRAG"):ae===1003?q(Z==="ANY"):ae===1004?q(V.sendFocus):ae===1005?4:ae===1006?q(K==="SGR"):ae===1015?4:ae===1016?q(K==="SGR_PIXELS"):ae===1048?1:ae===47||ae===1047||ae===1049?q(Y===I):ae===2004?q(V.bracketedPasteMode):0,ie.triggerDataEvent(`${d.C0.ESC}[${F?"":"?"}${ee};${le}$y`),!0;var ee,le}_updateAttrColor(L,F,V,Z,K){return F===2?(L|=50331648,L&=-16777216,L|=w.AttributeData.fromColorRGB([V,Z,K])):F===5&&(L&=-50331904,L|=33554432|255&V),L}_extractColor(L,F,V){const Z=[0,0,-1,0,0,0];let K=0,ie=0;do{if(Z[ie+K]=L.params[F+ie],L.hasSubParams(F+ie)){const se=L.getSubParams(F+ie);let fe=0;do Z[1]===5&&(K=1),Z[ie+fe+1+K]=se[fe];while(++fe<se.length&&fe+ie+1+K<Z.length);break}if(Z[1]===5&&ie+K>=2||Z[1]===2&&ie+K>=5)break;Z[1]&&(K=1)}while(++ie+F<L.length&&ie+K<Z.length);for(let se=2;se<Z.length;++se)Z[se]===-1&&(Z[se]=0);switch(Z[0]){case 38:V.fg=this._updateAttrColor(V.fg,Z[1],Z[3],Z[4],Z[5]);break;case 48:V.bg=this._updateAttrColor(V.bg,Z[1],Z[3],Z[4],Z[5]);break;case 58:V.extended=V.extended.clone(),V.extended.underlineColor=this._updateAttrColor(V.extended.underlineColor,Z[1],Z[3],Z[4],Z[5])}return ie}_processUnderline(L,F){F.extended=F.extended.clone(),(!~L||L>5)&&(L=1),F.extended.underlineStyle=L,F.fg|=268435456,L===0&&(F.fg&=-268435457),F.updateExtended()}_processSGR0(L){L.fg=p.DEFAULT_ATTR_DATA.fg,L.bg=p.DEFAULT_ATTR_DATA.bg,L.extended=L.extended.clone(),L.extended.underlineStyle=0,L.extended.underlineColor&=-67108864,L.updateExtended()}charAttributes(L){if(L.length===1&&L.params[0]===0)return this._processSGR0(this._curAttrData),!0;const F=L.length;let V;const Z=this._curAttrData;for(let K=0;K<F;K++)V=L.params[K],V>=30&&V<=37?(Z.fg&=-50331904,Z.fg|=16777216|V-30):V>=40&&V<=47?(Z.bg&=-50331904,Z.bg|=16777216|V-40):V>=90&&V<=97?(Z.fg&=-50331904,Z.fg|=16777224|V-90):V>=100&&V<=107?(Z.bg&=-50331904,Z.bg|=16777224|V-100):V===0?this._processSGR0(Z):V===1?Z.fg|=134217728:V===3?Z.bg|=67108864:V===4?(Z.fg|=268435456,this._processUnderline(L.hasSubParams(K)?L.getSubParams(K)[0]:1,Z)):V===5?Z.fg|=536870912:V===7?Z.fg|=67108864:V===8?Z.fg|=1073741824:V===9?Z.fg|=2147483648:V===2?Z.bg|=134217728:V===21?this._processUnderline(2,Z):V===22?(Z.fg&=-134217729,Z.bg&=-134217729):V===23?Z.bg&=-67108865:V===24?(Z.fg&=-268435457,this._processUnderline(0,Z)):V===25?Z.fg&=-536870913:V===27?Z.fg&=-67108865:V===28?Z.fg&=-1073741825:V===29?Z.fg&=2147483647:V===39?(Z.fg&=-67108864,Z.fg|=16777215&p.DEFAULT_ATTR_DATA.fg):V===49?(Z.bg&=-67108864,Z.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):V===38||V===48||V===58?K+=this._extractColor(L,K,Z):V===53?Z.bg|=1073741824:V===55?Z.bg&=-1073741825:V===59?(Z.extended=Z.extended.clone(),Z.extended.underlineColor=-1,Z.updateExtended()):V===100?(Z.fg&=-67108864,Z.fg|=16777215&p.DEFAULT_ATTR_DATA.fg,Z.bg&=-67108864,Z.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",V);return!0}deviceStatus(L){switch(L.params[0]){case 5:this._coreService.triggerDataEvent(`${d.C0.ESC}[0n`);break;case 6:const F=this._activeBuffer.y+1,V=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[${F};${V}R`)}return!0}deviceStatusPrivate(L){if(L.params[0]===6){const F=this._activeBuffer.y+1,V=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[?${F};${V}R`)}return!0}softReset(L){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=p.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(L){const F=L.params[0]||1;switch(F){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;
58case 5:case 6:this._optionsService.options.cursorStyle="bar"}const V=F%2==1;return this._optionsService.options.cursorBlink=V,!0}setScrollRegion(L){const F=L.params[0]||1;let V;return(L.length<2||(V=L.params[1])>this._bufferService.rows||V===0)&&(V=this._bufferService.rows),V>F&&(this._activeBuffer.scrollTop=F-1,this._activeBuffer.scrollBottom=V-1,this._setCursor(0,0)),!0}windowOptions(L){if(!R(L.params[0],this._optionsService.rawOptions.windowOptions))return!0;const F=L.length>1?L.params[1]:0;switch(L.params[0]){case 14:F!==2&&this._onRequestWindowsOptionsReport.fire(N.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(N.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${d.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:F!==0&&F!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),F!==0&&F!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:F!==0&&F!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),F!==0&&F!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(L){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(L){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(L){return this._windowTitle=L,this._onTitleChange.fire(L),!0}setIconName(L){return this._iconName=L,!0}setOrReportIndexedColor(L){const F=[],V=L.split(";");for(;V.length>1;){const Z=V.shift(),K=V.shift();if(/^\d+$/.exec(Z)){const ie=parseInt(Z);if(X(ie))if(K==="?")F.push({type:0,index:ie});else{const se=(0,k.parseColor)(K);se&&F.push({type:1,index:ie,color:se})}}}return F.length&&this._onColor.fire(F),!0}setHyperlink(L){const F=L.split(";");return!(F.length<2)&&(F[1]?this._createHyperlink(F[0],F[1]):!F[0]&&this._finishHyperlink())}_createHyperlink(L,F){this._getCurrentLinkId()&&this._finishHyperlink();const V=L.split(":");let Z;const K=V.findIndex(ie=>ie.startsWith("id="));return K!==-1&&(Z=V[K].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:Z,uri:F}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(L,F){const V=L.split(";");for(let Z=0;Z<V.length&&!(F>=this._specialColors.length);++Z,++F)if(V[Z]==="?")this._onColor.fire([{type:0,index:this._specialColors[F]}]);else{const K=(0,k.parseColor)(V[Z]);K&&this._onColor.fire([{type:1,index:this._specialColors[F],color:K}])}return!0}setOrReportFgColor(L){return this._setOrReportSpecialColor(L,0)}setOrReportBgColor(L){return this._setOrReportSpecialColor(L,1)}setOrReportCursorColor(L){return this._setOrReportSpecialColor(L,2)}restoreIndexedColor(L){if(!L)return this._onColor.fire([{type:2}]),!0;const F=[],V=L.split(";");for(let Z=0;Z<V.length;++Z)if(/^\d+$/.exec(V[Z])){const K=parseInt(V[Z]);X(K)&&F.push({type:2,index:K})}return F.length&&this._onColor.fire(F),!0}restoreFgColor(L){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(L){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(L){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,h.DEFAULT_CHARSET),!0}selectCharset(L){return L.length!==2?(this.selectDefaultCharset(),!0):(L[0]==="/"||this._charsetService.setgCharset(O[L[0]],h.CHARSETS[L[1]]||h.DEFAULT_CHARSET),!0)}
vendor: 13,235 bytes, line 58
58index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const L=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,L,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(L){return this._charsetService.setgLevel(L),!0}screenAlignmentPattern(){const L=new _.CellData;L.content=4194373,L.fg=this._curAttrData.fg,L.bg=this._curAttrData.bg,this._setCursor(0,0);for(let F=0;F<this._bufferService.rows;++F){const V=this._activeBuffer.ybase+this._activeBuffer.y+F,Z=this._activeBuffer.lines.get(V);Z&&(Z.fill(L),Z.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(L,F){const V=this._bufferService.buffer,Z=this._optionsService.rawOptions;return(K=>(this._coreService.triggerDataEvent(`${d.C0.ESC}${K}${d.C0.ESC}\\`),!0))(L==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:L==='"p'?'P1$r61;1"p':L==="r"?`P1$r${V.scrollTop+1};${V.scrollBottom+1}r`:L==="m"?"P1$r0m":L===" q"?`P1$r${{block:2,underline:4,bar:6}[Z.cursorStyle]-(Z.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(L,F){this._dirtyRowTracker.markRangeDirty(L,F)}}o.InputHandler=B;let U=class{constructor(oe){this._bufferService=oe,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(oe){oe<this.start?this.start=oe:oe>this.end&&(this.end=oe)}markRangeDirty(oe,L){oe>L&&(M=oe,oe=L,L=M),oe<this.start&&(this.start=oe),L>this.end&&(this.end=L)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function X(oe){return 0<=oe&&oe<256}U=c([u(0,C.IBufferService)],U)},844:(a,o)=>{function l(c){for(const u of c)u.dispose();c.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const c of this._disposables)c.dispose();this._disposables.length=0}register(c){return this._disposables.push(c),c}unregister(c){const u=this._disposables.indexOf(c);u!==-1&&this._disposables.splice(u,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(c){this._isDisposed||c===this._value||(this._value?.dispose(),this._value=c)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},o.toDisposable=function(c){return{dispose:c}},o.disposeArray=l,o.getDisposeArrayDisposable=function(c){return{dispose:()=>l(c)}}},1505:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.FourKeyMap=o.TwoKeyMap=void 0;class l{constructor(){this._data={}}set(u,d,h){this._data[u]||(this._data[u]={}),this._data[u][d]=h}get(u,d){return this._data[u]?this._data[u][d]:void 0}clear(){this._data={}}}o.TwoKeyMap=l,o.FourKeyMap=class{constructor(){this._data=new l}set(c,u,d,h,m){this._data.get(c,u)||this._data.set(c,u,new l),this._data.get(c,u).set(d,h,m)}get(c,u,d,h){return this._data.get(c,u)?.get(d,h)}clear(){this._data.clear()}}},6114:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.isChromeOS=o.isLinux=o.isWindows=o.isIphone=o.isIpad=o.isMac=o.getSafariVersion=o.isSafari=o.isLegacyEdge=o.isFirefox=o.isNode=void 0,o.isNode=typeof cp<"u"&&"title"in cp;const l=o.isNode?"node":navigator.userAgent,c=o.isNode?"node":navigator.platform;o.isFirefox=l.includes("Firefox"),o.isLegacyEdge=l.includes("Edge"),o.isSafari=/^((?!chrome|android).)*safari/i.test(l),o.getSafariVersion=function(){if(!o.isSafari)return 0;const u=l.match(/Version\/(\d+)/);return u===null||u.length<2?0:parseInt(u[1])},o.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(c),o.isIpad=c==="iPad",o.isIphone=c==="iPhone",o.isWindows=["Windows","Win16","Win32","WinCE"].includes(c),o.isLinux=c.indexOf("Linux")>=0,o.isChromeOS=/\bCrOS\b/.test(l)},6106:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SortedList=void 0;let l=0;o.SortedList=class{constructor(c){this._getKey=c,this._array=[]}clear(){this._array.length=0}insert(c){this._array.length!==0?(l=this._search(this._getKey(c)),this._array.splice(l,0,c)):this._array.push(c)}delete(c){if(this._array.length===0)return!1;const u=this._getKey(c);if(u===void 0||(l=this._search(u),l===-1)||this._getKey(this._array[l])!==u)return!1;do if(this._array[l]===c)return this._array.splice(l,1),!0;while(++l<this._array.length&&this._getKey(this._array[l])===u);return!1}*getKeyIterator(c){if(this._array.length!==0&&(l=this._search(c),!(l<0||l>=this._array.length)&&this._getKey(this._array[l])===c))do yield this._array[l];while(++l<this._array.length&&this._getKey(this._array[l])===c)}forEachByKey(c,u){if(this._array.length!==0&&(l=this._search(c),!(l<0||l>=this._array.length)&&this._getKey(this._array[l])===c))do u(this._array[l]);while(++l<this._array.length&&this._getKey(this._array[l])===c)}values(){return[...this._array].values()}_search(c){let u=0,d=this._array.length-1;for(;d>=u;){let h=u+d>>1;const m=this._getKey(this._array[h]);if(m>c)d=h-1;else{if(!(m<c)){for(;h>0&&this._getKey(this._array[h-1])===c;)h--;return h}u=h+1}}return u}}},7226:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DebouncedIdleTask=o.IdleTaskQueue=o.PriorityTaskQueue=void 0;const c=l(6114);class u{constructor(){this._tasks=[],this._i=0}enqueue(m){this._tasks.push(m),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(m){this._idleCallback=void 0;let b=0,g=0,p=m.timeRemaining(),y=0;for(;this._i<this._tasks.length;){if(b=Date.now(),this._tasks[this._i]()||this._i++,b=Math.max(1,Date.now()-b),g=Math.max(b,g),y=m.timeRemaining(),1.5*g>y)return p-b<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(p-b))}ms`),void this._start();p=y}this.clear()}}class d extends u{_requestCallback(m){return setTimeout(()=>m(this._createDeadline(16)))}_cancelCallback(m){clearTimeout(m)}_createDeadline(m){const b=Date.now()+m;return{timeRemaining:()=>Math.max(0,b-Date.now())}}}o.PriorityTaskQueue=d,o.IdleTaskQueue=!c.isNode&&"requestIdleCallback"in window?class extends u{_requestCallback(h){return requestIdleCallback(h)}_cancelCallback(h){cancelIdleCallback(h)}}:d,o.DebouncedIdleTask=class{constructor(){this._queue=new o.IdleTaskQueue}set(h){this._queue.clear(),this._queue.enqueue(h)}flush(){this._queue.flush()}}},9282:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.updateWindowsModeWrappedState=void 0;const c=l(643);o.updateWindowsModeWrappedState=function(u){const d=u.buffer.lines.get(u.buffer.ybase+u.buffer.y-1),h=d?.get(u.cols-1),m=u.buffer.lines.get(u.buffer.ybase+u.buffer.y);m&&h&&(m.isWrapped=h[c.CHAR_DATA_CODE_INDEX]!==c.NULL_CELL_CODE&&h[c.CHAR_DATA_CODE_INDEX]!==c.WHITESPACE_CELL_CODE)}},3734:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ExtendedAttrs=o.AttributeData=void 0;class l{constructor(){this.fg=0,this.bg=0,this.extended=new c}static toColorRGB(d){return[d>>>16&255,d>>>8&255,255&d]}static fromColorRGB(d){return(255&d[0])<<16|(255&d[1])<<8|255&d[2]}clone(){const d=new l;return d.fg=this.fg,d.bg=this.bg,d.extended=this.extended.clone(),d}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}o.AttributeData=l;class c{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(d){this._ext=d}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(d){this._ext&=-469762049,this._ext|=d<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(d){this._ext&=-67108864,this._ext|=67108863&d}get urlId(){return this._urlId}set urlId(d){this._urlId=d}get underlineVariantOffset(){const d=(3758096384&this._ext)>>29;return d<0?4294967288^d:d}set underlineVariantOffset(d){this._ext&=536870911,this._ext|=d<<29&3758096384}constructor(d=0,h=0){this._ext=0,this._urlId=0,this._ext=d,this._urlId=h}clone(){return new c(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}o.ExtendedAttrs=c},9092:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Buffer=o.MAX_BUFFER_SIZE=void 0;const c=l(6349),u=l(7226),d=l(3734),h=l(8437),m=l(4634),b=l(511),g=l(643),p=l(4863),y=l(7116);o.MAX_BUFFER_SIZE=4294967295,o.Buffer=class{constructor(v,_,w){this._hasScrollback=v,this._optionsService=_,this._bufferService=w,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=h.DEFAULT_ATTR_DATA.clone(),this.savedCharset=y.DEFAULT_CHARSET,this.markers=[],this._nullCell=b.CellData.fromCharData([0,g.NULL_CELL_CHAR,g.NULL_CELL_WIDTH,g.NULL_CELL_CODE]),this._whitespaceCell=b.CellData.fromCharData([0,g.WHITESPACE_CELL_CHAR,g.WHITESPACE_CELL_WIDTH,g.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new u.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new c.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(v){return v?(this._nullCell.fg=v.fg,this._nullCell.bg=v.bg,this._nullCell.extended=v.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new d.ExtendedAttrs),this._nullCell}getWhitespaceCell(v){return v?(this._whitespaceCell.fg=v.fg,this._whitespaceCell.bg=v.bg,this._whitespaceCell.extended=v.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new d.ExtendedAttrs),this._whitespaceCell}getBlankLine(v,_){return new h.BufferLine(this._bufferService.cols,this.getNull
58Cell(v),_)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const v=this.ybase+this.y-this.ydisp;return v>=0&&v<this._rows}_getCorrectBufferLength(v){if(!this._hasScrollback)return v;const _=v+this._optionsService.rawOptions.scrollback;return _>o.MAX_BUFFER_SIZE?o.MAX_BUFFER_SIZE:_}fillViewportRows(v){if(this.lines.length===0){v===void 0&&(v=h.DEFAULT_ATTR_DATA);let _=this._rows;for(;_--;)this.lines.push(this.getBlankLine(v))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new c.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(v,_){const w=this.getNullCell(h.DEFAULT_ATTR_DATA);let C=0;const A=this._getCorrectBufferLength(_);if(A>this.lines.maxLength&&(this.lines.maxLength=A),this.lines.length>0){if(this._cols<v)for(let S=0;S<this.lines.length;S++)C+=+this.lines.get(S).resize(v,w);let E=0;if(this._rows<_)for(let S=this._rows;S<_;S++)this.lines.length<_+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new h.BufferLine(v,w)):this.ybase>0&&this.lines.length<=this.ybase+this.y+E+1?(this.ybase--,E++,this.ydisp>0&&this.ydisp--):this.lines.push(new h.BufferLine(v,w)));else for(let S=this._rows;S>_;S--)this.lines.length>_+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(A<this.lines.maxLength){const S=this.lines.length-A;S>0&&(this.lines.trimStart(S),this.ybase=Math.max(this.ybase-S,0),this.ydisp=Math.max(this.ydisp-S,0),this.savedY=Math.max(this.savedY-S,0)),this.lines.maxLength=A}this.x=Math.min(this.x,v-1),this.y=Math.min(this.y,_-1),E&&(this.y+=E),this.savedX=Math.min(this.savedX,v-1),this.scrollTop=0}if(this.scrollBottom=_-1,this._isReflowEnabled&&(this._reflow(v,_),this._cols>v))for(let E=0;E<this.lines.length;E++)C+=+this.lines.get(E).resize(v,w);this._cols=v,this._rows=_,this._memoryCleanupQueue.clear(),C>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let v=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,v=!1);let _=0;for(;this._memoryCleanupPosition<this.lines.length;)if(_+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),_>100)return!0;return v}get _isReflowEnabled(){const v=this._optionsService.rawOptions.windowsPty;return v&&v.buildNumber?this._hasScrollback&&v.backend==="conpty"&&v.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(v,_){this._cols!==v&&(v>this._cols?this._reflowLarger(v,_):this._reflowSmaller(v,_))}_reflowLarger(v,_){const w=(0,m.reflowLargerGetLinesToRemove)(this.lines,this._cols,v,this.ybase+this.y,this.getNullCell(h.DEFAULT_ATTR_DATA));if(w.length>0){const C=(0,m.reflowLargerCreateNewLayout)(this.lines,w);(0,m.reflowLargerApplyNewLayout)(this.lines,C.layout),this._reflowLargerAdjustViewport(v,_,C.countRemoved)}}_reflowLargerAdjustViewport(v,_,w){const C=this.getNullCell(h.DEFAULT_ATTR_DATA);let A=w;for(;A-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<_&&this.lines.push(new h.BufferLine(v,C))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-w,0)}_reflowSmaller(v,_){const w=this.getNullCell(h.DEFAULT_ATTR_DATA),C=[];let A=0;for(let E=this.lines.length-1;E>=0;E--){let S=this.lines.get(E);if(!S||!S.isWrapped&&S.getTrimmedLength()<=v)continue;const k=[S];for(;S.isWrapped&&E>0;)S=this.lines.get(--E),k.unshift(S);const O=this.ybase+this.y;if(O>=E&&O<E+k.length)continue;const T=k[k.length-1].getTrimmedLength(),R=(0,m.reflowSmallerGetNewLineLengths)(k,this._cols,v),N=R.length-k.length;let M;M=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+N):Math.max(0,this.lines.length-this.lines.maxLength+N);const B=[];for(let V=0;V<N;V++){const Z=this.getBlankLine(h.DEFAULT_ATTR_DATA,!0);B.push(Z)}B.length>0&&(C.push({start:E+k.length+A,newLines:B}),A+=B.length),k.push(...B);let U=R.length-1,X=R[U];X===0&&(U--,X=R[U]);let oe=k.length-N-1,L=T;for(;oe>=0;){const V=Math.min(L,X);if(k[U]===void 0)break;if(k[U].copyCellsFrom(k[oe],L-V,X-V,V,!0),X-=V,X===0&&(U--,X=R[U]),L-=V,L===0){oe--;const Z=Math.max(oe,0);L=(0,m.getWrappedLineTrimmedLength)(k,Z,this._cols)}}for(let V=0;V<k.length;V++)R[V]<v&&k[V].setCell(R[V],w);let F=N-M;for(;F-- >0;)this.ybase===0?this.y<_-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+A)-_&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+N,this.ybase+_-1)}if(C.length>0){const E=[],S=[];for(let U=0;U<this.lines.length;U++)S.push(this.lines.get(U));const k=this.lines.length;let O=k-1,T=0,R=C[T];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+A);let N=0;for(let U=Math.min(this.lines.maxLength-1,k+A-1);U>=0;U--)if(R&&R.start>O+N){for(let X=R.newLines.length-1;X>=0;X--)this.lines.set(U--,R.newLines[X]);U++,E.push({index:O+1,amount:R.newLines.length}),N+=R.newLines.length,R=C[++T]}else this.lines.set(U,S[O--]);let M=0;for(let U=E.length-1;U>=0;
vendor: 17,420 bytes, lines 58-59
58U--)E[U].index+=M,this.lines.onInsertEmitter.fire(E[U]),M+=E[U].amount;const B=Math.max(0,k+A-this.lines.maxLength);B>0&&this.lines.onTrimEmitter.fire(B)}}translateBufferLineToString(v,_,w=0,C){const A=this.lines.get(v);return A?A.translateToString(_,w,C):""}getWrappedRangeForLine(v){let _=v,w=v;for(;_>0&&this.lines.get(_).isWrapped;)_--;for(;w+1<this.lines.length&&this.lines.get(w+1).isWrapped;)w++;return{first:_,last:w}}setupTabStops(v){for(v!=null?this.tabs[v]||(v=this.prevStop(v)):(this.tabs={},v=0);v<this._cols;v+=this._optionsService.rawOptions.tabStopWidth)this.tabs[v]=!0}prevStop(v){for(v==null&&(v=this.x);!this.tabs[--v]&&v>0;);return v>=this._cols?this._cols-1:v<0?0:v}nextStop(v){for(v==null&&(v=this.x);!this.tabs[++v]&&v<this._cols;);return v>=this._cols?this._cols-1:v<0?0:v}clearMarkers(v){this._isClearing=!0;for(let _=0;_<this.markers.length;_++)this.markers[_].line===v&&(this.markers[_].dispose(),this.markers.splice(_--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let v=0;v<this.markers.length;v++)this.markers[v].dispose(),this.markers.splice(v--,1);this._isClearing=!1}addMarker(v){const _=new p.Marker(v);return this.markers.push(_),_.register(this.lines.onTrim(w=>{_.line-=w,_.line<0&&_.dispose()})),_.register(this.lines.onInsert(w=>{_.line>=w.index&&(_.line+=w.amount)})),_.register(this.lines.onDelete(w=>{_.line>=w.index&&_.line<w.index+w.amount&&_.dispose(),_.line>w.index&&(_.line-=w.amount)})),_.register(_.onDispose(()=>this._removeMarker(_))),_}_removeMarker(v){this._isClearing||this.markers.splice(this.markers.indexOf(v),1)}}},8437:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLine=o.DEFAULT_ATTR_DATA=void 0;const c=l(3734),u=l(511),d=l(643),h=l(482);o.DEFAULT_ATTR_DATA=Object.freeze(new c.AttributeData);let m=0;class b{constructor(p,y,v=!1){this.isWrapped=v,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*p);const _=y||u.CellData.fromCharData([0,d.NULL_CELL_CHAR,d.NULL_CELL_WIDTH,d.NULL_CELL_CODE]);for(let w=0;w<p;++w)this.setCell(w,_);this.length=p}get(p){const y=this._data[3*p+0],v=2097151&y;return[this._data[3*p+1],2097152&y?this._combined[p]:v?(0,h.stringFromCodePoint)(v):"",y>>22,2097152&y?this._combined[p].charCodeAt(this._combined[p].length-1):v]}set(p,y){this._data[3*p+1]=y[d.CHAR_DATA_ATTR_INDEX],y[d.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[p]=y[1],this._data[3*p+0]=2097152|p|y[d.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*p+0]=y[d.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|y[d.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(p){return this._data[3*p+0]>>22}hasWidth(p){return 12582912&this._data[3*p+0]}getFg(p){return this._data[3*p+1]}getBg(p){return this._data[3*p+2]}hasContent(p){return 4194303&this._data[3*p+0]}getCodePoint(p){const y=this._data[3*p+0];return 2097152&y?this._combined[p].charCodeAt(this._combined[p].length-1):2097151&y}isCombined(p){return 2097152&this._data[3*p+0]}getString(p){const y=this._data[3*p+0];return 2097152&y?this._combined[p]:2097151&y?(0,h.stringFromCodePoint)(2097151&y):""}isProtected(p){return 536870912&this._data[3*p+2]}loadCell(p,y){return m=3*p,y.content=this._data[m+0],y.fg=this._data[m+1],y.bg=this._data[m+2],2097152&y.content&&(y.combinedData=this._combined[p]),268435456&y.bg&&(y.extended=this._extendedAttrs[p]),y}setCell(p,y){2097152&y.content&&(this._combined[p]=y.combinedData),268435456&y.bg&&(this._extendedAttrs[p]=y.extended),this._data[3*p+0]=y.content,this._data[3*p+1]=y.fg,this._data[3*p+2]=y.bg}setCellFromCodepoint(p,y,v,_){268435456&_.bg&&(this._extendedAttrs[p]=_.extended),this._data[3*p+0]=y|v<<22,this._data[3*p+1]=_.fg,this._data[3*p+2]=_.bg}addCodepointToCell(p,y,v){let _=this._data[3*p+0];2097152&_?this._combined[p]+=(0,h.stringFromCodePoint)(y):2097151&_?(this._combined[p]=(0,h.stringFromCodePoint)(2097151&_)+(0,h.stringFromCodePoint)(y),_&=-2097152,_|=2097152):_=y|4194304,v&&(_&=-12582913,_|=v<<22),this._data[3*p+0]=_}insertCells(p,y,v){if((p%=this.length)&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p-1,0,1,v),y<this.length-p){const _=new u.CellData;for(let w=this.length-p-y-1;w>=0;--w)this.setCell(p+y+w,this.loadCell(p+w,_));for(let w=0;w<y;++w)this.setCell(p+w,v)}else for(let _=p;_<this.length;++_)this.setCell(_,v);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,v)}deleteCells(p,y,v){if(p%=this.length,y<this.length-p){const _=new u.CellData;for(let w=0;w<this.length-p-y;++w)this.setCell(p+w,this.loadCell(p+y+w,_));for(let w=this.length-y;w<this.length;++w)this.setCell(w,v)}else for(let _=p;_<this.length;++_)this.setCell(_,v);p&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p-1,0,1,v),this.getWidth(p)!==0||this.hasContent(p)||this.setCellFromCodepoint(p,0,1,v)}replaceCells(p,y,v,_=!1){if(_)for(p&&this.getWidth(p-1)===2&&!this.isProtected(p-1)&&this.setCellFromCodepoint(p-1,0,1,v),y<this.length&&this.getWidth(y-1)===2&&!this.isProtected(y)&&this.setCellFromCodepoint(y,0,1,v);p<y&&p<this.length;)this.isProtected(p)||this.setCell(p,v),p++;else for(p&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p-1,0,1,v),y<this.length&&this.getWidth(y-1)===2&&this.setCellFromCodepoint(y,0,1,v);p<y&&p<this.length;)this.setCell(p++,v)}resize(p,y){if(p===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const v=3*p;if(p>this.length){if(this._data.buffer.byteLength>=4*v)this._data=new Uint32Array(this._data.buffer,0,v);else{const _=new Uint32Array(v);_.set(this._data),this._data=_}for(let _=this.length;_<p;++_)this.setCell(_,y)}else{this._data=this._data.subarray(0,v);const _=Object.keys(this._combined);for(let C=0;C<_.length;C++){const A=parseInt(_[C],10);A>=p&&delete this._combined[A]}const w=Object.keys(this._extendedAttrs);for(let C=0;C<w.length;C++){const A=parseInt(w[C],10);A>=p&&delete this._extendedAttrs[A]}}return this.length=p,4*v*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const p=new Uint32Array(this._data.length);return p.set(this._data),this._data=p,1}return 0}fill(p,y=!1){if(y)for(let v=0;v<this.length;++v)this.isProtected(v)||this.setCell(v,p);else{this._combined={},this._extendedAttrs={};for(let v=0;v<this.length;++v)this.setCell(v,p)}}copyFrom(p){this.length!==p.length?this._data=new Uint32Array(p._data):this._data.set(p._data),this.length=p.length,this._combined={};for(const y in p._combined)this._combined[y]=p._combined[y];this._extendedAttrs={};for(const y in p._extendedAttrs)this._extendedAttrs[y]=p._extendedAttrs[y];this.isWrapped=p.isWrapped}clone(){const p=new b(0);p._data=new Uint32Array(this._data),p.length=this.length;for(const y in this._combined)p._combined[y]=this._combined[y];for(const y in this._extendedAttrs)p._extendedAttrs[y]=this._extendedAttrs[y];return p.isWrapped=this.isWrapped,p}getTrimmedLength(){for(let p=this.length-1;p>=0;--p)if(4194303&this._data[3*p+0])return p+(this._data[3*p+0]>>22);return 0}getNoBgTrimmedLength(){for(let p=this.length-1;p>=0;--p)if(4194303&this._data[3*p+0]||50331648&this._data[3*p+2])return p+(this._data[3*p+0]>>22);return 0}copyCellsFrom(p,y,v,_,w){const C=p._data;if(w)for(let E=_-1;E>=0;E--){for(let S=0;S<3;S++)this._data[3*(v+E)+S]=C[3*(y+E)+S];268435456&C[3*(y+E)+2]&&(this._extendedAttrs[v+E]=p._extendedAttrs[y+E])}else for(let E=0;E<_;E++){for(let S=0;S<3;S++)this._data[3*(v+E)+S]=C[3*(y+E)+S];268435456&C[3*(y+E)+2]&&(this._extendedAttrs[v+E]=p._extendedAttrs[y+E])}const A=Object.keys(p._combined);for(let E=0;E<A.length;E++){const S=parseInt(A[E],10);S>=y&&(this._combined[S-y+v]=p._combined[S])}}translateToString(p,y,v,_){y=y??0,v=v??this.length,p&&(v=Math.min(v,this.getTrimmedLength())),_&&(_.length=0);let w="";for(;y<v;){const C=this._data[3*y+0],A=2097151&C,E=2097152&C?this._combined[y]:A?(0,h.stringFromCodePoint)(A):d.WHITESPACE_CELL_CHAR;if(w+=E,_)for(let S=0;S<E.length;++S)_.push(y);y+=C>>22||1}return _&&_.push(y),w}}o.BufferLine=b},4841:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.getRangeLength=void 0,o.getRangeLength=function(l,c){if(l.start.y>l.end.y)throw new Error(`Buffer range end (${l.end.x}, ${l.end.y}) cannot be before start (${l.start.x}, ${l.start.y})`);return c*(l.end.y-l.start.y)+(l.end.x-l.start.x+1)}},4634:(a,o)=>{function l(c,u,d){if(u===c.length-1)return c[u].getTrimmedLength();const h=!c[u].hasContent(d-1)&&c[u].getWidth(d-1)===1,m=c[u+1].getWidth(0)===2;return h&&m?d-1:d}Object.defineProperty(o,"__esModule",{value:!0}),o.getWrappedLineTrimmedLength=o.reflowSmallerGetNewLineLengths=o.reflowLargerApplyNewLayout=o.reflowLargerCreateNewLayout=o.reflowLargerGetLinesToRemove=void 0,o.reflowLargerGetLinesToRemove=function(c,u,d,h,m){const b=[];for(let g=0;g<c.length-1;g++){let p=g,y=c.get(++p);if(!y.isWrapped)continue;const v=[c.get(g)];for(;p<c.length&&y.isWrapped;)v.push(y),y=c.get(++p);if(h>=g&&h<p){g+=v.length-1;continue}let _=0,w=l(v,_,u),C=1,A=0;for(;C<v.length;){const S=l(v,C,u),k=S-A,O=d-w,T=Math.min(k,O);v[_].copyCellsFrom(v[C],A,w,T,!1),w+=T,w===d&&(_++,w=0),A+=T,A===S&&(C++,A=0),w===0&&_!==0&&v[_-1].getWidth(d-1)===2&&(v[_].copyCellsFrom(v[_-1],d-1,w++,1,!1),v[_-1].setCell(d-1,m))}v[_].replaceCells(w,d,m);let E=0;for(let S=v.length-1;S>0&&(S>_||v[S].getTrimmedLength()===0);S--)E++;E>0&&(b.push(g+v.length-E),b.push(E)),g+=v.length-1}return b},o.reflowLargerCreateNewLayout=function(c,u){const d=[];let h=0,m=u[h],b=0;for(let g=0;g<c.length;g++)if(m===g){const p=u[++h];c.onDeleteEmitter.fire({index:g-b,amount:p}),g+=p-1,b+=p,m=u[++h]}else d.push(g);return{layout:d,countRemoved:b}},o.reflowLargerApplyNewLayout=function(c,u){const d=[];for(let h=0;h<u.length;h++)d.push(c.get(u[h]));for(let h=0;h<d.length;h++)c.set(h,d[h]);c.length=u.length},o.reflowSmallerGetNewLineLengths=function(c,u,d){const h=[],m=c.map((y,v)=>l(c,v,u)).reduce((y,v)=>y+v);let b=0,g=0,p=0;for(;p<m;){if(m-p<d){h.push(m-p);break}b+=d;const y=l(c,g,u);b>y&&(b-=y,g++);const v=c[g].getWidth(b-1)===2;v&&b--;const _=v?d-1:d;h.push(_),p+=_}return h},o.getWrappedLineTrimmedLength=l},5295:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferSet=void 0;const c=l(8460),u=l(844),d=l(9092);class h extends u.Disposable{constructor(b,g){super(),this._optionsService=b,this._bufferService=g,this._onBufferActivate=this.register(new c.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new d.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new d.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(b){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(b),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(b,g){this._normal.resize(b,g),this._alt.resize(b,g),this.setupTabStops(b)}setupTabStops(b){this._normal.setupTabStops(b),this._alt.setupTabStops(b)}}o.BufferSet=h},511:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CellData=void 0;const c=l(482),u=l(643),d=l(3734);class h extends d.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new d.ExtendedAttrs,this.combinedData=""}static fromCharData(b){const g=new h;return g.setFromCharData(b),g}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,c.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(b){this.fg=b[u.CHAR_DATA_ATTR_INDEX],this.bg=0;let g=!1;if(b[u.CHAR_DATA_CHAR_INDEX].length>2)g=!0;else if(b[u.CHAR_DATA_CHAR_INDEX].length===2){const p=b[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=p&&p<=56319){const y=b[u.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=y&&y<=57343?this.content=1024*(p-55296)+y-56320+65536|b[u.CHAR_DATA_WIDTH_INDEX]<<22:g=!0}else g=!0}else this.content=b[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|b[u.CHAR_DATA_WIDTH_INDEX]<<22;g&&(this.combinedData=b[u.CHAR_DATA_CHAR_INDEX],this.content=2097152|b[u.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.CellData=h},643:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WHITESPACE_CELL_CODE=o.WHITESPACE_CELL_WIDTH=o.WHITESPACE_CELL_CHAR=o.NULL_CELL_CODE=o.NULL_CELL_WIDTH=o.NULL_CELL_CHAR=o.CHAR_DATA_CODE_INDEX=o.CHAR_DATA_WIDTH_INDEX=o.CHAR_DATA_CHAR_INDEX=o.CHAR_DATA_ATTR_INDEX=o.DEFAULT_EXT=o.DEFAULT_ATTR=o.DEFAULT_COLOR=void 0,o.DEFAULT_COLOR=0,o.DEFAULT_ATTR=256|o.DEFAULT_COLOR<<9,o.DEFAULT_EXT=0,o.CHAR_DATA_ATTR_INDEX=0,o.CHAR_DATA_CHAR_INDEX=1,o.CHAR_DATA_WIDTH_INDEX=2,o.CHAR_DATA_CODE_INDEX=3,o.NULL_CELL_CHAR="",o.NULL_CELL_WIDTH=1,o.NULL_CELL_CODE=0,o.WHITESPACE_CELL_CHAR=" ",o.WHITESPACE_CELL_WIDTH=1,o.WHITESPACE_CELL_CODE=32},4863:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Marker=void 0;const c=l(8460),u=l(844);class d{get id(){return this._id}constructor(m){this.line=m,this.isDisposed=!1,this._disposables=[],this._id=d._nextId++,this._onDispose=this.register(new c.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,u.disposeArray)(this._disposables),this._disposables.length=0)}register(m){return this._disposables.push(m),m}}o.Marker=d,d._nextId=1},7116:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DEFAULT_CHARSET=o.CHARSETS=void 0,o.CHARSETS={},o.DEFAULT_CHARSET=o.CHARSETS.B,o.CHARSETS[0]={"`":"â",a:"â",b:"â",c:"â",d:"â",e:"â",f:"°",g:"±",h:"â¤",i:"â",j:"â",k:"â",l:"â",m:"â",n:"â¼",o:"âº",p:"â»",q:"â",r:"â¼",s:"â½",t:"â",u:"â¤",v:"â´",w:"â¬",x:"â",y:"â¤",z:"â¥","{":"Ï","|":"â ","}":"£","~":"·"},o.CHARSETS.A={"#":"£"},o.CHARSETS.B=void 0,o.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},o.CHARSETS.C=o.CHARSETS[5]={"[":"Ã","\\":"Ã","]":"à ","^":"Ã","`":"é","{":"ä","|":"ö","}":"Ã¥","~":"ü"},o.CHARSETS.R={"#":"£","@":"à ","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},o.CHARSETS.Q={"@":"à ","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},o.CHARSETS.K={"@":"§","[":"Ã","\\":"Ã","]":"Ã","{":"ä","|":"ö","}":"ü","~":"Ã"},o.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à ","|":"ò","}":"è","~":"ì"},o.CHARSETS.E=o.CHARSETS[6]={"@":"Ã","[":"Ã","\\":"Ã","]":"à ","^":"Ã","`":"ä","{":"æ","|":"ø","}":"Ã¥","~":"ü"},o.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ã","]":"¿","{":"°","|":"ñ","}":"ç"},o.CHARSETS.H=o.CHARSETS[7]={"@":"Ã","[":"Ã","\\":"Ã","]":"à ","^":"Ã","`":"é","{":"ä","|":"ö","}":"Ã¥","~":"ü"},o.CHARSETS["="]={"#":"ù","@":"à ","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(a,o)=>{var l,c,u;Object.defineProperty(o,"__esModule",{value:!0}),o.C1_ESCAPED=o.C1=o.C0=void 0,function(d){d.NUL="\0",d.SOH="�",d.STX="�",d.ETX="�",d.EOT="�",d.ENQ="�",d.ACK="�",d.BEL="\x07",d.BS="\b",d.HT=" ",d.LF=` 59`,d.VT="\v",d.FF="\f",d.CR="\r",d.SO="�",d.SI="�",d.DLE="�",d.DC1="�",d.DC2="�",d.DC3="�",d.DC4="�",d.NAK="�",d.SYN="�",d.ETB="�",d.CAN="�",d.EM="�",d.SUB="�",d.ESC="\x1B",d.FS="�",d.GS="�",d.RS="�",d.US="�",d.SP=" ",d.DEL="�"}(l||(o.C0=l={})),function(d){d.PAD="Â",d.HOP="Â",d.BPH="Â",d.NBH="Â",d.IND="Â",d.NEL=" ",d.SSA="Â",d.ESA="Â",d.HTS="Â",d.HTJ="Â",d.VTS="Â",d.PLD="Â",d.PLU="Â",d.RI="Â",d.SS2="Â",d.SS3="Â",d.DCS="Â",d.PU1="Â",d.PU2="Â",d.STS="Â",d.CCH="Â",d.MW="Â",d.SPA="Â",d.EPA="Â",d.SOS="Â",d.SGCI="Â",d.SCI="Â",d.CSI="Â",d.ST="Â",d.OSC="Â",d.PM="Â",d.APC="Â"}(c||(o.C1=c={})),function(d){d.ST=`${l.ESC}\\`}(u||(o.C1_ESCAPED=u={}))},7399:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.evaluateKeyboardEvent=void 0;const c=l(2584),u={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};o.evaluateKeyboardEvent=function(d,h,m,b){const g={type:0,cancel:!1,key:void 0},p=(d.shiftKey?1:0)|(d.altKey?2:0)|(d.ctrlKey?4:0)|(d.metaKey?8:0);switch(d.keyCode){case 0:d.key==="UIKeyInputUpArrow"?g.key=h?c.C0.ESC+"OA":c.C0.ESC+"[A":d.key==="UIKeyInputLeftArrow"?g.key=h?c.C0.ESC+"OD":c.C0.ESC+"[D":d.key==="UIKeyInputRightArrow"?g.key=h?c.C0.ESC+"OC":c.C0.ESC+"[C":d.key==="UIKeyInputDownArrow"&&(g.key=h?c.C0.ESC+"OB":c.C0.ESC+"[B");break;
vendor: 6,591 bytes, line 59
59case 8:g.key=d.ctrlKey?"\b":c.C0.DEL,d.altKey&&(g.key=c.C0.ESC+g.key);break;case 9:if(d.shiftKey){g.key=c.C0.ESC+"[Z";break}g.key=c.C0.HT,g.cancel=!0;break;case 13:g.key=d.altKey?c.C0.ESC+c.C0.CR:c.C0.CR,g.cancel=!0;break;case 27:g.key=c.C0.ESC,d.altKey&&(g.key=c.C0.ESC+c.C0.ESC),g.cancel=!0;break;case 37:if(d.metaKey)break;p?(g.key=c.C0.ESC+"[1;"+(p+1)+"D",g.key===c.C0.ESC+"[1;3D"&&(g.key=c.C0.ESC+(m?"b":"[1;5D"))):g.key=h?c.C0.ESC+"OD":c.C0.ESC+"[D";break;case 39:if(d.metaKey)break;p?(g.key=c.C0.ESC+"[1;"+(p+1)+"C",g.key===c.C0.ESC+"[1;3C"&&(g.key=c.C0.ESC+(m?"f":"[1;5C"))):g.key=h?c.C0.ESC+"OC":c.C0.ESC+"[C";break;case 38:if(d.metaKey)break;p?(g.key=c.C0.ESC+"[1;"+(p+1)+"A",m||g.key!==c.C0.ESC+"[1;3A"||(g.key=c.C0.ESC+"[1;5A")):g.key=h?c.C0.ESC+"OA":c.C0.ESC+"[A";break;case 40:if(d.metaKey)break;p?(g.key=c.C0.ESC+"[1;"+(p+1)+"B",m||g.key!==c.C0.ESC+"[1;3B"||(g.key=c.C0.ESC+"[1;5B")):g.key=h?c.C0.ESC+"OB":c.C0.ESC+"[B";break;case 45:d.shiftKey||d.ctrlKey||(g.key=c.C0.ESC+"[2~");break;case 46:g.key=p?c.C0.ESC+"[3;"+(p+1)+"~":c.C0.ESC+"[3~";break;case 36:g.key=p?c.C0.ESC+"[1;"+(p+1)+"H":h?c.C0.ESC+"OH":c.C0.ESC+"[H";break;case 35:g.key=p?c.C0.ESC+"[1;"+(p+1)+"F":h?c.C0.ESC+"OF":c.C0.ESC+"[F";break;case 33:d.shiftKey?g.type=2:d.ctrlKey?g.key=c.C0.ESC+"[5;"+(p+1)+"~":g.key=c.C0.ESC+"[5~";break;case 34:d.shiftKey?g.type=3:d.ctrlKey?g.key=c.C0.ESC+"[6;"+(p+1)+"~":g.key=c.C0.ESC+"[6~";break;case 112:g.key=p?c.C0.ESC+"[1;"+(p+1)+"P":c.C0.ESC+"OP";break;case 113:g.key=p?c.C0.ESC+"[1;"+(p+1)+"Q":c.C0.ESC+"OQ";break;case 114:g.key=p?c.C0.ESC+"[1;"+(p+1)+"R":c.C0.ESC+"OR";break;case 115:g.key=p?c.C0.ESC+"[1;"+(p+1)+"S":c.C0.ESC+"OS";break;case 116:g.key=p?c.C0.ESC+"[15;"+(p+1)+"~":c.C0.ESC+"[15~";break;case 117:g.key=p?c.C0.ESC+"[17;"+(p+1)+"~":c.C0.ESC+"[17~";break;case 118:g.key=p?c.C0.ESC+"[18;"+(p+1)+"~":c.C0.ESC+"[18~";break;case 119:g.key=p?c.C0.ESC+"[19;"+(p+1)+"~":c.C0.ESC+"[19~";break;case 120:g.key=p?c.C0.ESC+"[20;"+(p+1)+"~":c.C0.ESC+"[20~";break;case 121:g.key=p?c.C0.ESC+"[21;"+(p+1)+"~":c.C0.ESC+"[21~";break;case 122:g.key=p?c.C0.ESC+"[23;"+(p+1)+"~":c.C0.ESC+"[23~";break;case 123:g.key=p?c.C0.ESC+"[24;"+(p+1)+"~":c.C0.ESC+"[24~";break;default:if(!d.ctrlKey||d.shiftKey||d.altKey||d.metaKey)if(m&&!b||!d.altKey||d.metaKey)!m||d.altKey||d.ctrlKey||d.shiftKey||!d.metaKey?d.key&&!d.ctrlKey&&!d.altKey&&!d.metaKey&&d.keyCode>=48&&d.key.length===1?g.key=d.key:d.key&&d.ctrlKey&&(d.key==="_"&&(g.key=c.C0.US),d.key==="@"&&(g.key=c.C0.NUL)):d.keyCode===65&&(g.type=1);else{const y=u[d.keyCode],v=y?.[d.shiftKey?1:0];if(v)g.key=c.C0.ESC+v;else if(d.keyCode>=65&&d.keyCode<=90){const _=d.ctrlKey?d.keyCode-64:d.keyCode+32;let w=String.fromCharCode(_);d.shiftKey&&(w=w.toUpperCase()),g.key=c.C0.ESC+w}else if(d.keyCode===32)g.key=c.C0.ESC+(d.ctrlKey?c.C0.NUL:" ");else if(d.key==="Dead"&&d.code.startsWith("Key")){let _=d.code.slice(3,4);d.shiftKey||(_=_.toLowerCase()),g.key=c.C0.ESC+_,g.cancel=!0}}else d.keyCode>=65&&d.keyCode<=90?g.key=String.fromCharCode(d.keyCode-64):d.keyCode===32?g.key=c.C0.NUL:d.keyCode>=51&&d.keyCode<=55?g.key=String.fromCharCode(d.keyCode-51+27):d.keyCode===56?g.key=c.C0.DEL:d.keyCode===219?g.key=c.C0.ESC:d.keyCode===220?g.key=c.C0.FS:d.keyCode===221&&(g.key=c.C0.GS)}return g}},482:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Utf8ToUtf32=o.StringToUtf32=o.utf32ToString=o.stringFromCodePoint=void 0,o.stringFromCodePoint=function(l){return l>65535?(l-=65536,String.fromCharCode(55296+(l>>10))+String.fromCharCode(l%1024+56320)):String.fromCharCode(l)},o.utf32ToString=function(l,c=0,u=l.length){let d="";for(let h=c;h<u;++h){let m=l[h];m>65535?(m-=65536,d+=String.fromCharCode(55296+(m>>10))+String.fromCharCode(m%1024+56320)):d+=String.fromCharCode(m)}return d},o.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(l,c){const u=l.length;if(!u)return 0;let d=0,h=0;if(this._interim){const m=l.charCodeAt(h++);56320<=m&&m<=57343?c[d++]=1024*(this._interim-55296)+m-56320+65536:(c[d++]=this._interim,c[d++]=m),this._interim=0}for(let m=h;m<u;++m){const b=l.charCodeAt(m);if(55296<=b&&b<=56319){if(++m>=u)return this._interim=b,d;const g=l.charCodeAt(m);56320<=g&&g<=57343?c[d++]=1024*(b-55296)+g-56320+65536:(c[d++]=b,c[d++]=g)}else b!==65279&&(c[d++]=b)}return d}},o.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(l,c){const u=l.length;if(!u)return 0;let d,h,m,b,g=0,p=0,y=0;if(this.interim[0]){let w=!1,C=this.interim[0];C&=(224&C)==192?31:(240&C)==224?15:7;let A,E=0;for(;(A=63&this.interim[++E])&&E<4;)C<<=6,C|=A;const S=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,k=S-E;for(;y<k;){if(y>=u)return 0;if(A=l[y++],(192&A)!=128){y--,w=!0;break}this.interim[E++]=A,C<<=6,C|=63&A}w||(S===2?C<128?y--:c[g++]=C:S===3?C<2048||C>=55296&&C<=57343||C===65279||(c[g++]=C):C<65536||C>1114111||(c[g++]=C)),this.interim.fill(0)}const v=u-4;let _=y;for(;_<u;){for(;!(!(_<v)||128&(d=l[_])||128&(h=l[_+1])||128&(m=l[_+2])||128&(b=l[_+3]));)c[g++]=d,c[g++]=h,c[g++]=m,c[g++]=b,_+=4;if(d=l[_++],d<128)c[g++]=d;else if((224&d)==192){if(_>=u)return this.interim[0]=d,g;if(h=l[_++],(192&h)!=128){_--;continue}if(p=(31&d)<<6|63&h,p<128){_--;continue}c[g++]=p}else if((240&d)==224){if(_>=u)return this.interim[0]=d,g;if(h=l[_++],(192&h)!=128){_--;continue}if(_>=u)return this.interim[0]=d,this.interim[1]=h,g;if(m=l[_++],(192&m)!=128){_--;continue}if(p=(15&d)<<12|(63&h)<<6|63&m,p<2048||p>=55296&&p<=57343||p===65279)continue;c[g++]=p}else if((248&d)==240){if(_>=u)return this.interim[0]=d,g;if(h=l[_++],(192&h)!=128){_--;continue}if(_>=u)return this.interim[0]=d,this.interim[1]=h,g;if(m=l[_++],(192&m)!=128){_--;continue}if(_>=u)return this.interim[0]=d,this.interim[1]=h,this.interim[2]=m,g;if(b=l[_++],(192&b)!=128){_--;continue}if(p=(7&d)<<18|(63&h)<<12|(63&m)<<6|63&b,p<65536||p>1114111)continue;c[g++]=p}}return g}}},225:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeV6=void 0;const c=l(1480),u=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3
vendor: 11,810 bytes, line 59
59021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],d=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let h;o.UnicodeV6=class{constructor(){if(this.version="6",!h){h=new Uint8Array(65536),h.fill(1),h[0]=0,h.fill(0,1,32),h.fill(0,127,160),h.fill(2,4352,4448),h[9001]=2,h[9002]=2,h.fill(2,11904,42192),h[12351]=1,h.fill(2,44032,55204),h.fill(2,63744,64256),h.fill(2,65040,65050),h.fill(2,65072,65136),h.fill(2,65280,65377),h.fill(2,65504,65511);for(let m=0;m<u.length;++m)h.fill(0,u[m][0],u[m][1]+1)}}wcwidth(m){return m<32?0:m<127?1:m<65536?h[m]:function(b,g){let p,y=0,v=g.length-1;if(b<g[0][0]||b>g[v][1])return!1;for(;v>=y;)if(p=y+v>>1,b>g[p][1])y=p+1;else{if(!(b<g[p][0]))return!0;v=p-1}return!1}(m,d)?0:m>=131072&&m<=196605||m>=196608&&m<=262141?2:1}charProperties(m,b){let g=this.wcwidth(m),p=g===0&&b!==0;if(p){const y=c.UnicodeService.extractWidth(b);y===0?p=!1:y>g&&(g=y)}return c.UnicodeService.createPropertyValue(0,g,p)}}},5981:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WriteBuffer=void 0;const c=l(8460),u=l(844);class d extends u.Disposable{constructor(m){super(),this._action=m,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new c.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(m,b){if(b!==void 0&&this._syncCalls>b)return void(this._syncCalls=0);if(this._pendingData+=m.length,this._writeBuffer.push(m),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let g;for(this._isSyncWriting=!0;g=this._writeBuffer.shift();){this._action(g);const p=this._callbacks.shift();p&&p()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(m,b){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=m.length,this._writeBuffer.push(m),this._callbacks.push(b),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=m.length,this._writeBuffer.push(m),this._callbacks.push(b)}_innerWrite(m=0,b=!0){const g=m||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const p=this._writeBuffer[this._bufferOffset],y=this._action(p,b);if(y){const _=w=>Date.now()-g>=12?setTimeout(()=>this._innerWrite(0,w)):this._innerWrite(g,w);return void y.catch(w=>(queueMicrotask(()=>{throw w}),Promise.resolve(!1))).then(_)}const v=this._callbacks[this._bufferOffset];if(v&&v(),this._bufferOffset++,this._pendingData-=p.length,Date.now()-g>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}o.WriteBuffer=d},5941:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.toRgbString=o.parseColor=void 0;const l=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,c=/^[\da-f]+$/;function u(d,h){const m=d.toString(16),b=m.length<2?"0"+m:m;switch(h){case 4:return m[0];case 8:return b;case 12:return(b+b).slice(0,3);default:return b+b}}o.parseColor=function(d){if(!d)return;let h=d.toLowerCase();if(h.indexOf("rgb:")===0){h=h.slice(4);const m=l.exec(h);if(m){const b=m[1]?15:m[4]?255:m[7]?4095:65535;return[Math.round(parseInt(m[1]||m[4]||m[7]||m[10],16)/b*255),Math.round(parseInt(m[2]||m[5]||m[8]||m[11],16)/b*255),Math.round(parseInt(m[3]||m[6]||m[9]||m[12],16)/b*255)]}}else if(h.indexOf("#")===0&&(h=h.slice(1),c.exec(h)&&[3,6,9,12].includes(h.length))){const m=h.length/3,b=[0,0,0];for(let g=0;g<3;++g){const p=parseInt(h.slice(m*g,m*g+m),16);b[g]=m===1?p<<4:m===2?p:m===3?p>>4:p>>8}return b}},o.toRgbString=function(d,h=16){const[m,b,g]=d;return`rgb:${u(m,h)}/${u(b,h)}/${u(g,h)}`}},5770:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.PAYLOAD_LIMIT=void 0,o.PAYLOAD_LIMIT=1e7},6351:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DcsHandler=o.DcsParser=void 0;const c=l(482),u=l(8742),d=l(5770),h=[];o.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=h,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}registerHandler(b,g){this._handlers[b]===void 0&&(this._handlers[b]=[]);const p=this._handlers[b];return p.push(g),{dispose:()=>{const y=p.indexOf(g);y!==-1&&p.splice(y,1)}}}clearHandler(b){this._handlers[b]&&delete this._handlers[b]}setHandlerFallback(b){this._handlerFb=b}reset(){if(this._active.length)for(let b=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;b>=0;--b)this._active[b].unhook(!1);this._stack.paused=!1,this._active=h,this._ident=0}hook(b,g){if(this.reset(),this._ident=b,this._active=this._handlers[b]||h,this._active.length)for(let p=this._active.length-1;p>=0;p--)this._active[p].hook(g);else this._handlerFb(this._ident,"HOOK",g)}put(b,g,p){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(b,g,p);else this._handlerFb(this._ident,"PUT",(0,c.utf32ToString)(b,g,p))}unhook(b,g=!0){if(this._active.length){let p=!1,y=this._active.length-1,v=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,p=g,v=this._stack.fallThrough,this._stack.paused=!1),!v&&p===!1){for(;y>=0&&(p=this._active[y].unhook(b),p!==!0);y--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,p;y--}for(;y>=0;y--)if(p=this._active[y].unhook(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,p}else this._handlerFb(this._ident,"UNHOOK",b);this._active=h,this._ident=0}};const m=new u.Params;m.addParam(0),o.DcsHandler=class{constructor(b){this._handler=b,this._data="",this._params=m,this._hitLimit=!1}hook(b){this._params=b.length>1||b.params[0]?b.clone():m,this._data="",this._hitLimit=!1}put(b,g,p){this._hitLimit||(this._data+=(0,c.utf32ToString)(b,g,p),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(b){let g=!1;if(this._hitLimit)g=!1;else if(b&&(g=this._handler(this._data,this._params),g instanceof Promise))return g.then(p=>(this._params=m,this._data="",this._hitLimit=!1,p));return this._params=m,this._data="",this._hitLimit=!1,g}}},2015:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.EscapeSequenceParser=o.VT500_TRANSITION_TABLE=o.TransitionTable=void 0;const c=l(844),u=l(8742),d=l(6242),h=l(6351);class m{constructor(y){this.table=new Uint8Array(y)}setDefault(y,v){this.table.fill(y<<4|v)}add(y,v,_,w){this.table[v<<8|y]=_<<4|w}addMany(y,v,_,w){for(let C=0;C<y.length;C++)this.table[v<<8|y[C]]=_<<4|w}}o.TransitionTable=m;const b=160;o.VT500_TRANSITION_TABLE=function(){const p=new m(4095),y=Array.apply(null,Array(256)).map((E,S)=>S),v=(E,S)=>y.slice(E,S),_=v(32,127),w=v(0,24);w.push(25),w.push.apply(w,v(28,32));const C=v(0,14);let A;for(A in p.setDefault(1,0),p.addMany(_,0,2,0),C)p.addMany([24,26,153,154],A,3,0),p.addMany(v(128,144),A,3,0),p.addMany(v(144,152),A,3,0),p.add(156,A,0,0),p.add(27,A,11,1),p.add(157,A,4,8),p.addMany([152,158,159],A,0,7),p.add(155,A,11,3),p.add(144,A,11,9);return p.addMany(w,0,3,0),p.addMany(w,1,3,1),p.add(127,1,0,1),p.addMany(w,8,0,8),p.addMany(w,3,3,3),p.add(127,3,0,3),p.addMany(w,4,3,4),p.add(127,4,0,4),p.addMany(w,6,3,6),p.addMany(w,5,3,5),p.add(127,5,0,5),p.addMany(w,2,3,2),p.add(127,2,0,2),p.add(93,1,4,8),p.addMany(_,8,5,8),p.add(127,8,5,8),p.addMany([156,27,24,26,7],8,6,0),p.addMany(v(28,32),8,0,8),p.addMany([88,94,95],1,0,7),p.addMany(_,7,0,7),p.addMany(w,7,0,7),p.add(156,7,0,0),p.add(127,7,0,7),p.add(91,1,11,3),p.addMany(v(64,127),3,7,0),p.addMany(v(48,60),3,8,4),p.addMany([60,61,62,63],3,9,4),p.addMany(v(48,60),4,8,4),p.addMany(v(64,127),4,7,0),p.addMany([60,61,62,63],4,0,6),p.addMany(v(32,64),6,0,6),p.add(127,6,0,6),p.addMany(v(64,127),6,0,0),p.addMany(v(32,48),3,9,5),p.addMany(v(32,48),5,9,5),p.addMany(v(48,64),5,0,6),p.addMany(v(64,127),5,7,0),p.addMany(v(32,48),4,9,5),p.addMany(v(32,48),1,9,2),p.addMany(v(32,48),2,9,2),p.addMany(v(48,127),2,10,0),p.addMany(v(48,80),1,10,0),p.addMany(v(81,88),1,10,0),p.addMany([89,90,92],1,10,0),p.addMany(v(96,127),1,10,0),p.add(80,1,11,9),p.addMany(w,9,0,9),p.add(127,9,0,9),p.addMany(v(28,32),9,0,9),p.addMany(v(32,48),9,9,12),p.addMany(v(48,60),9,8,10),p.addMany([60,61,62,63],9,9,10),p.addMany(w,11,0,11),p.addMany(v(32,128),11,0,11),p.addMany(v(28,32),11,0,11),p.addMany(w,10,0,10),p.add(127,10,0,10),p.addMany(v(28,32),10,0,10),p.addMany(v(48,60),10,8,10),p.addMany([60,61,62,63],10,0,11),p.addMany(v(32,48),10,9,12),p.addMany(w,12,0,12),p.add(127,12,0,12),p.addMany(v(28,32),12,0,12),p.addMany(v(32,48),12,9,12),p.addMany(v(48,64),12,0,11),p.addMany(v(64,127),12,12,13),p.addMany(v(64,127),10,12,13),p.addMany(v(64,127),9,12,13),p.addMany(w,13,13,13),p.addMany(_,13,13,13),p.add(127,13,0,13),p.addMany([27,156,24,26],13,14,0),p.add(b,0,2,0),p.add(b,8,5,8),p.add(b,6,0,6),p.add(b,11,0,11),p.add(b,13,13,13),p}();class g extends c.Disposable{constructor(y=o.VT500_TRANSITION_TABLE){super(),this._transitions=y,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new u.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(v,_,w)=>{},this._executeHandlerFb=v=>{},this._csiHandlerFb=(v,_)=>{},this._escHandlerFb=v=>{},this._errorHandlerFb=v=>v,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,c.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new d.OscParser),this._dcsParser=this.register(new h.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(y,v=[64,126]){let _=0;if(y.prefix){if(y.prefix.length>1)throw new Error("only one byte as prefix supported");if(_=y.prefix.charCodeAt(0),_&&60>_||_>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(y.intermediates){if(y.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let C=0;C<y.intermediates.length;
59++C){const A=y.intermediates.charCodeAt(C);if(32>A||A>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");_<<=8,_|=A}}if(y.final.length!==1)throw new Error("final must be a single byte");const w=y.final.charCodeAt(0);if(v[0]>w||w>v[1])throw new Error(`final must be in range ${v[0]} .. ${v[1]}`);return _<<=8,_|=w,_}identToString(y){const v=[];for(;y;)v.push(String.fromCharCode(255&y)),y>>=8;return v.reverse().join("")}setPrintHandler(y){this._printHandler=y}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(y,v){const _=this._identifier(y,[48,126]);this._escHandlers[_]===void 0&&(this._escHandlers[_]=[]);const w=this._escHandlers[_];return w.push(v),{dispose:()=>{const C=w.indexOf(v);C!==-1&&w.splice(C,1)}}}clearEscHandler(y){this._escHandlers[this._identifier(y,[48,126])]&&delete this._escHandlers[this._identifier(y,[48,126])]}setEscHandlerFallback(y){this._escHandlerFb=y}setExecuteHandler(y,v){this._executeHandlers[y.charCodeAt(0)]=v}clearExecuteHandler(y){this._executeHandlers[y.charCodeAt(0)]&&delete this._executeHandlers[y.charCodeAt(0)]}setExecuteHandlerFallback(y){this._executeHandlerFb=y}registerCsiHandler(y,v){const _=this._identifier(y);this._csiHandlers[_]===void 0&&(this._csiHandlers[_]=[]);const w=this._csiHandlers[_];return w.push(v),{dispose:()=>{const C=w.indexOf(v);C!==-1&&w.splice(C,1)}}}clearCsiHandler(y){this._csiHandlers[this._identifier(y)]&&delete this._csiHandlers[this._identifier(y)]}setCsiHandlerFallback(y){this._csiHandlerFb=y}registerDcsHandler(y,v){return this._dcsParser.registerHandler(this._identifier(y),v)}clearDcsHandler(y){this._dcsParser.clearHandler(this._identifier(y))}setDcsHandlerFallback(y){this._dcsParser.setHandlerFallback(y)}registerOscHandler(y,v){return this._oscParser.registerHandler(y,v)}clearOscHandler(y){this._oscParser.clearHandler(y)}setOscHandlerFallback(y){this._oscParser.setHandlerFallback(y)}setErrorHandler(y){this._errorHandler=y}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(y,v,_,w,C){this._parseStack.state=y,this._parseStack.handlers=v,this._parseStack.handlerPos=_,this._parseStack.transition=w,this._parseStack.chunkPos=C}parse(y,v,_){let w,C=0,A=0,E=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,E=this._parseStack.chunkPos+1;else{if(_===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const S=this._parseStack.handlers;let k=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(_===!1&&k>-1){for(;k>=0&&(w=S[k](this._params),w!==!0);k--)if(w instanceof Promise)return this._parseStack.handlerPos=k,w}this._parseStack.handlers=[];break;case 4:if(_===!1&&k>-1){for(;k>=0&&(w=S[k](),w!==!0);k--)if(w instanceof Promise)return this._parseStack.handlerPos=k,w}this._parseStack.handlers=[];break;case 6:if(C=y[this._parseStack.chunkPos],w=this._dcsParser.unhook(C!==24&&C!==26,_),w)return w;C===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(C=y[this._parseStack.chunkPos],w=this._oscParser.end(C!==24&&C!==26,_),w)return w;C===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,E=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let S=E;S<v;++S){switch(C=y[S],A=this._transitions.table[this.currentState<<8|(C<160?C:b)],A>>4){case 2:for(let N=S+1;;++N){if(N>=v||(C=y[N])<32||C>126&&C<b){this._printHandler(y,S,N),S=N-1;break}if(++N>=v||(C=y[N])<32||C>126&&C<b){this._printHandler(y,S,N),S=N-1;break}if(++N>=v||(C=y[N])<32||C>126&&C<b){this._printHandler(y,S,N),S=N-1;break}if(++N>=v||(C=y[N])<32||C>126&&C<b){this._printHandler(y,S,N),S=N-1;break}}break;case 3:this._executeHandlers[C]?this._executeHandlers[C]():this._executeHandlerFb(C),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:S,code:C,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const k=this._csiHandlers[this._collect<<8|C];let O=k?k.length-1:-1;for(;O>=0&&(w=k[O](this._params),w!==!0);O--)if(w instanceof Promise)return this._preserveStack(3,k,O,A,S),w;O<0&&this._csiHandlerFb(this._collect<<8|C,this._params),this.precedingJoinState=0;break;case 8:do switch(C){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;
59default:this._params.addDigit(C-48)}while(++S<v&&(C=y[S])>47&&C<60);S--;break;case 9:this._collect<<=8,this._collect|=C;break;case 10:const T=this._escHandlers[this._collect<<8|C];let R=T?T.length-1:-1;for(;R>=0&&(w=T[R](),w!==!0);R--)if(w instanceof Promise)return this._preserveStack(4,T,R,A,S),w;R<0&&this._escHandlerFb(this._collect<<8|C),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|C,this._params);break;case 13:for(let N=S+1;;++N)if(N>=v||(C=y[N])===24||C===26||C===27||C>127&&C<b){this._dcsParser.put(y,S,N),S=N-1;break}break;case 14:if(w=this._dcsParser.unhook(C!==24&&C!==26),w)return this._preserveStack(6,[],0,A,S),w;C===27&&(A|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let N=S+1;;N++)if(N>=v||(C=y[N])<32||C>127&&C<b){this._oscParser.put(y,S,N),S=N-1;break}break;case 6:if(w=this._oscParser.end(C!==24&&C!==26),w)return this._preserveStack(5,[],0,A,S),w;C===27&&(A|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&A}}}o.EscapeSequenceParser=g},6242:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OscHandler=o.OscParser=void 0;const c=l(5770),u=l(482),d=[];o.OscParser=class{constructor(){this._state=0,this._active=d,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(h,m){this._handlers[h]===void 0&&(this._handlers[h]=[]);const b=this._handlers[h];return b.push(m),{dispose:()=>{const g=b.indexOf(m);g!==-1&&b.splice(g,1)}}}clearHandler(h){this._handlers[h]&&delete this._handlers[h]}setHandlerFallback(h){this._handlerFb=h}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=d}reset(){if(this._state===2)for(let h=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;h>=0;--h)this._active[h].end(!1);this._stack.paused=!1,this._active=d,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||d,this._active.length)for(let h=this._active.length-1;h>=0;h--)this._active[h].start();else this._handlerFb(this._id,"START")}_put(h,m,b){if(this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].put(h,m,b);else this._handlerFb(this._id,"PUT",(0,u.utf32ToString)(h,m,b))}start(){this.reset(),this._state=1}put(h,m,b){if(this._state!==3){if(this._state===1)for(;m<b;){const g=h[m++];if(g===59){this._state=2,this._start();break}if(g<48||57<g)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+g-48}this._state===2&&b-m>0&&this._put(h,m,b)}}end(h,m=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let b=!1,g=this._active.length-1,p=!1;if(this._stack.paused&&(g=this._stack.loopPosition-1,b=m,p=this._stack.fallThrough,this._stack.paused=!1),!p&&b===!1){for(;g>=0&&(b=this._active[g].end(h),b!==!0);g--)if(b instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=g,this._stack.fallThrough=!1,b;g--}for(;g>=0;g--)if(b=this._active[g].end(!1),b instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=g,this._stack.fallThrough=!0,b}else this._handlerFb(this._id,"END",h);this._active=d,this._id=-1,this._state=0}}},o.OscHandler=class{constructor(h){this._handler=h,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(h,m,b){this._hitLimit||(this._data+=(0,u.utf32ToString)(h,m,b),this._data.length>c.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(h){let m=!1;if(this._hitLimit)m=!1;else if(h&&(m=this._handler(this._data),m instanceof Promise))return m.then(b=>(this._data="",this._hitLimit=!1,b));return this._data="",this._hitLimit=!1,m}}},8742:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Params=void 0;const l=2147483647;class c{static fromArray(d){const h=new c;if(!d.length)return h;for(let m=Array.isArray(d[0])?1:0;m<d.length;++m){const b=d[m];if(Array.isArray(b))for(let g=0;g<b.length;++g)h.addSubParam(b[g]);else h.addParam(b)}return h}constructor(d=32,h=32){if(this.maxLength=d,this.maxSubParamsLength=h,h>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(d),this.length=0,this._subParams=new Int32Array(h),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(d),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const d=new c(this.maxLength,this.maxSubParamsLength);return d.params.set(this.params),d.length=this.length,d._subParams.set(this._subParams),d._subParamsLength=this._subParamsLength,d._subParamsIdx.set(this._subParamsIdx),d._rejectDigits=this._rejectDigits,d._rejectSubDigits=this._rejectSubDigits,d._digitIsSub=this._digitIsSub,d}toArray(){const d=[];for(let h=0;h<this.length;++h){d.push(this.params[h]);const m=this._subParamsIdx[h]>>8,b=255&this._subParamsIdx[h];b-m>0&&d.push(Array.prototype.slice.call(this._subParams,m,b))}return d}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(d){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=d>l?l:d}}addSubParam(d){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=d>l?l:d,this._subParamsIdx[this.length-1]++}}hasSubParams(d){return(255&this._subParamsIdx[d])-(this._subParamsIdx[d]>>8)>0}getSubParams(d){const h=this._subParamsIdx[d]>>8,m=255&this._subParamsIdx[d];return m-h>0?this._subParams.subarray(h,m):null}getSubParamsAll(){const d={};for(let h=0;h<this.length;++h){const m=this._subParamsIdx[h]>>8,b=255&this._subParamsIdx[h];b-m>
vendor: 4,425 bytes, line 59
590&&(d[h]=this._subParams.slice(m,b))}return d}addDigit(d){let h;if(this._rejectDigits||!(h=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const m=this._digitIsSub?this._subParams:this.params,b=m[h-1];m[h-1]=~b?Math.min(10*b+d,l):d}}o.Params=c},5741:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.AddonManager=void 0,o.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let l=this._addons.length-1;l>=0;l--)this._addons[l].instance.dispose()}loadAddon(l,c){const u={instance:c,dispose:c.dispose,isDisposed:!1};this._addons.push(u),c.dispose=()=>this._wrappedAddonDispose(u),c.activate(l)}_wrappedAddonDispose(l){if(l.isDisposed)return;let c=-1;for(let u=0;u<this._addons.length;u++)if(this._addons[u]===l){c=u;break}if(c===-1)throw new Error("Could not dispose an addon that has not been loaded");l.isDisposed=!0,l.dispose.apply(l.instance),this._addons.splice(c,1)}}},8771:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferApiView=void 0;const c=l(3785),u=l(511);o.BufferApiView=class{constructor(d,h){this._buffer=d,this.type=h}init(d){return this._buffer=d,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(d){const h=this._buffer.lines.get(d);if(h)return new c.BufferLineApiView(h)}getNullCell(){return new u.CellData}}},3785:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLineApiView=void 0;const c=l(511);o.BufferLineApiView=class{constructor(u){this._line=u}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(u,d){if(!(u<0||u>=this._line.length))return d?(this._line.loadCell(u,d),d):this._line.loadCell(u,new c.CellData)}translateToString(u,d,h){return this._line.translateToString(u,d,h)}}},8285:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferNamespaceApi=void 0;const c=l(8771),u=l(8460),d=l(844);class h extends d.Disposable{constructor(b){super(),this._core=b,this._onBufferChange=this.register(new u.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new c.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new c.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}o.BufferNamespaceApi=h},7975:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ParserApi=void 0,o.ParserApi=class{constructor(l){this._core=l}registerCsiHandler(l,c){return this._core.registerCsiHandler(l,u=>c(u.toArray()))}addCsiHandler(l,c){return this.registerCsiHandler(l,c)}registerDcsHandler(l,c){return this._core.registerDcsHandler(l,(u,d)=>c(u,d.toArray()))}addDcsHandler(l,c){return this.registerDcsHandler(l,c)}registerEscHandler(l,c){return this._core.registerEscHandler(l,c)}addEscHandler(l,c){return this.registerEscHandler(l,c)}registerOscHandler(l,c){return this._core.registerOscHandler(l,c)}addOscHandler(l,c){return this.registerOscHandler(l,c)}}},7090:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeApi=void 0,o.UnicodeApi=class{constructor(l){this._core=l}register(l){this._core.unicodeService.register(l)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(l){this._core.unicodeService.activeVersion=l}}},744:function(a,o,l){var c=this&&this.__decorate||function(p,y,v,_){var w,C=arguments.length,A=C<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,v):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(p,y,v,_);else for(var E=p.length-1;E>=0;E--)(w=p[E])&&(A=(C<3?w(A):C>3?w(y,v,A):w(y,v))||A);return C>3&&A&&Object.defineProperty(y,v,A),A},u=this&&this.__param||function(p,y){return function(v,_){y(v,_,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferService=o.MINIMUM_ROWS=o.MINIMUM_COLS=void 0;const d=l(8460),h=l(844),m=l(5295),b=l(2585);
59o.MINIMUM_COLS=2,o.MINIMUM_ROWS=1;let g=o.BufferService=class extends h.Disposable{get buffer(){return this.buffers.active}constructor(p){super(),this.isUserScrolling=!1,this._onResize=this.register(new d.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(p.rawOptions.cols||0,o.MINIMUM_COLS),this.rows=Math.max(p.rawOptions.rows||0,o.MINIMUM_ROWS),this.buffers=this.register(new m.BufferSet(p,this))}resize(p,y){this.cols=p,this.rows=y,this.buffers.resize(p,y),this._onResize.fire({cols:p,rows:y})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(p,y=!1){const v=this.buffer;let _;_=this._cachedBlankLine,_&&_.length===this.cols&&_.getFg(0)===p.fg&&_.getBg(0)===p.bg||(_=v.getBlankLine(p,y),this._cachedBlankLine=_),_.isWrapped=y;const w=v.ybase+v.scrollTop,C=v.ybase+v.scrollBottom;if(v.scrollTop===0){const A=v.lines.isFull;C===v.lines.length-1?A?v.lines.recycle().copyFrom(_):v.lines.push(_.clone()):v.lines.splice(C+1,0,_.clone()),A?this.isUserScrolling&&(v.ydisp=Math.max(v.ydisp-1,0)):(v.ybase++,this.isUserScrolling||v.ydisp++)}else{const A=C-w+1;v.lines.shiftElements(w+1,A-1,-1),v.lines.set(C,_.clone())}this.isUserScrolling||(v.ydisp=v.ybase),this._onScroll.fire(v.ydisp)}scrollLines(p,y,v){const _=this.buffer;if(p<0){if(_.ydisp===0)return;this.isUserScrolling=!0}else p+_.ydisp>=_.ybase&&(this.isUserScrolling=!1);const w=_.ydisp;_.ydisp=Math.max(Math.min(_.ydisp+p,_.ybase),0),w!==_.ydisp&&(y||this._onScroll.fire(_.ydisp))}};o.BufferService=g=c([u(0,b.IOptionsService)],g)},7994:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CharsetService=void 0,o.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(l){this.glevel=l,this.charset=this._charsets[l]}setgCharset(l,c){this._charsets[l]=c,this.glevel===l&&(this.charset=c)}}},1753:function(a,o,l){var c=this&&this.__decorate||function(_,w,C,A){var E,S=arguments.length,k=S<3?w:A===null?A=Object.getOwnPropertyDescriptor(w,C):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(_,w,C,A);else for(var O=_.length-1;O>=0;O--)(E=_[O])&&(k=(S<3?E(k):S>3?E(w,C,k):E(w,C))||k);return S>3&&k&&Object.defineProperty(w,C,k),k},u=this&&this.__param||function(_,w){return function(C,A){w(C,A,_)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreMouseService=void 0;const d=l(2585),h=l(8460),m=l(844),b={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:_=>_.button!==4&&_.action===1&&(_.ctrl=!1,_.alt=!1,_.shift=!1,!0)},VT200:{events:19,restrict:_=>_.action!==32},DRAG:{events:23,restrict:_=>_.action!==32||_.button!==3},ANY:{events:31,restrict:_=>!0}};function g(_,w){let C=(_.ctrl?16:0)|(_.shift?4:0)|(_.alt?8:0);return _.button===4?(C|=64,C|=_.action):(C|=3&_.button,4&_.button&&(C|=64),8&_.button&&(C|=128),_.action===32?C|=32:_.action!==0||w||(C|=3)),C}const p=String.fromCharCode,y={DEFAULT:_=>{const w=[g(_,!1)+32,_.col+32,_.row+32];return w[0]>255||w[1]>255||w[2]>255?"":`\x1B[M${p(w[0])}${p(w[1])}${p(w[2])}`},SGR:_=>{const w=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${g(_,!0)};${_.col};${_.row}${w}`},SGR_PIXELS:_=>{const w=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${g(_,!0)};${_.x};${_.y}${w}`}};let v=o.CoreMouseService=class extends m.Disposable{constructor(_,w){super(),this._bufferService=_,this._coreService=w,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new h.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const C of Object.keys(b))this.addProtocol(C,b[C]);for(const C of Object.keys(y))this.addEncoding(C,y[C]);this.reset()}addProtocol(_,w){this._protocols[_]=w}addEncoding(_,w){this._encodings[_]=w}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(_){if(!this._protocols[_])throw new Error(`unknown protocol "${_}"`);this._activeProtocol=_,this._onProtocolChange.fire(this._protocols[_].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(_){if(!this._encodings[_])throw new Error(`unknown encoding "${_}"`);this._activeEncoding=_}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(_){if(_.col<0||_.col>=this._bufferService.cols||_.row<0||_.row>=this._bufferService.rows||_.button===4&&_.action===32||_.button===3&&_.action!==32||_.button!==4&&(_.action===2||_.action===3)||(_.col++,_.row++,_.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,_,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(_))return!1;const w=this._encodings[this._activeEncoding](_);return w&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(w):this._coreService.triggerDataEvent(w,!0)),this._lastEvent=_,!0}explainEvents(_){return{down:!!(1&_),up:!!(2&_),drag:!!(4&_),move:!!(8&_),wheel:!!(16&_)}}_equalEvents(_,w,C){if(C){if(_.x!==w.x||_.y!==w.y)return!1}else if(_.col!==w.col||_.row!==w.row)return!1;return _.button===w.button&&_.action===w.action&&_.ctrl===w.ctrl&&_.alt===w.alt&&_.shift===w.shift}};o.CoreMouseService=v=c([u(0,d.IBufferService),u(1,d.ICoreService)],v)},6975:function(a,o,l){var c=this&&this.__decorate||function(v,_,w,C){var A,E=arguments.length,S=E<3?_:C===null?C=Object.getOwnPropertyDescriptor(_,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,_,w,C);else for(var k=v.length-1;k>=0;k--)(A=v[k])&&(S=(E<3?A(S):E>3?A(_,w,S):A(_,w))||S);return E>3&&S&&Object.defineProperty(_,w,S),S},u=this&&this.__param||function(v,_){return function(w,C){_(w,C,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreService=void 0;const d=l(1439),h=l(8460),m=l(844),b=l(2585),g=Object.freeze({insertMode:!1}),p=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let y=o.CoreService=class extends m.Disposable{constructor(v,_,w){super(),this._bufferService=v,this._logService=_,this._optionsService=w,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new h.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new h.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new h.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new h.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,d.clone)(g),this.decPrivateModes=(0,d.clone)(p)}reset(){this.modes=(0,d.clone)(g),this.decPrivateModes=(0,d.clone)(p)}triggerDataEvent(v,_=!1){if(this._optionsService.rawOptions.disableStdin)return;const w=this._bufferService.buffer;_&&this._optionsService.rawOptions.scrollOnUserInput&&w.ybase!==w.ydisp&&this._onRequestScrollToBottom.f
vendor: 8,445 bytes, line 59
59ire(),_&&this._onUserInput.fire(),this._logService.debug(`sending data "${v}"`,()=>v.split("").map(C=>C.charCodeAt(0))),this._onData.fire(v)}triggerBinaryEvent(v){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${v}"`,()=>v.split("").map(_=>_.charCodeAt(0))),this._onBinary.fire(v))}};o.CoreService=y=c([u(0,b.IBufferService),u(1,b.ILogService),u(2,b.IOptionsService)],y)},9074:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DecorationService=void 0;const c=l(8055),u=l(8460),d=l(844),h=l(6106);let m=0,b=0;class g extends d.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new h.SortedList(v=>v?.marker.line),this._onDecorationRegistered=this.register(new u.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new u.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,d.toDisposable)(()=>this.reset()))}registerDecoration(v){if(v.marker.isDisposed)return;const _=new p(v);if(_){const w=_.marker.onDispose(()=>_.dispose());_.onDispose(()=>{_&&(this._decorations.delete(_)&&this._onDecorationRemoved.fire(_),w.dispose())}),this._decorations.insert(_),this._onDecorationRegistered.fire(_)}return _}reset(){for(const v of this._decorations.values())v.dispose();this._decorations.clear()}*getDecorationsAtCell(v,_,w){let C=0,A=0;for(const E of this._decorations.getKeyIterator(_))C=E.options.x??0,A=C+(E.options.width??1),v>=C&&v<A&&(!w||(E.options.layer??"bottom")===w)&&(yield E)}forEachDecorationAtCell(v,_,w,C){this._decorations.forEachByKey(_,A=>{m=A.options.x??0,b=m+(A.options.width??1),v>=m&&v<b&&(!w||(A.options.layer??"bottom")===w)&&C(A)})}}o.DecorationService=g;class p extends d.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=c.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=c.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(v){super(),this.options=v,this.onRenderEmitter=this.register(new u.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new u.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=v.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.InstantiationService=o.ServiceCollection=void 0;const c=l(2585),u=l(8343);class d{constructor(...m){this._entries=new Map;for(const[b,g]of m)this.set(b,g)}set(m,b){const g=this._entries.get(m);return this._entries.set(m,b),g}forEach(m){for(const[b,g]of this._entries.entries())m(b,g)}has(m){return this._entries.has(m)}get(m){return this._entries.get(m)}}o.ServiceCollection=d,o.InstantiationService=class{constructor(){this._services=new d,this._services.set(c.IInstantiationService,this)}setService(h,m){this._services.set(h,m)}getService(h){return this._services.get(h)}createInstance(h,...m){const b=(0,u.getServiceDependencies)(h).sort((y,v)=>y.index-v.index),g=[];for(const y of b){const v=this._services.get(y.id);if(!v)throw new Error(`[createInstance] ${h.name} depends on UNKNOWN service ${y.id}.`);g.push(v)}const p=b.length>0?b[0].index:m.length;if(m.length!==p)throw new Error(`[createInstance] First service dependency of ${h.name} at position ${p+1} conflicts with ${m.length} static arguments`);return new h(...m,...g)}}},7866:function(a,o,l){var c=this&&this.__decorate||function(p,y,v,_){var w,C=arguments.length,A=C<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,v):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(p,y,v,_);else for(var E=p.length-1;E>=0;E--)(w=p[E])&&(A=(C<3?w(A):C>3?w(y,v,A):w(y,v))||A);return C>3&&A&&Object.defineProperty(y,v,A),A},u=this&&this.__param||function(p,y){return function(v,_){y(v,_,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.traceCall=o.setTraceLogger=o.LogService=void 0;const d=l(844),h=l(2585),m={trace:h.LogLevelEnum.TRACE,debug:h.LogLevelEnum.DEBUG,info:h.LogLevelEnum.INFO,warn:h.LogLevelEnum.WARN,error:h.LogLevelEnum.ERROR,off:h.LogLevelEnum.OFF};let b,g=o.LogService=class extends d.Disposable{get logLevel(){return this._logLevel}constructor(p){super(),this._optionsService=p,this._logLevel=h.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),b=this}_updateLogLevel(){this._logLevel=m[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(p){for(let y=0;y<p.length;y++)typeof p[y]=="function"&&(p[y]=p[y]())}_log(p,y,v){this._evalLazyOptionalParams(v),p.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+y,...v)}trace(p,...y){this._logLevel<=h.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,p,y)}debug(p,...y){this._logLevel<=h.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,p,y)}info(p,...y){this._logLevel<=h.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,p,y)}warn(p,...y){this._logLevel<=h.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,p,y)}error(p,...y){this._logLevel<=h.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,p,y)}};o.LogService=g=c([u(0,h.IOptionsService)],g),o.setTraceLogger=function(p){b=p},o.traceCall=function(p,y,v){if(typeof v.value!="function")throw new Error("not supported");const _=v.value;v.value=function(...w){if(b.logLevel!==h.LogLevelEnum.TRACE)return _.apply(this,w);b.trace(`GlyphRenderer#${_.name}(${w.map(A=>JSON.stringify(A)).join(", ")})`);const C=_.apply(this,w);return b.trace(`GlyphRenderer#${_.name} return`,C),C}}},7302:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OptionsService=o.DEFAULT_OPTIONS=void 0;const c=l(8460),u=l(844),d=l(6114);o.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:d.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const h=["normal","bold","100","200","300","400","500","600","700","800","900"];class m extends u.Disposable{constructor(g){super(),this._onOptionChange=this.register(new c.EventEmitter),this.onOptionChange=this._onOptionChange.event;const p={...o.DEFAULT_OPTIONS};for(const y in g)if(y in p)try{const v=g[y];p[y]=this._sanitizeAndValidateOption(y,v)}catch(v){console.error(v)}this.rawOptions=p,this.options={...p},this._setupOptions(),this.register((0,u.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(g,p){return this.onOptionChange(y=>{y===g&&p(this.rawOptions[g])})}onMultipleOptionChange(g,p){return this.onOptionChange(y=>{g.indexOf(y)!==-1&&p()})}_setupOptions(){const g=y=>{if(!(y in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);return this.rawOptions[y]},p=(y,v)=>{if(!(y in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);v=this._sanitizeAndValidateOption(y,v),this.rawOptions[y]!==v&&(this.rawOptions[y]=v,this._onOptionChange.fire(y))};
59for(const y in this.rawOptions){const v={get:g.bind(this,y),set:p.bind(this,y)};Object.defineProperty(this.options,y,v)}}_sanitizeAndValidateOption(g,p){switch(g){case"cursorStyle":if(p||(p=o.DEFAULT_OPTIONS[g]),!function(y){return y==="block"||y==="underline"||y==="bar"}(p))throw new Error(`"${p}" is not a valid value for ${g}`);break;case"wordSeparator":p||(p=o.DEFAULT_OPTIONS[g]);break;case"fontWeight":case"fontWeightBold":if(typeof p=="number"&&1<=p&&p<=1e3)break;p=h.includes(p)?p:o.DEFAULT_OPTIONS[g];break;case"cursorWidth":p=Math.floor(p);case"lineHeight":case"tabStopWidth":if(p<1)throw new Error(`${g} cannot be less than 1, value: ${p}`);break;case"minimumContrastRatio":p=Math.max(1,Math.min(21,Math.round(10*p)/10));break;case"scrollback":if((p=Math.min(p,4294967295))<0)throw new Error(`${g} cannot be less than 0, value: ${p}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(p<=0)throw new Error(`${g} cannot be less than or equal to 0, value: ${p}`);break;case"rows":case"cols":if(!p&&p!==0)throw new Error(`${g} must be numeric, value: ${p}`);break;case"windowsPty":p=p??{}}return p}}o.OptionsService=m},2660:function(a,o,l){var c=this&&this.__decorate||function(m,b,g,p){var y,v=arguments.length,_=v<3?b:p===null?p=Object.getOwnPropertyDescriptor(b,g):p;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,b,g,p);else for(var w=m.length-1;w>=0;w--)(y=m[w])&&(_=(v<3?y(_):v>3?y(b,g,_):y(b,g))||_);return v>3&&_&&Object.defineProperty(b,g,_),_},u=this&&this.__param||function(m,b){return function(g,p){b(g,p,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkService=void 0;const d=l(2585);let h=o.OscLinkService=class{constructor(m){this._bufferService=m,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(m){const b=this._bufferService.buffer;if(m.id===void 0){const w=b.addMarker(b.ybase+b.y),C={data:m,id:this._nextId++,lines:[w]};return w.onDispose(()=>this._removeMarkerFromLink(C,w)),this._dataByLinkId.set(C.id,C),C.id}const g=m,p=this._getEntryIdKey(g),y=this._entriesWithId.get(p);if(y)return this.addLineToLink(y.id,b.ybase+b.y),y.id;const v=b.addMarker(b.ybase+b.y),_={id:this._nextId++,key:this._getEntryIdKey(g),data:g,lines:[v]};return v.onDispose(()=>this._removeMarkerFromLink(_,v)),this._entriesWithId.set(_.key,_),this._dataByLinkId.set(_.id,_),_.id}addLineToLink(m,b){const g=this._dataByLinkId.get(m);if(g&&g.lines.every(p=>p.line!==b)){const p=this._bufferService.buffer.addMarker(b);g.lines.push(p),p.onDispose(()=>this._removeMarkerFromLink(g,p))}}getLinkData(m){return this._dataByLinkId.get(m)?.data}_getEntryIdKey(m){return`${m.id};;${m.uri}`}_removeMarkerFromLink(m,b){const g=m.lines.indexOf(b);g!==-1&&(m.lines.splice(g,1),m.lines.length===0&&(m.data.id!==void 0&&this._entriesWithId.delete(m.key),this._dataByLinkId.delete(m.id)))}};o.OscLinkService=h=c([u(0,d.IBufferService)],h)},8343:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createDecorator=o.getServiceDependencies=o.serviceRegistry=void 0;const l="di$target",c="di$dependencies";o.serviceRegistry=new Map,o.getServiceDependencies=function(u){return u[c]||[]},o.createDecorator=function(u){if(o.serviceRegistry.has(u))return o.serviceRegistry.get(u);const d=function(h,m,b){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(g,p,y){p[l]===p?p[c].push({id:g,index:y}):(p[c]=[{id:g,index:y}],p[l]=p)})(d,h,b)};return d.toString=()=>u,o.serviceRegistry.set(u,d),d}},2585:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.IDecorationService=o.IUnicodeService=o.IOscLinkService=o.IOptionsService=o.ILogService=o.LogLevelEnum=o.IInstantiationService=o.ICharsetService=o.ICoreService=o.ICoreMouseService=o.IBufferService=void 0;const c=l(8343);var u;o.IBufferService=(0,c.createDecorator)("BufferService"),o.ICoreMouseService=(0,c.createDecorator)("CoreMouseService"),o.ICoreService=(0,c.createDecorator)("CoreService"),o.ICharsetService=(0,c.createDecorator)("CharsetService"),o.IInstantiationService=(0,c.createDecorator)("InstantiationService"),function(d){d[d.TRACE=0]="TRACE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.ERROR=4]="ERROR",d[d.OFF=5]="OFF"}(u||(o.LogLevelEnum=u={})),o.ILogService=(0,c.createDecorator)("LogService"),o.IOptionsService=(0,c.createDecorator)("OptionsService"),o.IOscLinkService=(0,c.createDecorator)("OscLinkService"),o.IUnicodeService=(0,c.createDecorator)("UnicodeService"),o.IDecorationService=(0,c.createDecorator)("DecorationService")},1480:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeService=void 0;const c=l(8460),u=l(225);class d{static extractShouldJoin(m){return(1&m)!=0}static extractWidth(m){return m>>1&3}static extractCharKind(m){return m>>3}static createPropertyValue(m,b,g=!1){return(16777215&m)<<3|(3&b)<<1|(g?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new c.EventEmitter,this.onChange=this._onChange.event;const m=new u.UnicodeV6;this.register(m),this._active=m.version,this._activeProvider=m}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(m){if(!this._providers[m])throw new Error(`unknown Unicode version "${m}"`);this._active=m,this._activeProvider=this._providers[m],this._onChange.fire(m)}register(m){this._providers[m.version]=m}wcwidth(m){return this._activeProvider.wcwidth(m)}getStringCellWidth(m){let b=0,g=0;const p=m.length;for(let y=0;y<p;++y){let v=m.charCodeAt(y);if(55296<=v&&v<=56319){if(++y>=p)return b+this.wcwidth(v);const C=m.charCodeAt(y);56320<=C&&C<=57343?v=1024*(v-55296)+C-56320+65536:b+=this.wcwidth(C)}const _=this.charProperties(v,g);let w=d.extractWidth(_);d.extractShouldJoin(_)&&(w-=d.extractWidth(g)),b+=w,g=_}return b}charProperties(m,b){return this._activeProvider.charProperties(m,b)}}o.UnicodeService=d}},n={};function s(a){var o=n[a];if(o!==void 0)return o.exports;var l=n[a]={exports:{}};return r[a].call(l.exports,l,l.exports,s),l.exports}var i={};return(()=>{var a=i;Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;
vendor: 4,336 bytes, lines 59-60
59const o=s(9042),l=s(3236),c=s(844),u=s(5741),d=s(8285),h=s(7975),m=s(7090),b=["cols","rows"];class g extends c.Disposable{constructor(y){super(),this._core=this.register(new l.Terminal(y)),this._addonManager=this.register(new u.AddonManager),this._publicOptions={...this._core.options};const v=w=>this._core.options[w],_=(w,C)=>{this._checkReadonlyOptions(w),this._core.options[w]=C};for(const w in this._core.options){const C={get:v.bind(this,w),set:_.bind(this,w)};Object.defineProperty(this._publicOptions,w,C)}}_checkReadonlyOptions(y){if(b.includes(y))throw new Error(`Option "${y}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new h.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new m.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new d.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const y=this._core.coreService.decPrivateModes;let v="none";switch(this._core.coreMouseService.activeProtocol){case"X10":v="x10";break;case"VT200":v="vt200";break;case"DRAG":v="drag";break;case"ANY":v="any"}return{applicationCursorKeysMode:y.applicationCursorKeys,applicationKeypadMode:y.applicationKeypad,bracketedPasteMode:y.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:v,originMode:y.origin,reverseWraparoundMode:y.reverseWraparound,sendFocusMode:y.sendFocus,wraparoundMode:y.wraparound}}get options(){return this._publicOptions}set options(y){for(const v in y)this._publicOptions[v]=y[v]}blur(){this._core.blur()}focus(){this._core.focus()}input(y,v=!0){this._core.input(y,v)}resize(y,v){this._verifyIntegers(y,v),this._core.resize(y,v)}open(y){this._core.open(y)}attachCustomKeyEventHandler(y){this._core.attachCustomKeyEventHandler(y)}attachCustomWheelEventHandler(y){this._core.attachCustomWheelEventHandler(y)}registerLinkProvider(y){return this._core.registerLinkProvider(y)}registerCharacterJoiner(y){return this._checkProposedApi(),this._core.registerCharacterJoiner(y)}deregisterCharacterJoiner(y){this._checkProposedApi(),this._core.deregisterCharacterJoiner(y)}registerMarker(y=0){return this._verifyIntegers(y),this._core.registerMarker(y)}registerDecoration(y){return this._checkProposedApi(),this._verifyPositiveIntegers(y.x??0,y.width??0,y.height??0),this._core.registerDecoration(y)}hasSelection(){return this._core.hasSelection()}select(y,v,_){this._verifyIntegers(y,v,_),this._core.select(y,v,_)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(y,v){this._verifyIntegers(y,v),this._core.selectLines(y,v)}dispose(){super.dispose()}scrollLines(y){this._verifyIntegers(y),this._core.scrollLines(y)}scrollPages(y){this._verifyIntegers(y),this._core.scrollPages(y)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(y){this._verifyIntegers(y),this._core.scrollToLine(y)}clear(){this._core.clear()}write(y,v){this._core.write(y,v)}writeln(y,v){this._core.write(y),this._core.write(`\r 60`,v)}paste(y){this._core.paste(y)}refresh(y,v){this._verifyIntegers(y,v),this._core.refresh(y,v)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return o}
60_verifyIntegers(...y){for(const v of y)if(v===1/0||isNaN(v)||v%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const v of y)if(v&&(v===1/0||isNaN(v)||v%1!=0||v<0))throw new Error("This API only accepts positive integers")}}a.Terminal=g})(),i})())})(uI);var zV=uI.exports;const VV=getComputedStyle(document.documentElement),yn=t=>VV.getPropertyValue(t)||void 0;function xb(t){return{cursor:yn("--bolt-elements-terminal-cursorColor"),cursorAccent:yn("--bolt-elements-terminal-cursorColorAccent"),foreground:yn("--bolt-elements-terminal-textColor"),background:yn("--bolt-elements-terminal-backgroundColor"),selectionBackground:yn("--bolt-elements-terminal-selection-backgroundColor"),selectionForeground:yn("--bolt-elements-terminal-selection-textColor"),selectionInactiveBackground:yn("--bolt-elements-terminal-selection-backgroundColorInactive"),black:yn("--bolt-elements-terminal-color-black"),red:yn("--bolt-elements-terminal-color-red"),green:yn("--bolt-elements-terminal-color-green"),yellow:yn("--bolt-elements-terminal-color-yellow"),blue:yn("--bolt-elements-terminal-color-blue"),magenta:yn("--bolt-elements-terminal-color-magenta"),cyan:yn("--bolt-elements-terminal-color-cyan"),white:yn("--bolt-elements-terminal-color-white"),brightBlack:yn("--bolt-elements-terminal-color-brightBlack"),brightRed:yn("--bolt-elements-terminal-color-brightRed"),brightGreen:yn("--bolt-elements-terminal-color-brightGreen"),brightYellow:yn("--bolt-elements-terminal-color-brightYellow"),brightBlue:yn("--bolt-elements-terminal-color-brightBlue"),brightMagenta:yn("--bolt-elements-terminal-color-brightMagenta"),brightCyan:yn("--bolt-elements-terminal-color-brightCyan"),brightWhite:yn("--bolt-elements-terminal-color-brightWhite"),...t}}const SC=ya("Terminal"),CC=x.memo(x.forwardRef(({className:t,theme:e,readonly:r,id:n,onTerminalReady:s,onTerminalResize:i},a)=>{const o=x.useRef(null),l=x.useRef();return x.useEffect(()=>{const c=o.current;if(!c)return;let u=0,d=!1;const h=new HV.FitAddon,m=new UV.WebLinksAddon,b=new zV.Terminal({cursorBlink:!0,convertEol:!0,disableStdin:r,theme:xb(r?{cursor:"#00000000"}:{}),fontSize:12,fontFamily:"Menlo, courier-new, courier, monospace"});l.current=b,b.loadAddon(h),b.loadAddon(m),b.open(c);const g=()=>{d||u!==0||(u=window.requestAnimationFrame(()=>{if(u=0,d)return;const{width:y,height:v}=c.getBoundingClientRect();if(!(y<=0||v<=0))try{h.fit(),i?.(b.cols,b.rows)}catch(_){SC.debug(`Skipped terminal fit [${n}] before xterm renderer was ready`,{error:_ instanceof Error?_.message:String(_)})}}))};g();const p=new ResizeObserver(()=>{g()});return p.observe(c),SC.debug(`Attach [${n}]`),s?.(b),()=>{d=!0,u!==0&&window.cancelAnimationFrame(u),p.disconnect(),b.dispose()}},[]),x.useEffect(()=>{const c=l.current;c.options.theme=xb(r?{cursor:"#00000000"}:{}),c.options.disableStdin=r},[e,r]),x.useImperativeHandle(a,()=>({reloadStyles:()=>{const c=l.current;c.options.theme=xb(r?{cursor:"#00000000"}:{})},getTerminal:()=>l.current}),[]),f.jsx("div",{className:t,ref:o})})),GV=ya("Terminal"),AC=3,Cy=25,qV=x.memo(()=>{const t=We(j.showTerminal),e=We(Ed),r=x.useRef([]),n=x.useRef(null),s=x.useRef(!1),[i,a]=x.useState(0),[o,l]=x.useState(0),c=()=>{o<AC&&(l(o+1),a(o))},u=d=>{if(d===0)return;const h=r.current[d];if(h?.getTerminal){const m=h.getTerminal();m&&j.detachTerminal(m)}r.current.splice(d,1),l(o-1),i===d?a(Math.max(0,d-1)):i>d&&a(i-1)};return x.useEffect(()=>()=>{r.current.forEach((d,h)=>{if(d?.getTerminal){const m=d.getTerminal();m&&(h===0?j.detachBoltTerminal(m):j.detachTerminal(m))}})},[]),x.useEffect(()=>{const{current:d}=n;if(!d)return;const h=d.isCollapsed();!t&&!h?d.collapse():t&&h&&d.resize(Cy),s.current=!1},[t]),x.useEffect(()=>{const d=kE.on("toggleTerminal",()=>{s.current=!0}),h=Ed.subscribe(()=>{for(const m of Object.values(r.current))m?.reloadStyles()});return()=>{d(),h()}},[]),f.jsx(vd,{ref:n,defaultSize:t?Cy:0,minSize:10,collapsible:!0,onExpand:()=>{s.current||j.toggleTerminal(!0)},onCollapse:()=>{s.current||j.toggleTerminal(!1)},children:f.jsx("div",{className:"h-full",children:f.jsxs("div",{className:"bg-bolt-elements-terminals-background h-full flex flex-col",children:[f.jsxs("div",{className:"flex items-center bg-bolt-elements-background-depth-2 border-y border-bolt-elements-borderColor gap-1.5 min-h-[34px] p-2",children:[Array.from({length:o+1},(d,h)=>{const m=i===h;return f.jsx(_t.Fragment,{children:h==0?f.jsxs("button",{className:ue("flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full",{"bg-bolt-elements-terminals-buttonBackgroun
60d text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary":m,"bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground":!m}),onClick:()=>a(h),children:[f.jsx("div",{className:"i-ph:terminal-window-duotone text-lg"}),"Genie Terminal"]},h):f.jsx(_t.Fragment,{children:f.jsxs("button",{className:ue("flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full",{"bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textPrimary":m,"bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground":!m}),onClick:()=>a(h),children:[f.jsx("div",{className:"i-ph:terminal-window-duotone text-lg"}),"Terminal ",o>1&&h,f.jsx("button",{className:"bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary hover:bg-transparent rounded",onClick:b=>{b.stopPropagation(),u(h)},children:f.jsx("div",{className:"i-ph:x text-xs"})})]},h)})},h)}),o<AC&&f.jsx(tu,{icon:"i-ph:plus",size:"md",onClick:c}),f.jsx(tu,{className:"ml-auto",icon:"i-ph:caret-down",title:"Close",size:"md",onClick:()=>j.toggleTerminal(!1)})]}),Array.from({length:o+1},(d,h)=>{const m=i===h;return GV.debug(`Starting genie terminal [${h}]`),h==0?f.jsx(CC,{id:`terminal_${h}`,className:ue("h-full overflow-hidden modern-scrollbar-invert",{hidden:!m}),ref:b=>{r.current[h]=b},onTerminalReady:b=>j.attachBoltTerminal(b),onTerminalResize:(b,g)=>j.onTerminalResize(b,g),theme:e},h):f.jsx(CC,{id:`terminal_${h}`,className:ue("modern-scrollbar h-full overflow-hidden",{hidden:!m}),ref:b=>{r.current[h]=b},onTerminalReady:b=>j.attachTerminal(b),onTerminalResize:(b,g)=>j.onTerminalResize(b,g),theme:e},h)})]})})})});async function KV(t,e,r,n){if(!t||typeof t.internal?.textSearch!="function"){console.error("WebContainer instance not available or internal searchText method is missing/not a function.");return}const s={...r,folders:[Za]},i=(a,o)=>{const l=[];o.forEach(c=>{const u=c.preview.text.split(` 61`);c.ranges.forEach(d=>{let h="(Preview line not found)",m=-1;if(c.preview.matches.length>0){const b=c.preview.matches[0].startLineNumber;m=d.startLineNumber-b}m>=0&&m<u.length?h=u[m]:h=u[0]??"(Preview unavailable)",l.push({path:a,lineNumber:d.startLineNumber,previewText:h,matchCharStart:d.startColumn,matchCharEnd:d.endColumn})})}),l.length>0&&n(l)};try{await t.internal.textSearch(e,s,i)}catch(a){console.error("Error during internal text search:",a)}}function YV(t){return t.reduce((e,r)=>(e[r.path]||(e[r.path]=[]),e[r.path].push(r),e),{})}function XV(){const[t,e]=x.useState(""),[r,n]=x.useState([]),[s,i]=x.useState(!1),[a,o]=x.useState({}),[l,c]=x.useState(!1),u=x.useMemo(()=>YV(r),[r]);x.useEffect(()=>{if(r.length>0){const b={};Object.keys(u).forEach(g=>{b[g]=!0}),o(b)}},[u,r]);const d=x.useCallback(async b=>{if(!b.trim()){n([]),i(!1),o({}),c(!1);return}i(!0),n([]),o({}),c(!0);const g=300,p=Date.now();try{const y=await ev;await KV(y,b,{homeDir:Za,includes:["**/*.*"],excludes:["**/node_modules/**","**/package-lock.json","**/.git/**","**/dist/**","**/*.lock"],gitignore:!0,requireGit:!1,globalIgnoreFiles:!0,ignoreSymlinks:!1,resultLimit:500,isRegex:!1,caseSensitive:!1,isWordMatch:!1},w=>{n(C=>[...C,...w])})}catch(y){console.error("Failed to initiate search:",y)}finally{const y=Date.now()-p;y<g?setTimeout(()=>i(!1),g-y):i(!1)}},[]),h=x.useCallback(sh(d,300),[d]);x.useEffect(()=>{h(t)},[t,h]);const m=(b,g)=>{j.setSelectedFile(b);const p=typeof g=="number"?Math.max(0,g-1):void 0;j.setCurrentDocumentScrollPosition({line:p,column:0})};return f.jsxs("div",{className:"flex flex-col h-full bg-bolt-elements-background-depth-2",children:[f.jsx("div",{className:"flex items-center py-3 px-3",children:f.jsx("div",{className:"relative flex-1",children:f.jsx("input",{type:"text",value:t,onChange:b=>e(b.target.value),placeholder:"Search",className:"w-full px-2 py-1 rounded-md bg-bolt-elements-background-depth-3 text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary focus:outline-none transition-all"})})}),f.jsxs("div",{className:"flex-1 overflow-auto py-2",children:[s&&f.jsxs("div",{className:"flex items-center justify-center h-32 text-bolt-elements-textTertiary",children:[f.jsx("div",{className:"i-ph:circle-notch animate-spin mr-2"})," Searching..."]}),!s&&l&&r.length===0&&t.trim()!==""&&f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500",children:"No results found."}),!s&&Object.keys(u).map(b=>f.jsxs("div",{className:"mb-2",children:[f.jsxs("button",{className:"flex gap-2 items-center w-full text-left py-1 px-2 text-bolt-elements-textSecondary bg-transparent hover:bg-bolt-elements-background-depth-3 group",onClick:()=>o(g=>({...g,[b]:!g[b]})),children:[f.jsx("span",{className:" i-ph:caret-down-thin w-3 h-3 text-bolt-elements-textSecondary transition-transform",style:{transform:a[b]?"rotate(180deg)":void 0}}),f.jsx("span",{className:"font-normal text-sm",children:b.split("/").pop()}),f.jsx("span",{className:"h-5.5 w-5.5 flex items-center justify-center text-xs ml-auto bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent rounded-full",children:u[b].length})]}),a[b]&&f.jsx("div",{className:"",children:u[b].map((g,p)=>{const v=g.matchCharStart<=7,_=v?0:g.matchCharStart-7,w=g.previewText.slice(_),C=v?g.matchCharStart:7,A=v?g.matchCharEnd:7+(g.matchCharEnd-g.matchCharStart);return f.jsx("div",{className:"hover:bg-bolt-elements-background-depth-3 cursor-pointer transition-colors pl-6 py-1",onClick:()=>m(g.path,g.lineNumber),children:f.jsxs("pre",{className:"font-mono text-xs text-bolt-elements-textTertiary truncate",children:[!v&&f.jsx("span",{children:"..."}),w.slice(0,C),f.jsx("span",{className:"bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent rounded px-1",children:w.slice(C,A)}),w.slice(A)]})},p)})})]},b))]})]})}function JV(){const[t,e]=x.useState([]),[r,n]=x.useState(new Set),[s,i]=x.useState("all"),[a,o]=x.useState("");x.useEffect(()=>{const g=()=>{const y=[],v=j.files.get();Object.entries(v).forEach(([_,w])=>
61{w&&(w.type==="file"&&w.isLocked?y.push({path:_,type:"file"}):w.type==="folder"&&w.isLocked&&y.push({path:_,type:"folder"}))}),e(y)};g();const p=setInterval(g,5e3);return()=>clearInterval(p)},[]);const l=t.filter(g=>!(s==="files"&&g.type!=="file"||s==="folders"&&g.type!=="folder"||a&&!g.path.toLowerCase().includes(a.toLowerCase()))).sort((g,p)=>g.path.localeCompare(p.path)),c=g=>{const p=new Set(r);p.has(g)?p.delete(g):p.add(g),n(p)},u=g=>{if(g===!0){const p=new Set(l.map(y=>y.path));n(p)}else n(new Set)},d=()=>{if(r.size===0){Se.error("No items selected to unlock.");return}let g=0;r.forEach(p=>{const y=t.find(v=>v.path===p);y&&(y.type==="file"?j.unlockFile(p):j.unlockFolder(p),g++)}),g>0&&(Se.success(`Unlocked ${g} selected item(s).`),n(new Set))},h=l.length>0&&r.size===l.length,m=r.size>0&&r.size<l.length,b=h?!0:m?"indeterminate":!1;return f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 border-b border-bolt-elements-borderColor",children:[f.jsxs("div",{className:"relative flex-1",children:[f.jsx("span",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary i-ph:magnifying-glass text-xs pointer-events-none"}),f.jsx("input",{type:"text",placeholder:"Search...",className:"w-full text-xs pl-6 pr-2 py-0.5 h-6 bg-bolt-elements-background-depth-2 text-bolt-elements-textPrimary rounded border border-bolt-elements-borderColor focus:outline-none",value:a,onChange:g=>o(g.target.value),style:{minWidth:0}})]}),f.jsxs("select",{className:"text-xs px-1 py-0.5 h-6 bg-bolt-elements-background-depth-2 text-bolt-elements-textPrimary rounded border border-bolt-elements-borderColor focus:outline-none",value:s,onChange:g=>i(g.target.value),children:[f.jsx("option",{value:"all",children:"All"}),f.jsx("option",{value:"files",children:"Files"}),f.jsx("option",{value:"folders",children:"Folders"})]})]}),f.jsxs("div",{className:"flex items-center justify-between px-2 py-1 text-xs text-bolt-elements-textSecondary",children:[f.jsxs("div",{children:[f.jsx(op,{checked:b,onCheckedChange:u,className:"w-3 h-3 rounded border-bolt-elements-borderColor mr-2","aria-label":"Select all items",disabled:l.length===0}),f.jsx("span",{children:"All"})]}),r.size>0&&f.jsx("button",{className:"ml-auto px-2 py-0.5 rounded bg-bolt-elements-button-secondary-background hover:bg-bolt-elements-button-secondary-backgroundHover text-bolt-elements-button-secondary-text text-xs flex items-center gap-1",onClick:d,title:"Unlock all selected items",children:"Unlock all"}),f.jsx("div",{})]}),f.jsx("div",{className:"flex-1 overflow-auto modern-scrollbar px-1 py-1",children:l.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bolt-elements-textTertiary text-xs gap-2",children:[f.jsx("span",{className:"i-ph:lock-open-duotone text-lg opacity-50"}),f.jsx("span",{children:"No locked items found"})]}):f.jsx("ul",{className:"space-y-1",children:l.map(g=>f.jsxs("li",{className:ue("text-bolt-elements-textTertiary flex items-center gap-2 px-2 py-1 rounded hover:bg-bolt-elements-background-depth-2 transition-colors group",r.has(g.path)?"bg-bolt-elements-background-depth-2":""),children:[f.jsx(op,{checked:r.has(g.path),onCheckedChange:()=>c(g.path),className:"w-3 h-3 rounded border-bolt-elements-borderColor","aria-labelledby":`item-label-${g.path}`}),f.jsx("span",{className:ue("shrink-0 text-bolt-elements-textTertiary text-xs",g.type==="file"?"i-ph:file-text-duotone":"i-ph:folder-duotone")}),f.jsx("span",{id:`item-label-${g.path}`,className:"truncate flex-1 text-xs",title:g.path,children:g.path.replace("/home/project/","")}),f.jsx("span",{className:ue("inline-flex items-center px-1 rounded-sm text-xs","bg-red-500/10 text-red-500")}),f.jsx("button",{className:"flex items-center px-1 py-0.5 text-xs rounded bg-transparent hover:bg-bolt-elements-background-depth-3",onClick:()=>{g.type==="file"?j.unlockFile(g.path):j.unlockFolder(g.path),Se.success(`${g.path.replace("/home/project/","")} unlocked`)},title:"Unlock",children:f.jsx("span",{className:"i-ph:lock-open text-xs"})})]},g.path))})}),f.jsx("div",{className:"px-2 py-1 border-t border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-xs text-bolt-elements-textTertiary flex justify-between items-center",children:f.jsxs("div",{children:[l.length," item(s) ⢠",r.size," selected"]})})]})}const QV=(t,e,r)=>{const n=r?"running":"complete";switch(t){case"STREAM_COMPLETE":return{id:"builder-lifecycle-validation",label:e.isFollowUpRequest?"Validating app updates":"Validating generated app",status:n};case"INSTALLING_DEPENDENCIES":return{id:"builder-lifecycle-installing-dependencies",label:r?e.currentInstallLabel:"Installing dependencies",status:n};case"BUILDING":return{id:"builder-lifecycle-building",label:"Building app",status:n};case"BUILD_FAILED_AGGREGATED":case"REPAIRING":return{id:"builder-lifecycle-repairing",label:"Refining build issues",status:n};case"BUILD_VERIFICATION":return{id:"builder-lifecycle-build-verification",label:"Verifying final updates",status:n};case"READY_FOR_PREVIEW":return{id:"builder-lifecycle-preview",label:e.isFollowUpRequest?"Starting updated live preview":"Starting live preview",status:n};case"PREVIEW_RUNNING":return{id:"builder-lifecycle-preview",label:e.isFollowUpRequest?"Live preview is updated":"Application is running",status:"complete"};case"FAILED":return{id:"builder-lifecycle-failed",label:e.failureLabel,status:"failed"};case"CANCELED":return{id:"builder-lifecycle-canceled",label:"Generation stopped",status:"aborted"};default:return null}};function ZV(t){const e=t.currentPhase==="IDLE"||t.currentPhase==="GENERATING"||t.phaseHistory[t.phaseHistory.length-1]===t.currentPhase?t.phaseHistory:[...t.phaseHistory,t.currentPhase],r=[];if(e.forEach((s,i)=>{const a=QV(s,t,i===e.length-1);if(!a)return;const o=r.findIndex(l=>l.id===a.id);o>=0&&r.splice(o,1),r.push(a)}),t.currentPhase==="FAILED"&&/(?:dependenc\w*|package\w*).*(?:install|download)|(?:install|download).*(?:dependenc\w*|package\w*)/i.test(t.failureLabel)){const s=r.findIndex(a=>a.id==="builder-lifecycle-installing-dependencies"),i=r.findIndex(a=>a.id==="builder-lifecycle-failed");s>=0&&i>=0&&(r[s]={...r[s],label:t.failureLabel,status:"failed"},r.splice(i,1))}return r}const eG=oh({}),tG=/\.(html?|tsx?|jsx|vue|astro|svelte|mdx?)$/i,rG=/\.(css|scss|sass|less)$/i,nG=/\.(mjs|cjs|js|jsx|ts|tsx)$/i,sG=/\.(md|mdx|txt|json|yml|yaml)$/i,iG=/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.ya?ml|yarn\.lock|bun\.lockb?)$/i,oG=["imported-files","starter-template-files"],aG="user updated files",lG=["/components/","/component/","/css/","/styles/","/js/","/scripts/","/assets/"],cG=t=>oG.some(e=>String(t?.id||"").toLowerCase().startsWith(e)),uG=t=>String(t?.title||"").trim().toLowerCase()===aG,wb=t=>!!t&&t.type!=="runtime"&&!cG(t)&&!uG(t),Cf=t=>{const e=Math.floor(t/60),r=t%60;return`${e}:${r.toString().padStart(2,"0")}`},dG=t=>t?"Updating your app":"Working on app",hG=t=>
61{const r=t.replace(/\\/g,"/").split("/").filter(Boolean);let s=(r[r.length-1]??"").replace(/\.[^/.]+$/,"");return s.toLowerCase()==="index"&&r.length>1&&(s=r[r.length-2]??s),s.toLowerCase()==="index"?"Home":s.replace(/[-_]+/g," ").trim().replace(/\b\w/g,i=>i.toUpperCase())},fG=t=>{if(t.type==="file"){const e=t.filePath.replace(/\\/g,"/"),r=e.split("/").pop()||e,n=hG(t.filePath);return tG.test(r)&&!lG.some(i=>e.toLowerCase().includes(i))?`Creating ${n} page`:rG.test(r)?`Updating ${n} styles`:e.toLowerCase().includes("/components/")?`Refining ${n} section`:iG.test(r)?"Updating dependencies":sG.test(r)?"Refreshing website content":nG.test(r)?"Improving site interactions":"Applying website updates"}return t.type==="shell"?String(t.content||"").toLowerCase().includes("install")?"Preparing your website workspace":null:t.type==="start"?"Launching live preview":t.type==="build"?"Finalizing your website":null},Sb=t=>t==="complete"?"text-emerald-500":t==="failed"||t==="aborted"?"text-red-500":t==="running"?"text-blue-500":"text-bolt-elements-textTertiary",Cb=t=>t==="complete"?f.jsx("div",{className:"i-ph:check-circle-fill text-base"}):t==="failed"||t==="aborted"?f.jsx("div",{className:"i-ph:warning-circle-fill text-base"}):t==="running"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg text-base"}):f.jsx("div",{className:"i-ph:circle text-sm"}),zu=(t,e)=>e&&(t==="pending"||t==="running")?"aborted":t,pG=(t,e)=>t==="aborted"&&!e?"Replaced":t,mG=(t,e)=>t==="aborted"&&!e?"pending":t,hI=t=>t.trim().toLowerCase().replace(/\s+/g," "),fI=t=>{const e=hI(t);return e.includes("live preview")||e.includes("application is running")||e.includes("application is ready")||e.includes("starting application")||e.includes("launching live preview")},gG=t=>fI(t)?"preview":hI(t),bG=t=>t==="pending"||t==="running"||t==="complete"||t==="failed"||t==="aborted"?t:"pending",EC=t=>{const e=new Map,r=[];for(const n of t){const s=gG(n.label),i=e.get(s);if(i===void 0){e.set(s,r.length),r.push(n);continue}r[i]=n}return r},pI=x.memo(({isStreaming:t=!1,isFollowUpRequest:e=!1,messageId:r,progressMessage:n,embedded:s=!1})=>{const i=We(j.artifacts),a=We(j.activeProgressMessageId),o=We(j.restoreProgress),{historyRestoring:l,aborted:c}=We(Ve),u=We(j.ignoredProgressMessageIds),d=We(j.previewStarting),h=We(j.previewVisible),m=We(j.previewEverReady),b=We(j.builderLifecyclePhase),g=We(j.builderLifecyclePhaseHistory),p=We(j.actionAlert),y=l_(),v=We(j.frozenProgress),_=x.useMemo(()=>Zl(j.previews,Pe=>Pe.filter(be=>be.ready).length),[]),w=We(_),[C,A]=x.useState(0),[E,S]=x.useState(0),k=w>0,O=b==="PREVIEW_RUNNING",T=xD(b),R=!T&&(O||h||k),N=b==="INSTALLING_DEPENDENCIES"||!!o?.some(Pe=>Pe.id==="install-dependencies"&&Pe.status==="running");x.useEffect(()=>{if(!N){S(0);return}const Pe=Date.now(),be=window.setInterval(()=>{S(Math.floor((Date.now()-Pe)/1e3))},1e3);return()=>window.clearInterval(be)},[N]);const M=x.useMemo(()=>{if(r){const Ne=i[r];return Ne&&!u.has(r)&&wb(Ne)?Ne:void 0}const Pe=Object.entries(i).filter(([Ne])=>!u.has(Ne)).map(([,Ne])=>Ne).filter(Ne=>wb(Ne)),be=a?i[a]:void 0;return!!be&&!u.has(a||"")&&wb(be)?be:Pe.slice(-1)[0]},[a,i,u,r]),B=x.useMemo(()=>Zl(M?.runner.actions??eG,Pe=>Object.values(Pe)),[M]),U=We(B),X=x.useMemo(()=>{const Pe=new Map,be=[];return U.forEach(Te=>{if(Te.type==="start"&&T)return;const Ne=e&&Te.type==="start"&&!T&&(m||R||d),Fe=Te.type==="start"&&O,Fr=Te.type==="shell"&&O&&String(Te.content||"").toLowerCase().includes("install")&&(Te.status==="pending"||Te.status==="running"),Jr=Ne?h?"Live preview is updated":R?"Live preview is ready":"Refreshing live preview":Fe?h?"Live preview is running":"Live preview is ready":fG(Te);if(!Jr)return;const Dt=Ne?h||R?"complete":"running":Fe||Fr?"complete":zu(Te.status,c);Pe.has(Jr)||be.push(Jr),Pe.set(Jr,Dt)}),be.map((Te,Ne)=>({id:`${Te}-${Ne}`,label:Te,status:Pe.get(Te)??"pending"}))}
61,[U,e,m,T,O,R,d,h]),oe=x.useMemo(()=>X.some(Pe=>{const be=Pe.label.toLowerCase();return be.includes("live preview")||be.includes("application is running")||be.includes("application is ready")}),[X]),L=X.length,F=x.useMemo(()=>X.filter(Pe=>Pe.status==="complete").length,[X]),V=x.useMemo(()=>X.length>0&&X.every(Pe=>Pe.status!=="pending"&&Pe.status!=="running"),[X]),Z=g.some(Pe=>Pe!=="IDLE"&&Pe!=="GENERATING"),K=!c&&!l&&b!=="FAILED"&&b!=="CANCELED"&&L>0&&F===L&&!oe&&!Z&&!T&&(!r||a===r||v?.messageId===r),ie=x.useMemo(()=>K?{id:"runtime-preview",label:e?h?"Live preview is updated":R?"Live preview is ready":m||d?"Refreshing live preview":"Starting live preview":h?"Application is running":R?"Application is ready":d?"Starting application":"Installing dependencies and starting application",status:h||R?"complete":"running"}:null,[e,m,R,d,h,K]),se=x.useMemo(()=>ie?[...X,ie]:X,[X,ie]),fe=x.useMemo(()=>!r||v?.messageId!==r?null:v.actions.map((Pe,be)=>({id:Pe.id||`frozen-progress-${be}`,label:Pe.label,status:bG(Pe.status)})),[v,r]),Y=x.useRef(t),I=x.useRef(!1);x.useEffect(()=>{(Y.current&&!t||!t||M?.closed)&&!I.current&&v===null&&r&&V&&se.length>=1&&(I.current=!0,j.frozenProgress.set({messageId:r,actions:EC(se),totalActions:se.length,completedActions:se.filter(Ne=>Ne.status==="complete").length})),Y.current=t,!t&&!M&&v!==null&&!r&&(j.frozenProgress.set(null),I.current=!1)},[t,V,v,se,M,r]);const z=x.useMemo(()=>(fe?ie?[...fe,ie]:fe:se).map(be=>fI(be.label)?O&&h?{...be,label:"Application is running",status:"complete"}:O&&R?{...be,label:"Application is ready",status:"complete"}:T?{...be,label:"Preparing preview environment",status:"running"}:d?{...be,label:"Starting application",status:"running"}:be:be),[fe,T,O,R,d,h,se,ie]),q=x.useMemo(()=>U.some(Pe=>zu(Pe.status,c)==="failed")?"failed":U.some(Pe=>zu(Pe.status,c)==="aborted")?c?"aborted":"pending":U.some(Pe=>zu(Pe.status,c)==="running")?"running":U.length>0&&U.every(Pe=>zu(Pe.status,c)==="complete")?"complete":"pending",[c,U]),ae=!r||a===r||v?.messageId===r,ee=x.useMemo(()=>{if(c||l||!ae)return[];const Pe=y.constrained?"Installing dependencies - slow connection detected":E>=45?"Installing dependencies - still downloading required packages":"Installing dependencies";return ZV({phaseHistory:g,currentPhase:b,isFollowUpRequest:e,currentInstallLabel:Pe,failureLabel:/dependency installation timed out/i.test(p?.title||"")?"Dependency installation could not finish":"Build failed"})},[c,p?.title,b,g,l,E,e,y.constrained,ae]),le=x.useMemo(()=>EC([...z,...ee]),[z,ee]),ve=le.length,ye=!!o&&o.length>0,Ae=!!o?.some(Pe=>Pe.status==="running"||Pe.status==="pending"),we=!r&&ye&&(l||Ae),pe=ve>0&&(!!M||fe!==null),Ye=!c&&!ye&&!pe&&t&&ae,ft=!c&&!ye&&!pe&&!t&&d&&!l&&ae,pt=!c&&!ye&&!pe&&l&&ae,Lt=6e4,[nt,xt]=x.useState(!1),ct=x.useMemo(()=>n||dG(e),[e,n]),_r=s?"w-full":"h-full",ht=s?"":"overflow-auto modern-scrollbar";if(x.useEffect(()=>{if(!Ye&&!ft){A(0),xt(!1);return}const Pe=Date.now();A(0),xt(!1);const be=window.setInterval(()=>{const Te=Math.floor((Date.now()-Pe)/1e3);if(A(Te),ft&&Te*1e3>=Lt&&!nt){if(xt(!0),t||l||T){console.warn("[ProgressPanel] Preview timeout detected, refresh deferred while request is processing",{isStreaming:t,historyRestoring:l,builderLifecyclePhase:b});return}console.warn("[ProgressPanel] Preview timeout detected, triggering refresh"),j.requestPreviewRefresh(),j.refreshAllPreviews()}},1e3);return()=>{window.clearInterval(be)}},[b,l,t,T,nt,ft,Ye]),we)return f.jsxs("div",{className:ue(_r,ht,"p-3"),children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Restored Website Setup"})}),f.jsx("div",{className:"mt-3 space-y-2",children:o.map(Pe=>{const be=Pe.id==="install-dependencies"&&Pe.status==="running";return f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Sb(Pe.status)),children:Cb(Pe.status)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:be&&y.constrained?"Installing dependencies - slow connection detected":Pe.label}),f.jsxs("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:[Pe.status,be?` - ${Cf(E)}`:""]}),be&&f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textTertiary",children:"Your files are saved. Required packages are still downloading before preview can start."})]})]},Pe.id)})})]});if(!M&&!fe||ve===0){if(M&&U.length>0)return f.jsxs("div",{className:ue(_r,ht,"p-3"),children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:ct})}),f.jsx("div",{className:"mt-3 space-y-2",children:f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Sb(q)),children:Cb(q)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:ct}),f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:q})]})]})})]});if(r&&!Ye&&!ft&&!pt&&!c)return null;if(c)return f.jsx("div",{className:ue(_r,"flex items-center justify-center p-4"),children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-red-500
61i-ph:warning-circle-fill"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Generation stopped"})]})});if(pt)return f.jsx("div",{className:ue(_r,"flex items-center justify-center p-4"),children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-blue-500 i-svg-spinners:90-ring-with-bg"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Restoring your app workspace"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:"Reloading files and starting preview for this chat."})]})});if(ft){const Pe=C>45;return f.jsx("div",{className:ue(_r,"flex items-center justify-center p-4"),children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:ue("mx-auto mb-2 h-8 w-8",Pe?"text-yellow-500":"text-blue-500","i-svg-spinners:90-ring-with-bg")}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:Pe?"Preview taking longer than usual...":"Starting app preview"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:Pe?"Still working on it - this can happen with complex apps":"Please wait while the app compiles and the preview becomes available."}),f.jsxs("div",{className:"mt-2 text-[11px] text-bolt-elements-textTertiary",children:["Elapsed time: ",Cf(C),nt&&f.jsx("div",{className:"mt-1 text-green-600",children:"â Auto-recovery triggered"})]})]})})}return Ye?f.jsx("div",{className:ue(_r,"flex items-center justify-center p-4"),children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-blue-500 i-svg-spinners:90-ring-with-bg"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:ct}),f.jsxs("div",{className:"mt-2 text-[11px] text-bolt-elements-textTertiary",children:["Elapsed time: ",Cf(C)]})]})}):f.jsx("div",{className:ue(_r,"flex items-center justify-center p-4"),children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-bolt-elements-textTertiary i-ph:sparkle-duotone"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:ct})]})})}return f.jsxs("div",{className:ue(_r,ht,"p-3"),children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:ct})}),f.jsx("div",{className:"mt-3 space-y-2",children:le.map(Pe=>{const be=pG(Pe.status,c),Te=mG(Pe.status,c);return f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Sb(Te)),children:Cb(Te)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:Pe.label}),f.jsxs("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:[be,Pe.id==="builder-lifecycle-installing-dependencies"?` - ${Cf(E)}`:""]}),Pe.id==="builder-lifecycle-installing-dependencies"&&f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textTertiary",children:"Your files are saved. Required packages are still downloading before preview can start."})]})]},Pe.id)})})]})}),vG=Object.freeze(Object.defineProperty({__proto__:null,ProgressPanel:pI},Symbol.toStringTag,{value:"Module"})),yG=100-Cy,_G={tabSize:2},xG=oh({}),wG=/\.(html?|tsx?|jsx|vue|astro|svelte|mdx?)$/i,SG=/\.(css|scss|sass|less)$/i,CG=/\.(mjs|cjs|js|jsx|ts|tsx)$/i,AG=/\.(md|mdx|txt|json|yml|yaml)$/i,EG=/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.ya?ml|yarn\.lock|bun\.lockb?)$/i,kG=["imported-files","starter-template-files"],PG=["/components/","/component/","/css/","/styles/","/js/","/scripts/","/assets/"],TG=t=>kG.some(e=>String(t?.id||"").toLowerCase().startsWith(e)),kC=t=>!!t&&t.type!=="runtime"&&!TG(t),PC=t=>{const e=Math.floor(t/60),r=t%60;return`${e}:${r.toString().padStart(2,"0")}`},RG=t=>t?"Updating your app":"Working on app",IG=t=>
61{const r=t.replace(/\\/g,"/").split("/").filter(Boolean);let s=(r[r.length-1]??"").replace(/\.[^/.]+$/,"");return s.toLowerCase()==="index"&&r.length>1&&(s=r[r.length-2]??s),s.toLowerCase()==="index"?"Home":s.replace(/[-_]+/g," ").trim().replace(/\b\w/g,i=>i.toUpperCase())},NG=t=>{if(t.type==="file"){const e=t.filePath.replace(/\\/g,"/"),r=e.split("/").pop()||e,n=IG(t.filePath);return wG.test(r)&&!PG.some(i=>e.toLowerCase().includes(i))?`Creating ${n} page`:SG.test(r)?`Updating ${n} styles`:e.toLowerCase().includes("/components/")?`Refining ${n} section`:EG.test(r)?"Updating dependencies":AG.test(r)?"Refreshing website content":CG.test(r)?"Improving site interactions":"Applying website updates"}return t.type==="shell"?String(t.content||"").toLowerCase().includes("install")?"Preparing your website workspace":null:t.type==="start"?"Launching live preview":t.type==="build"?"Finalizing your website":null},Ab=t=>t==="complete"?"text-emerald-500":t==="failed"||t==="aborted"?"text-red-500":t==="running"?"text-blue-500":"text-bolt-elements-textTertiary",Eb=t=>t==="complete"?f.jsx("div",{className:"i-ph:check-circle-fill text-base"}):t==="failed"||t==="aborted"?f.jsx("div",{className:"i-ph:warning-circle-fill text-base"}):t==="running"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg text-base"}):f.jsx("div",{className:"i-ph:circle text-sm"});x.memo(({isStreaming:t=!1,isFollowUpRequest:e=!1})=>{const r=We(j.artifacts),n=We(j.activeProgressMessageId),s=We(j.restoreProgress),{historyRestoring:i}=We(Ve),a=We(j.ignoredProgressMessageIds),o=We(j.previewStarting),l=x.useMemo(()=>Zl(j.previews,k=>k.length),[]),c=We(l),[u,d]=x.useState(0),h=c>0,m=x.useMemo(()=>{const k=Object.entries(r).filter(([R])=>!a.has(R)).map(([,R])=>R).filter(R=>kC(R)),O=n?r[n]:void 0;
61return!!O&&!a.has(n||"")&&kC(O)?O:k.slice(-1)[0]},[n,r,a]),b=x.useMemo(()=>Zl(m?.runner.actions??xG,k=>Object.values(k)),[m]),g=We(b),p=x.useMemo(()=>{const k=new Map,O=[];return g.forEach(T=>{const R=T.type==="start"&&h&&(T.status==="pending"||T.status==="running"||T.status==="aborted"),N=T.type==="shell"&&h&&String(T.content||"").toLowerCase().includes("install")&&(T.status==="pending"||T.status==="running"),M=R?"Live preview is running":NG(T);if(!M)return;const B=R||N?"complete":T.status;k.has(M)||O.push(M),k.set(M,B)}),O.map((T,R)=>({id:`${T}-${R}`,label:T,status:k.get(T)??"pending"}))},[g,h]),y=x.useMemo(()=>g.some(k=>k.status==="failed"||k.status==="aborted")?"failed":g.some(k=>k.status==="running")?"running":g.length>0&&g.every(k=>k.status==="complete")?"complete":"pending",[g]),v=p.length,_=!!s&&s.length>0,w=!!m&&v>0,C=!_&&!w&&t,A=!_&&!w&&!t&&o&&!i,E=!_&&!w&&i,S=x.useMemo(()=>RG(e),[e]);return x.useEffect(()=>{if(!C&&!A){d(0);return}const k=Date.now();d(0);const O=window.setInterval(()=>{d(Math.floor((Date.now()-k)/1e3))},1e3);return()=>{window.clearInterval(O)}},[A,C]),(!m||v===0)&&_?f.jsxs("div",{className:"h-full overflow-auto modern-scrollbar p-3",children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Restored Website Setup"})}),f.jsx("div",{className:"mt-3 space-y-2",children:s.map(k=>f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Ab(k.status)),children:Eb(k.status)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:k.label}),f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:k.status})]})]},k.id))})]}):!m||v===0?m&&g.length>0?f.jsxs("div",{className:"h-full overflow-auto modern-scrollbar p-3",children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:S})}),f.jsx("div",{className:"mt-3 space-y-2",children:f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Ab(y)),children:Eb(y)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:S}),f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:y})]})]})})]}):E?f.jsx("div",{className:"h-full flex items-center justify-center p-4",children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-blue-500 i-svg-spinners:90-ring-with-bg"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Restoring your app workspace"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:"Reloading files and starting preview for this chat."})]})}):A?f.jsx("div",{className:"h-full flex items-center justify-center p-4",children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-blue-500 i-svg-spinners:90-ring-with-bg"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Starting app preview"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:"Please wait while the app compiles and the preview becomes available."}),f.jsxs("div",{className:"mt-2 text-[11px] text-bolt-elements-textTertiary",children:["Elapsed time: ",PC(u)]})]})}):C?f.jsx("div",{className:"h-full flex items-center justify-center p-4",children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-blue-500 i-svg-spinners:90-ring-with-bg"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:S}),f.jsxs("div",{className:"mt-2 text-[11px] text-bolt-elements-textTertiary",children:["Elapsed time: ",PC(u)]})]})}):f.jsx("div",{className:"h-full flex items-center justify-center p-4",children:f.jsxs("div",{className:"max-w-xs rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 text-center",children:[f.jsx("div",{className:"mx-auto mb-2 h-8 w-8 text-bolt-elements-textTertiary i-ph:sparkle-duotone"}),f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:S})]})}):f.jsxs("div",{className:"h-full overflow-auto modern-scrollbar p-3",children:[f.jsx("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:S})}),f.jsx("div",{className:"mt-3 space-y-2",children:p.map(k=>f.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-2.5",children:[f.jsx("div",{className:ue("mt-0.5",Ab(k.status)),children:Eb(k.status)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textPrimary truncate",children:k.label}),f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary capitalize",children:k.status})]})]},k.id))})]})});const LG=x.memo(({files:t,unsavedFiles:e,editorDocument:r,selectedFile:n,isStreaming:s,isFollowUpRequest:i=!1,progressMessage:a,buildJob:o,advancedMode:l=!1,fileHistory:c,onFileSelect:u,onEditorChange:d,onEditorScroll:h,onFileSave:m,onFileReset:b,onToggleAdvancedMode:g})=>{gu.trace("EditorPanel");const p=We(Ed),y=We(j.showTerminal),[v,_]=x.useState("progress"),w=x.useRef(l),C=o?.requestMode==="update"||!o&&i;x.useEffect(()=>{!l&&v!=="progress"&&_("progress")},[v,l]),x.useEffect(()=>{l&&!w.current&&v==="progress"&&_("files"),w.current=l},[v,l]);const A=O=>{O!=="progress"&&O!=="files"&&O!=="search"&&O!=="locks"||!l&&O!=="progress"||_(O)},E=x.useMemo(()=>
61{if(r)return r.filePath.split("/")},[r]),S=x.useMemo(()=>!r||!e?!1:e instanceof Set&&e.has(r.filePath),[r,e]),k=x.useMemo(()=>Object.values(t||{}).some(O=>O?.type==="file"&&!O.isBinary),[t]);return f.jsxs(wy,{direction:"vertical",children:[f.jsx(vd,{defaultSize:y?yG:100,minSize:20,children:f.jsxs(wy,{direction:"horizontal",children:[f.jsx(vd,{defaultSize:20,minSize:15,collapsible:!0,className:"border-r border-bolt-elements-borderColor",children:f.jsx("div",{className:"h-full",children:f.jsxs(x2,{value:v,onValueChange:A,className:"flex flex-col h-full",children:[f.jsx(xC,{className:"w-full text-sm font-medium text-bolt-elements-textSecondary px-1",children:f.jsxs("div",{className:"flex h-full w-full min-w-0 items-center justify-between gap-1",children:[l?f.jsxs(w2,{className:"flex h-full min-w-0 items-center overflow-x-auto modern-scrollbar",children:[f.jsx(Wh,{value:"progress",className:ue("h-full bg-transparent hover:bg-bolt-elements-background-depth-3 py-0.5 px-2 rounded-lg text-sm font-medium text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary data-[state=active]:text-bolt-elements-textPrimary"),children:"Progress"}),f.jsx(Wh,{value:"files",className:ue("h-full bg-transparent hover:bg-bolt-elements-background-depth-3 py-0.5 px-2 rounded-lg text-sm font-medium text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary data-[state=active]:text-bolt-elements-textPrimary"),children:"Files"}),f.jsx(Wh,{value:"search",className:ue("h-full bg-transparent hover:bg-bolt-elements-background-depth-3 py-0.5 px-2 rounded-lg text-sm font-medium text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary data-[state=active]:text-bolt-elements-textPrimary"),children:"Search"}),f.jsx(Wh,{value:"locks",className:ue("h-full bg-transparent hover:bg-bolt-elements-background-depth-3 py-0.5 px-2 rounded-lg text-sm font-medium text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary data-[state=active]:text-bolt-elements-textPrimary"),children:"Locks"})]}):f.jsx("div",{className:"px-2 text-sm font-medium text-bolt-elements-textPrimary",children:"Progress"}),f.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[l&&v==="files"&&f.jsx(Mn,{className:"h-8 w-8 justify-center",disabled:!k,title:"Download project as zip",onClick:()=>{j.downloadZip()},children:f.jsx("div",{className:"i-ph:download-simple-duotone"})}),f.jsx(Mn,{className:l?"h-8 w-8 justify-center":"text-sm",title:l?"Switch to simple mode":"Switch to advanced mode",onClick:g,children:l?f.jsx("div",{className:"i-ph:eye-slash-duotone"}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"i-ph:sliders-horizontal-duotone"}),"Advanced"]})})]})]})}),f.jsx(Hh,{value:"progress",className:"flex-grow overflow-auto focus-visible:outline-none",children:f.jsx(pI,{isStreaming:s,isFollowUpRequest:C,progressMessage:a})}),f.jsx(Hh,{value:"files",className:"flex-grow overflow-auto focus-visible:outline-none",children:f.jsx("div",{className:"flex h-full flex-col",children:f.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:f.jsx(iI,{className:"h-full",files:t,hideRoot:!0,unsavedFiles:e,fileHistory:c,rootFolder:Za,selectedFile:n,onFileSelect:u})})})}),f.jsx(Hh,{value:"search",className:"flex-grow overflow-auto focus-visible:outline-none",children:f.jsx(XV,{})}),f.jsx(Hh,{value:"locks",className:"flex-grow overflow-auto focus-visible:outline-none",children:f.jsx(JV,{})})]})})}),f.jsx(Sy,{}),f.jsxs(vd,{className:"flex flex-col",defaultSize:80,minSize:20,children:[f.jsx(xC,{className:"overflow-x-auto",children:E?.length&&f.jsxs("div",{className:"flex items-center flex-1 text-sm",children:[f.jsx(WV,{pathSegments:E,files:t,onFileSelect:u}),S&&f.jsxs("div",{className:"flex gap-1 ml-auto -mr-1.5",children:[f.jsxs(Mn,{onClick:m,children:[f.jsx("div",{className:"i-ph:floppy-disk-duotone"}),"Save"]}),f.jsxs(Mn,{onClick:b,children:[f.jsx("div",{className:"i-ph:clock-counter-clockwise-duotone"}),"Reset"]})]})]})}),f.jsx("div",{className:"h-full flex-1 overflow-hidden modern-scrollbar",children:f.jsx(RR,{theme:p,editable:!s&&r!==void 0,settings:_G,doc:r,autoF
61ocusOnDocumentChange:!nV(),onScroll:h,onChange:d,onSave:m})})]})]})}),f.jsx(Sy,{}),f.jsx(qV,{})]})}),DG=5e3,MG=7e3,mI={"ai-app-builder":"https://cloudmysite.ai/app",forms:"https://cloudmysite.com/form",domains:"https://cloudmysite.com/domain-purchase","site-transfer":"https://cloudmysite.com/migration-services","image-logo-generation":"https://cloudmysite.com/genie-logo","vps-hosting":"https://cloudmysite.com/vps-hosting",byow:"https://cloudmysite.com/byow","web-builder":"https://cloudmysite.com/website-builder","build-websites":"https://cloudmysite.com/web-pages","wordpress-hosting":"https://cloudmysite.com/wordpress-hosting","joomla-hosting":"https://cloudmysite.com/joomla"},sd=[{id:"ai-app-builder",title:"AI App Builder",description:"Turn a simple prompt into a polished app with the essentials already connected.",highlights:["Build complete apps from simple prompts","Accounts, forms, and saved data ready to grow","Keep improving with follow-up prompts"],icon:"i-ph:app-window-duotone",accentClassName:"from-sky-500/20 via-cyan-500/12 to-transparent text-sky-300",ctaLabel:"See app plans"},{id:"forms",title:"Forms",description:"Launch forms fast and keep every submission organized without extra setup.",highlights:["Create forms and collect submissions","Email notifications and integrations","Spam protection and analytics"],icon:"i-ph:rows-duotone",accentClassName:"from-emerald-500/20 via-teal-500/12 to-transparent text-emerald-300",ctaLabel:"Explore forms"},{id:"domains",title:"Domains",description:"Find the right name and connect it to your product in a few simple steps.",highlights:["Search and purchase domains instantly","Easy DNS management","Connect domains to apps and websites"],icon:"i-ph:globe-hemisphere-west-duotone",accentClassName:"from-violet-500/20 via-fuchsia-500/12 to-transparent text-violet-300",ctaLabel:"Browse domains"},{id:"site-transfer",title:"Site Transfer",description:"Move an existing site over smoothly while keeping the experience steady for visitors.",highlights:["Move existing websites easily","No downtime migration","Works with WordPress, static, and custom apps"],icon:"i-ph:arrows-left-right-duotone",accentClassName:"from-amber-500/20 via-orange-500/12 to-transparent text-amber-300",ctaLabel:"Transfer a site"},{id:"image-logo-generation",title:"Image and Logo Generation",description:"Create fresh visual assets in minutes when your app needs branding or marketing art.",highlights:["Generate logos and images using AI","Download and use instantly","Great for branding your app or site"],icon:"i-ph:image-square-duotone",accentClassName:"from-pink-500/20 via-rose-500/12 to-transparent text-pink-300",ctaLabel:"Create visuals"},{id:"vps-hosting",title:"VPS Hosting",description:"Run demanding workloads on hosting built for speed, control, and room to grow.",highlights:["High-performance cloud hosting","Full control environments","Scalable and secure infrastru
61cture"],icon:"i-ph:cloud-duotone",accentClassName:"from-cyan-500/20 via-blue-500/12 to-transparent text-cyan-300",ctaLabel:"View hosting"},{id:"byow",title:"BYOW",description:"Bring your own site and get it live quickly without rebuilding from scratch.",highlights:["Upload your own website or app","Host instantly on CloudMySite","Map custom domains easily"],icon:"i-ph:upload-simple-duotone",accentClassName:"from-indigo-500/20 via-sky-500/12 to-transparent text-indigo-300",ctaLabel:"Bring your site"},{id:"web-builder",title:"Web Builder",description:"Design pages visually when you want speed and control without touching code.",highlights:["Drag-and-drop website builder","Visual editing with no code","Publish instantly"],icon:"i-ph:layout-duotone",accentClassName:"from-lime-500/20 via-emerald-500/12 to-transparent text-lime-300",ctaLabel:"Open builder"},{id:"build-websites",title:"Build Websites",description:"Generate a polished website with AI, then refine the details through simple prompts.",highlights:["Generate full websites using AI","Landing pages, business sites, and portfolios","Customize with follow-up prompts"],icon:"i-ph:magic-wand-duotone",accentClassName:"from-blue-500/20 via-indigo-500/12 to-transparent text-blue-300",ctaLabel:"Generate a site"},{id:"wordpress-hosting",title:"WordPress Hosting",description:"Get WordPress online fast with hosting tuned for reliability and day-to-day ease.",highlights:["One-click WordPress setup","Managed hosting","Optimized performance"],icon:"i-ph:article-ny-times-duotone",accentClassName:"from-slate-500/20 via-zinc-500/12 to-transparent text-slate-300",ctaLabel:"Host WordPress"},{id:"joomla-hosting",title:"Joomla Hosting",description:"Launch Joomla with less overhead and keep the environment stable as your site grows.",highlights:["Easy Joomla deployment","Managed environment","Secure and scalable"],icon:"i-ph:stack-duotone",accentClassName:"from-orange-500/20 via-amber-500/12 to-transparent text-orange-300",ctaLabel:"Host Joomla"}];function TC(t){const e=sd.length;return e===0?0:(t+e)%e}const OG=x.memo(({product:t,variant:e,onExploreMore:r})=>{const n=e==="workspace";return f.jsxs(ar.div,{initial:{opacity:0,x:18},animate:{opacity:1,x:0},exit:{opacity:0,x:-18},transition:{duration:.35,ease:Ds},className:"flex h-full min-h-0 flex-col",children:[f.jsx("div",{className:ue("mb-4 inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br",n?"border border-sky-200/80 from-white via-sky-50 to-sky-100 shadow-sm dark:border-slate-700 dark:from-slate-800 dark:via-slate-800 dark:to-slate-700":"border border-white/10",t.accentClassName),children:f.jsx("div",{className:ue(t.icon,"text-[22px]")})}),f.jsx("div",{className:ue("text-xl font-semibold tracking-tight",n?"text-slate-950 dark:text-white":"text-white"),children:t.title}),f.jsx("p",{className:ue("mt-2 text-sm leading-6",n?"text-slate-700 dark:text-slate-300":"text-slate-300"),children:t.description}),f.jsx("ul",{className:"mt-5 flex-1 space-y-2.5 overflow-y-auto pr-1",children:t.highlights.map(s=>f.jsxs("li",{className:ue("flex items-start gap-2.5 text-sm",n?"text-slate-800 dark:text-slate-200":"text-slate-200"),children:[f.jsx("span",{className:ue("mt-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full",n?"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300":"bg-white/8 text-emerald-300"),children:f.jsx("span",{className:"i-ph:check-bold text-[11px]"})}),f.jsx("span",{className:"leading-5",children:s})]},s))}),f.jsx("div",{className:"mt-6 flex items-center gap-3",children:t.ctaLabel&&f.jsxs("a",{href:mI[t.id]||"#",target:"_blank",rel:"noopener noreferrer",className:ue("inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition",n?"bg-slate-900 text-white hover:bg-slate-800 dark:bg-accent-600 dark:hover:bg-accent-700":"bg-white text-slate-950 hover:bg-slate-100"),children:[t.ctaLabel,f.jsx("span",{className:"i-ph:arrow-up-right text-sm"})]})})]},t.id)}),jG=x.memo(({className:t,isMobile:e=!1,variant:r="sidebar",onExploreMore:n})=>{const[s,i]=x.useState(0),[a,o]=x.useState(!1),[l,c]=x.useState(!1),[u,d]=x.useState(r==="workspace"),h=x.useRef(null),m=sd[s],b=r==="workspace",g=e&&b,p=a||l,y=x.useCallback(()=>{h.current&&(window.clearTimeout(h.current),h.current=null)},[]),v=x.useCallback(()=>{y(),c(!0),h.current=window.setTimeout(()=>{c(!1),h.current=null},MG)},[y]);x.useEffect(()=>{if(p||sd.length<=1)return;const k=window.setTimeout(()=>{i(O=>TC(O+1))},DG);return()=>{window.clearTimeout(k)}},[s,p]),x.useEffect(()=>()=>{y()},[y]);const _=x.useCallback(k=>{i(TC(k)),v()},[v]),w=x.useCallback(()=>{_(s-1)},[s,_]),C=x.useCallback(()=>{_(s+1)},[s,_]),A=x.useMemo(()=>f.jsxs("div",{className:ue("mt-6 flex flex-wrap items-center justify-between gap-3 pt-4",b?"border-t border-sky-200/80 dark:border-slate-700":"border-t border-white/10"),children:[f.jsx("a",{href:mI[m.id]||"#",target:"_blank",rel:"noopener noreferrer",className:ue("text-sm font-medium transition",b?"text-slate-700 hover:text-slate-950 dar
61k:text-slate-300 dark:hover:text-white":"text-slate-200 hover:text-white"),children:"Explore more on CloudMySite"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{type:"button",onClick:w,className:ue("inline-flex h-9 w-9 items-center justify-center rounded-full border transition",b?"border-sky-200/80 bg-white/75 text-slate-700 hover:bg-white hover:text-slate-950 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700 dark:hover:text-white":"border-white/10 bg-white/5 text-slate-200 hover:bg-white/10 hover:text-white"),"aria-label":"Show previous CloudMySite option",children:f.jsx("span",{className:"i-ph:caret-left text-base"})}),f.jsx("button",{type:"button",onClick:C,className:ue("inline-flex h-9 w-9 items-center justify-center rounded-full border transition",b?"border-sky-200/80 bg-white/75 text-slate-700 hover:bg-white hover:text-slate-950 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700 dark:hover:text-white":"border-white/10 bg-white/5 text-slate-200 hover:bg-white/10 hover:text-white"),"aria-label":"Show next CloudMySite option",children:f.jsx("span",{className:"i-ph:caret-right text-base"})})]})]}),[m.id,C,w,b,n]),E=f.jsx("div",{className:"mt-5 flex items-center gap-2",children:sd.map((k,O)=>{const T=O===s;return f.jsx("button",{type:"button",onClick:()=>_(O),"aria-label":`Show ${k.title}`,className:ue("h-2.5 rounded-full transition-all duration-300",T?ue("w-8",b?"bg-slate-900 dark:bg-white":"bg-white"):ue("w-2.5",b?"bg-slate-300 hover:bg-slate-400 dark:bg-slate-600 dark:hover:bg-slate-500":"bg-white/25 hover:bg-white/50"))},k.id)})}),S=f.jsxs("div",{className:ue("flex h-full min-h-0 flex-col overflow-hidden rounded-[28px] p-4 sm:p-5",b?"border border-sky-200/80 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(239,246,255,0.94))] shadow-[0_24px_72px_rgba(148,163,184,0.18)] dark:border-slate-800 dark:bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] dark:shadow-[0_24px_72px_rgba(2,6,23,0.55)]":"border border-white/10 bg-slate-950/88 shadow-[0_24px_80px_rgba(15,23,42,0.28)] backdrop-blur",t),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[f.jsxs("div",{className:"mb-4 flex flex-wrap items-start justify-between gap-3 sm:gap-4",children:[f.jsxs("div",{children:[f.jsx("div",{className:ue("text-xs font-semibold uppercase tracking-[0.24em]",b?"text-sky-700 dark:text-sky-300":"text-cyan-200/70"),children:"CloudMySite"}),f.jsx("div",{className:ue("mt-2 text-xl font-semibold tracking-tight sm:text-2xl",b?"text-slate-950 dark:text-white":"text-white"),children:"While we build your app..."}),f.jsx("p",{className:ue("mt-2 max-w-xl text-sm leading-6",b?"text-slate-700 dark:text-slate-300":"text-slate-300"),children:"Explore what else you can launch on CloudMySite while your workspace finishes setting up."})]}),f.jsxs("div",{className:ue("rounded-full px-2.5 py-1 text-xs",b?"border border-sky-200/80 bg-white/80 text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300":"border border-white/10 bg-white/5 text-slate-300"),children:[s+1,"/",sd.length]})]}),f.jsxs("div",{className:ue("relative min-h-[280px] flex-1 overflow-hidden rounded-[24px] p-4 sm:min-h-[332px] sm:p-5",b?"border border-sky-200/80 bg-[linear-gradient(180deg,rgba(255,255,255,0.82),rgba(239,246,255,0.88))] dark:border-slate-700 dark:bg-[linear-gradient(180deg,rgba(15,23,42,0.82),rgba(2,6,23,0.88))]":"border border-white/8 bg-gradient-to-br from-slate-900 via-slate-950 to-slate-900"),children:[f.jsx("div",{className:ue("pointer-events-none absolute inset-0",b?"bg-[radial-gradient(circle_at_top_right,rgba(56,189,248,0.12),transparent_36%),radial-gradient(circle_at_bottom_left,rgba(59,130,246,0.10),transparent_38%)] dark:bg-[radial-gradient(circle_at_top_right,rgba(59,130,246,0.16),transparent_34%),radial-gradient(circle_at_bottom_left,rgba(14,165,233,0.10),transparent_38%)]":"bg-[radial-gradient(circle_at_top_right,rgba(56,189,248,0.14),transparent_38%),radial-gradient(circle_at_bottom_left,rgba(99,102,241,0.16),transparent_42%)]")}),f.jsxs("div",{className:"relative z-[1] flex h-full min-h-0 flex-col",children:[f.jsx(Si,{mode:"wait",children:f.jsx(OG,{product:m,variant:r,onExploreMore:n},m.id)}),E]})]}),A]});return e?f.jsx("div",{className:ue(g?"pointer-events-none absolute inset-0 z-[6] flex items-stretch justify-center p-2 sm:p-3":"pointer-events-none absolute inset-x-0 bottom-0 z-[6] flex max-h-full items-end justify-center p-3 sm:p-4",t),children:f.jsxs("div",{className:ue("pointer-events-auto w-full",g?"h-full max-w-none":"max-w-[26rem]"),children:[f.jsx(Si,{initial:!1,children:u?f.jsxs(ar.div,{initial:{opacity:0,y:18,scale:.98}
61,animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:18,scale:.98},transition:{duration:.24,ease:Ds},className:ue("w-full",g?"flex h-full min-h-0 flex-col":"mb-3 h-[min(76vh,42rem)]"),children:[f.jsx("div",{className:ue("flex justify-end",g?"mb-2 shrink-0":"mb-2"),children:f.jsxs("button",{type:"button",onClick:()=>d(!1),className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-slate-900/90 px-3 py-1.5 text-xs font-medium text-slate-100 shadow-lg backdrop-blur",children:[f.jsx("span",{className:"i-ph:x"}),"Close"]})}),f.jsx("div",{className:ue(g?"min-h-0 flex-1":void 0),children:S})]},"marketing-panel-mobile"):null}),f.jsxs("button",{type:"button",onClick:()=>d(k=>!k),className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-slate-950/90 px-4 py-2.5 text-sm font-medium text-white shadow-lg backdrop-blur transition hover:bg-slate-900",children:[f.jsx("span",{className:"i-ph:sparkle-duotone text-base text-cyan-300"}),"While we build your app...",f.jsx("span",{className:ue(u?"i-ph:caret-down":"i-ph:caret-up")})]})]})}):r==="workspace"?f.jsx("div",{className:ue("flex h-full w-full items-stretch p-4 lg:p-6",t),children:f.jsx("div",{className:"h-full w-full",children:S})}):f.jsx("aside",{className:"flex h-full w-[320px] shrink-0 border-l border-bolt-elements-borderColor bg-transparent p-4 xl:w-[360px]",children:S})});o_.configure(a_);const gI=u_();async function Loe(t){try{return c_(t),(await gI.graphql({query:pO,variables:{input:t}})).data.createGenieWebsitePayment.responseMessage}catch(e){throw console.error("Error in payment utils:",e),e}}async function $G(t){try{return(await gI.graphql({query:GM,variables:{id:t}})).data.getPaymentDetailsByIdGenieWebsite.responseMessage}catch(e){throw console.log("error in fetching payment details in utils file:",e),e}}o_.configure(a_);const bI=u_();async function Doe(t){try{return c_(t),(await bI.graphql({query:mO,variables:{input:t}})).data.createOrderGenie.responseMessage}catch(e){throw console.error("Error in payment utils:",e),e}}async function BG({id:t,product_type:e,paypalToken:r}){try{return c_({product_type:e}),(await bI.graphql({query:qM,variables:{id:t,product_type:e,paypalToken:r}})).data.captureOrderGenie.responseMessage}catch(n){throw console.log("error in fetching payment details in utils file:",n),n}}const RC=x.memo(({className:t})=>{const e=We(Ed),[r,n]=x.useState(!1);return x.useEffect(()=>{n(!0)},[]),r&&f.jsx(tu,{className:t,icon:e==="dark"?"i-ph-sun-dim-duotone":"i-ph-moon-stars-duotone",size:"xl",title:"Toggle Theme",onClick:S2})});o_.configure(a_);const FG=u_();async function WG(t){try{return(await FG.graphql({query:KM,variables:{email:t}})).data.getDomainDetailsByEmail}catch(e){throw console.error(e),e}}const kb="app.config.json",HG="public/app.config.json",UG={enabled:!1,requireLogin:!1,allowSignup:!0,allowAnonymousLogin:!1,emailPasswordEnabled:!0,enableGoogleLogin:!1,googleOAuthMode:"managed",googleClientId:"",googleClientSecretSet:!1,redirectUri:"",allowedDomains:[],protectedPaths:[],sessionDurationDays:14},vI=48,Gd=3,zG=new RegExp(`_(\\d{${Gd}})$`);function kn(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").slice(0,vI)}function VG(){if(typeof globalThis<"u"&&"crypto"in globalThis&&globalThis.crypto?.getRandomValues){const t=new Uint16Array(1);return globalThis.crypto.getRandomValues(t),String(t[0]%1e3).padStart(Gd,"0")}return String(Math.floor(Math.random()*1e3)).padStart(Gd,"0")}function h0(t,e){const r=kn(t)||"my_app",n=String(e??VG()).replace(/\D/g,"").slice(-Gd).padStart(Gd,"0"),s=vI-n.length-1;return`${r.slice(0,Math.max(1,s)).replace(/^_+|_+$/g,"")||"app"}_${n}`}function yI(t){return kn(t).match(zG)?.[1]}function _I(t){const e=kn(t.artifactId),r=kn(t.appSlug),n=kn(t.fallback)||"my_app";if(!e)return r||n;const s=yI(r);return s?h0(e,s):e||r||n}function Pb(t){const e=kn(t.artifactId),r=_I(t);return!e||yI(r)?r:h0(e)}function GG(t){return Array.isArray(t)?Array.from(new Set(t.map(e=>String(e||"").trim()).filter(e=>e.startsWith("/")&&!e.startsWith("//")).map(e=>e.length>1&&e.endsWith("/")?e.slice(0,-1):e))):[]}function qG(t){const e=Array.isArray(t)?t:typeof t=="string"?t.split(/[\n,]/):[];return Array.from(new Set(e.map(r=>String(r||"").trim().toLowerCase().replace(/^@+/,"")).filter(r=>/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(r))))}function Ay(t,e){return{app:{name:t||"My App",slug:kn(e||t||"my_app")||"my_app"},auth:{...UG}}}function IC(t,e,r){const n=Ay(e,r);if(!t||!t.trim())return n;try{const s=JSON.parse(t);return{app:{name:typeof s?.app?.name=="string"&&s.app.name.trim()?s.app.name.trim():n.app.name,slug:kn(s?.app?.slug||s?.app?.name||n.app.slug||r||e)||n.app.slug},auth:{enabled:s?.auth?.enabled===!0,requireLogin:s?.auth?.requireLogin===!0,allowSignup:s?.auth?.allowSignup!==!1,allowAnonymousLogin:s?.auth?.allowAnonymousLogin===!0,emailPasswordEnabled:s?.auth?.emailPasswordEnabled!==!1,enableGoogleLogin:s?.auth?.enableGoogleLogin===!0,googleOAuthMode:s?.auth?.googleOAuthMode==="custom"?"custom"
61:"managed",googleClientId:typeof s?.auth?.googleClientId=="string"?s.auth.googleClientId.trim():"",googleClientSecretSet:s?.auth?.googleClientSecretSet===!0,redirectUri:typeof s?.auth?.redirectUri=="string"?s.auth.redirectUri.trim():"",allowedDomains:qG(s?.auth?.allowedDomains),protectedPaths:GG(s?.auth?.protectedPaths),sessionDurationDays:typeof s?.auth?.sessionDurationDays=="number"&&Number.isFinite(s.auth.sessionDurationDays)?Math.min(Math.max(s.auth.sessionDurationDays,1),90):n.auth.sessionDurationDays}}}catch{return n}}function Kf(t){return`${JSON.stringify(t,null,2)} 62`}const KG=120;function YG(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function XG(t,e="Untitled App"){return String(t??"").replace(/\s+/g," ").trim().slice(0,KG).trim()||e}function JG(t,e){const n=`<title>${YG(XG(e))}</title>`;return/<title\b[^>]*>[\s\S]*?<\/title>/i.test(t)?t.replace(/<title\b[^>]*>[\s\S]*?<\/title>/i,n):/<head\b[^>]*>/i.test(t)?t.replace(/<head\b[^>]*>/i,s=>`${s} 63 ${n}`):`${n} 64${t}`}const id="https://auth.cloudmysite.app",f0="CLOUDMYSITE_AUTH",QG="cloudmysite-auth-worker",ZG=`function buildGoogleLoginUrl(returnTo?: string) { 65 const url = new URL('/api/auth/google/start', window.location.origin) 66 67 if (returnTo) { 68 url.searchParams.set('returnTo', returnTo) 69 } 70 71 return url.toString() 72}`,eq=ZG,tq=`const CLOUDMYSITE_AUTH_BASE_URL_ENV_NAME = 'CLOUDMYSITE_AUTH_BASE_URL' 73const CLOUDMYSITE_APP_ID_ENV_NAME = 'APP_ID' 74const CLOUDMYSITE_AUTH_SERVICE_BINDING_NAME = '${f0}' 75const DEFAULT_CLOUDMYSITE_AUTH_BASE_URL = '${id}' 76 77function usesManagedGoogleOAuth(authConfig) { 78 return String(authConfig?.auth?.googleOAuthMode || 'managed').trim().toLowerCase() !== 'custom' 79} 80 81function getCloudMySiteAuthBaseUrl(env) { 82 const rawValue = 83 typeof env?.[CLOUDMYSITE_AUTH_BASE_URL_ENV_NAME] === 'string' && env[CLOUDMYSITE_AUTH_BASE_URL_ENV_NAME].trim() 84 ? env[CLOUDMYSITE_AUTH_BASE_URL_ENV_NAME].trim() 85 : DEFAULT_CLOUDMYSITE_AUTH_BASE_URL 86 87 try { 88 return new URL(rawValue).origin 89 } catch { 90 return DEFAULT_CLOUDMYSITE_AUTH_BASE_URL 91 } 92} 93 94function getCloudMySiteAppId(env) { 95 return typeof env?.[CLOUDMYSITE_APP_ID_ENV_NAME] === 'string' ? env[CLOUDMYSITE_APP_ID_ENV_NAME].trim() : '' 96} 97 98function getCloudMySiteAuthService(env) { 99 const binding = env?.[CLOUDMYSITE_AUTH_SERVICE_BINDING_NAME] 100 return binding && typeof binding.fetch === 'function' ? binding : null 101} 102 103async function fetchCloudMySiteAuth(env, pathname, init = {}) { 104 const url = new URL(pathname, getCloudMySiteAuthBaseUrl(env)) 105 const service = getCloudMySiteAuthService(env) 106 107 if (service) { 108 return service.fetch(new Request(url.toString(), init)) 109 } 110 111 return fetch(url.toString(), init) 112} 113 114function hasCloudMySiteManagedGoogleConfig(env, authConfig) { 115 return !!getCloudMySiteAppId(env) && !!getCloudMySiteAuthBaseUrl(env) && usesManagedGoogleOAuth(authConfig) 116} 117`,xI=`async function readCloudMySiteExchangeError(response) { 118 try { 119 const contentType = response.headers.get('content-type') || '' 120 121 if (contentType.includes('application/json')) { 122 const payload = await response.json() 123 return payload?.error || \`CloudMySite auth exchange failed with HTTP \${response.status}.\` 124 } 125 126 const text = await response.text() 127 128 if (/\\berror\\s+code:\\s*1014\\b/i.test(text) || /\\b1014\\b/.test(text)) { 129 return 'CloudMySite auth exchange failed before reaching the auth broker (Cloudflare error 1014).' 130 } 131 132 return text || \`CloudMySite auth exchange failed with HTTP \${response.status}.\` 133 } catch { 134 return \`CloudMySite auth exchange failed with HTTP \${response.status}.\` 135 } 136}`,wI=`async function exchangeCloudMySiteLoginCode(env, code) { 137 const appId = getCloudMySiteAppId(env) 138 139 if (!appId) { 140 throw new Error('App ID is not configured for managed Google login.') 141 } 142 143 const response = await fetchCloudMySiteAuth(env, '/api/oauth/exchange', { 144 method: 'POST', 145 headers: { 146 'Content-Type': 'application/json', 147 }, 148 body: JSON.stringify({ 149 app_id: appId, 150 code, 151 }), 152 }) 153 154 if (!response.ok) { 155 const error = new Error(await readCloudMySiteExchangeError(response)) 156 error.status = response.status === 401 ? 401 : 400 157 throw error 158 } 159 160 const payload = await response.json() 161 const user = payload?.user || {} 162 163 return { 164 email: normalizeEmail(user.email), 165 providerUserId: typeof user.provider_user_id === 'string' ? user.provider_user_id.trim() : '', 166 name: typeof user.name === 'string' ? user.name.trim() : '', 167 picture: typeof user.picture === 'string' ? user.picture.trim() : '', 168 } 169}`,rq=`${xI} 170 171${wI} 172 173async function upsertCloudMySiteManagedGoogleUser(db, authConfig, identity) { 174 if (!identity.providerUserId || !isValidEmail(identity.email)) { 175 return { user: null, profile: null } 176 } 177 178 const profileData = {} 179 180 if (identity.name) { 181 profileData.full_name = identity.name 182 } 183 184 if (identity.picture) { 185 profileData.picture = identity.picture 186 profileData.avatar_url = identity.picture 187 } 188 189 const profileFieldNames = Object.keys(profileData) 190 const { usersTable, userProfilesTable } = await ensureAuthSchema(db, authConfig.app.slug, profileFieldNames) 191 let user = await readUserByProvider(db, usersTable, 'google', identity.providerUserId) 192 193 if (!user) { 194 user = await readUserByEmail(db, usersTable, identity.email) 195 196 if (user) { 197 await db 198 .prepare( 199 \`UPDATE \${quoteIdentifier(usersTable)} SET \${quoteIdentifier('provider_id')} = ?, \${quoteIdentifier('provider')} = CASE WHEN \${quoteIdentifier('provider')} = 'anonymous' THEN 'google' ELSE \${quoteIdentifier('provider')} END WHERE rowid = ?\`, 200 ) 201 .bind(identity.providerUserId, user.id) 202 .run() 203 204 user = await readUserByEmail(db, usersTable, identity.email) 205 } 206 } 207 208 if (!user) { 209 const insertResult = await db 210 .prepare( 211 \`INSERT INTO \${quoteIdentifier(usersTable)} (\${quoteIdentifier('email')}, \${quoteIdentifier('provider')}, \${quoteIdentifier('provider_id')}) VALUES (?, ?, ?)\`, 212 ) 213 .bind(identity.email, 'google', identity.providerUserId) 214 .run() 215 216 user = await readUserById(db, usersTable, insertResult?.meta?.last_row_i
216d) 217 } 218 219 const profile = 220 user && profileFieldNames.length > 0 221 ? await upsertUserProfile(db, userProfilesTable, user.id, profileData) 222 : null 223 224 return { user, profile } 225} 226 227async function completeCloudMySiteManagedGoogleLogin(request, env, options = {}) { 228 const authConfig = await getResolvedAuthConfig(request, env) 229 const code = String(options.code || '').trim() 230 const returnTo = sanitizeReturnTo(options.returnTo || '/') 231 232 if (!usesManagedGoogleOAuth(authConfig)) { 233 return { error: 'Managed Google login is not enabled for this app.', status: 400, returnTo } 234 } 235 236 if (!authConfig.auth.enabled || !authConfig.auth.enableGoogleLogin) { 237 return { error: 'Google login is disabled for this app.', status: 403, returnTo } 238 } 239 240 if (!env.DB) { 241 return { error: 'Google login is unavailable right now.', status: 503, returnTo } 242 } 243 244 if (!code) { 245 return { error: 'Missing CloudMySite login code.', status: 400, returnTo } 246 } 247 248 try { 249 await ensureAuthRuntime(env.DB, authConfig.app.slug, env) 250 const identity = await exchangeCloudMySiteLoginCode(env, code) 251 const { user, profile } = await upsertCloudMySiteManagedGoogleUser(env.DB, authConfig, identity) 252 253 if (!user) { 254 return { error: 'google_profile_missing_email', status: 400, returnTo } 255 } 256 257 return { authConfig, user, profile, returnTo } 258 } catch (error) { 259 return { 260 error: error instanceof Error ? error.message : 'google_login_failed', 261 status: Number.isFinite(Number(error?.status)) ? Number(error.status) : 400, 262 returnTo, 263 } 264 } 265} 266 267function buildCloudMySiteCompletePage(request) { 268 const loginUrl = new URL('/login', request.url).toString() 269 270 return new Response( 271 \`<!doctype html> 272<html lang="en"> 273 <head> 274 <meta charset="utf-8" /> 275 <meta name="viewport" content="width=device-width, initial-scale=1" /> 276 <title>Signing you in</title> 277 <style> 278 :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } 279 body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f8fafc; color: #0f172a; } 280 main { width: min(92vw, 440px); border: 1px solid #e2e8f0; border-radius: 18px; background: #fff; padding: 28px; box-shadow: 0 24px 70px rgba(15, 23, 42, 0.12); text-align: center; } 281 p { color: #475569; line-height: 1.55; } 282 a { color: inherit; font-weight: 700; } 283 @media (prefers-color-scheme: dark) { 284 body { background: #020617; color: #e2e8f0; } 285 main { background: #0f172a; border-color: #1e293b; } 286 p { color: #cbd5e1; } 287 } 288 </style> 289 </head> 290 <body> 291 <main> 292 <h1 id="title">Signing you in...</h1> 293 <p id="message">Please wait while we finish your Google login.</p> 294 <p id="login-link" hidden><a href="\${escapeHtml(loginUrl)}">Back to login</a></p> 295 </main> 296 <script> 297 const params = new URLSearchParams(window.location.search) 298 const code = params.get('code') || '' 299 const returnTo = params.get('returnTo') || '/' 300 const title = document.querySelector('#title') 301 const message = document.querySelector('#message') 302 const loginLink = document.querySelector('#login-link') 303 304 function cleanCodeFromUrl() { 305 const nextUrl = new URL(window.location.href) 306 nextUrl.searchParams.delete('code') 307 window.history.replaceState({}, document.title, nextUrl.toString()) 308 } 309 310 function fail(text) { 311 cleanCodeFromUrl() 312 title.textContent = 'We could not sign you in' 313 message.textContent = text || 'The sign-in link is invalid or expired. Please try again.' 314 loginLink.hidden = false 315 } 316 317 async function complete() { 318 if (!code) { 319 fail('Missing sign-in code. Please start Google login again.') 320 return 321 } 322 323 try { 324 const response = await fetch('/api/auth/cloudmysite/exchange', { 325 method: 'POST', 326 credentials: 'include', 327 headers: { 'Content-Type': 'application/json' }, 328 body: JSON.stringify({ code, returnTo }), 329 }) 330 const payload = await response.json().catch(() => ({})) 331 332 if (!response.ok || payload.success === false) { 333 fail(payload.error || 'The sign-in link could not be verified. Please try again.') 334 return 335 } 336 337 cleanCodeFromUrl() 338 window.location.replace(payload.redirect || returnTo || '/') 339 } catch { 340 fail('Google sign-in could not be completed right now. Please try again.') 341 } 342 } 343 344 complete() 345 <\/script> 346 </body> 347</html>\`, 348 { 349 status: 200, 350 headers: { 351 'content-type': 'text/html; charset=utf-8', 352 }, 353 }, 354 ) 355} 356 357export function handleAuthCloudMySiteComplete(request) { 358 return buildCloudMySiteCompletePage(request) 359} 360 361export async function handleAuthCloudMySiteExchange(request, env) { 362 const body = await request.json().catch(() => ({})) 363 const result = await completeCloudMySiteManagedGoogleLogin(request, env, { 364 code: body?.code || '', 365 returnTo: body?.returnTo || '/', 366 }) 367 368 if (result.user && result.authConfig) { 369 return await buildAuthenticatedJsonResponse(request, env, result.authConfig, result.user, 200, result.profile, { 370 redirect: result.returnTo || '/', 371 }) 372 } 373 374 return jsonResponse({ success: false, error: result.error || 'google_login_failed' }, result.status || 400) 375}`;function Ey(t,e,r){const n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(?:async\\s+)*function\\s+${n}\\s*\\(`).exec(t)?.index??-1;if(i===-1)return t;const a=t.indexOf("{",i);if(a===-1)return t;let o=0;for(let l=a;l<t.length;l+=1){const c=t[l];if(c==="{")o+=1;else if(c==="}"&&(o-=1,o===0))return`${t.slice(0,i)}${r}${t.slice(l+1)}`}return t}function SI(t){let e=t;return e=e.replace(` enableGoogleLogin: normalizeBoolean(authInput.enableGoogleLogin), 376 protectedPaths,`,` enableGoogleLogin: normalizeBoolean(authInput.enableGoogleLogin), 377 googleOAuthMode: authInput.googleOAuthMode === 'custom' ? 'custom' : 'managed', 378 protectedPaths,`),e}function CI(t){return t.includes("import runtimeConfig from '../../app.config.json'")?Ey(t,"buildGoogleLoginUrl",eq):t}function AI(t){let e=t;return e.includes("function usesManagedGoogleOAuth(")||(e=e.replace("function getAuthStateTableName(scope) {\n const normalizedScope = normalizeAuthScope(scope) || 'app'\n return `app_${normalizedScope}_${AUTH_STATE_TABLE_SUFFIX}`\n}",`${tq} 379 380function getAuthStateTableName(scope) { 381 const normalizedScope = normalizeAuthScope(scope) || 'app' 382 return \`app_\${normalizedScope}_\${AUTH_STATE_TABLE_SUFFIX}\` 383}`)),e.includes("CLOUDMYSITE_AUTH_SERVICE_BINDING_NAME")||(e=e.replace(`const CLOUDMYSITE_APP_ID_ENV_NAME = 'APP_ID' 384`,`const CLOUDMYSITE_APP_ID_ENV_NAME = 'APP_ID' 385const CLOUDMYSITE_AUTH_SERVICE_BINDING_NAME = '${f0}' 386`)),e.includes("function getCloudMySiteAuthService(")||(e=e.replace(`function getCloudMySiteAppId(env) { 387 return typeof env?.[CLOUDMYSITE_APP_ID_ENV_NAME] === 'string' ? env[CLOUDMYSITE_APP_ID_ENV_NAME].trim() : '' 388} 389`,`function getCloudMySiteAppId(env) { 390 return typeof env?.[CLOUDMYSITE_APP_ID_ENV_NAME] === 'string' ? env[CLOUDMYSITE_APP_ID_ENV_NAME].trim() : '' 391} 392 393function getCloudMySiteAuthService(env) { 394 const binding = env?.[CLOUDMYSITE_AUTH_SERVICE_BINDING_NAME] 395 return binding && typeof binding.fetch === 'function' ? binding : null 396} 397 398async function fetchCloudMySiteAuth(env, pathname, init = {}) { 399 const url = new URL(pathname, getCloudMySiteAuthBaseUrl(env)) 400 const service = getCloudMySiteAuthService(env) 401 402 if (service) {
403 return service.fetch(new Request(url.toString(), init)) 404 } 405 406 return fetch(url.toString(), init) 407} 408`)),e=e.replace(` if (Object.prototype.hasOwnProperty.call(source, 'enableGoogleLogin')) { 409 patch.enableGoogleLogin = source.enableGoogleLogin === true 410 } 411 412 if (Object.prototype.hasOwnProperty.call(source, 'protectedPaths')) {`,` if (Object.prototype.hasOwnProperty.call(source, 'enableGoogleLogin')) { 413 patch.enableGoogleLogin = source.enableGoogleLogin === true 414 } 415 416 if (Object.prototype.hasOwnProperty.call(source, 'googleOAuthMode')) { 417 patch.googleOAuthMode = source.googleOAuthMode === 'custom' ? 'custom' : 'managed' 418 } 419 420 if (Object.prototype.hasOwnProperty.call(source, 'protectedPaths')) {`),e=e.replace(` googleConfigured: 421 hasConfiguredSecret(env, GOOGLE_CLIENT_ID_SECRET_NAME) && hasConfiguredSecret(env, GOOGLE_CLIENT_SECRET_NAME),`,` googleConfigured: usesManagedGoogleOAuth(config) 422 ? hasCloudMySiteManagedGoogleConfig(env, config) 423 : hasConfiguredSecret(env, GOOGLE_CLIENT_ID_SECRET_NAME) && hasConfiguredSecret(env, GOOGLE_CLIENT_SECRET_NAME),`),e=e.replace(` enableGoogleLogin: config.auth.enableGoogleLogin, 424 googleConfigured:`,` enableGoogleLogin: config.auth.enableGoogleLogin, 425 googleOAuthMode: config.auth.googleOAuthMode, 426 googleConfigured:`),e.includes("async function exchangeCloudMySiteLoginCode(")?(e=Ey(e,"readCloudMySiteExchangeError",xI),e=Ey(e,"exchangeCloudMySiteLoginCode",wI)):e=e.replace("export async function handleAuthGoogleStart(request, env) {",`${rq} 427 428export async function handleAuthGoogleStart(request, env) {`),e.includes("const completeUrl = new URL('/auth/complete', request.url)")||(e=e.replace(` if (!env.DB) { 429 return jsonResponse({ error: 'Google login is unavailable right now.' }, 503) 430 } 431 432 const runtime = await ensureAuthRuntime(env.DB, authConfig.app.slug, env)`,` if (!env.DB) { 433 return jsonResponse({ error: 'Google login is unavailable right now.' }, 503) 434 } 435 436 if (usesManagedGoogleOAuth(authConfig)) { 437 const appId = getCloudMySiteAppId(env) 438 439 if (!appId) { 440 return jsonResponse({ error: 'App ID is not configured for managed Google login.' }, 503) 441 } 442 443 const url = new URL(request.url) 444 const returnTo = sanitizeReturnTo(url.searchParams.get('returnTo') || '/') 445 const completeUrl = new URL('/auth/complete', request.url) 446 completeUrl.searchParams.set('returnTo', returnTo) 447 448 const startUrl = new URL('/api/oauth/google/start', getCloudMySiteAuthBaseUrl(env)) 449 startUrl.searchParams.set('app_id', appId) 450 startUrl.searchParams.set('return_to', completeUrl.toString()) 451 452 return Response.redirect(startUrl.toString(), 302) 453 } 454 455 const runtime = await ensureAuthRuntime(env.DB, authConfig.app.slug, env)`)),e}function EI(t){let e=t;return e.includes("handleAuthCloudMySiteComplete")||(e=e.replace(` handleAuthGoogleCallback, 456`,` handleAuthGoogleCallback, 457 handleAuthCloudMySiteComplete, 458 handleAuthCloudMySiteExchange, 459`)),e.includes("normalizedPathname === '/auth/complete'")||(e=e.replace(` if (normalizedPathname === '/api/auth/google/callback') { 460 if (request.method !== 'GET') return jsonResponse({ error: 'Method not allowed' }, 405) 461 return await handleAuthGoogleCallback(routeRequest, env) 462 } 463`,` if (normalizedPathname === '/api/auth/google/callback') { 464 if (request.method !== 'GET') return jsonResponse({ error: 'Method not allowed' }, 405) 465 return await handleAuthGoogleCallback(routeRequest, env) 466 } 467 468 if (normalizedPathname === '/auth/complete') { 469 if (request.method !== 'GET') return jsonResponse({ error: 'Method not allowed' }, 405) 470 return await handleAuthCloudMySiteComplete(routeRequest, env) 471 } 472 473 if (normalizedPathname === '/api/auth/cloudmysite/exchange') { 474 if (request.method !== 'POST') return jsonResponse({ error: 'Method not allowed' }, 405) 475 return await handleAuthCloudMySiteExchange(routeRequest, env) 476 } 477`)),e}function nq(t){let e=t;return e=e.replace('run_worker_first = ["/api/*"]','run_worker_first = ["/api/*", "/auth/complete"]'),e.includes('not_found_handling = "single-page-application"')||(e=e.replace('run_worker_first = ["/api/*", "/auth/complete"]',`run_worker_first = ["/api/*", "/auth/complete"] 478not_found_handling = "single-page-application"`)),e}function ky(t){return String(t||"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function sq(t,e){const r=Object.entries(e).map(([d,h])=>[d.trim(),String(h||"").trim()]).filter(([d,h])=>/^[A-Z][A-Z0-9_]*$/.test(d)&&h);if(r.length===0)return t;const n=t.replace(/\r\n/g,` 479`).split(` 480`),s=n.findIndex(d=>/^\s*\[vars\]\s*$/.test(d)),i=(d,h)=>`${d} = "${ky(h)}"`;if(s===-1)return[...n.length>0&&n[n.length-1]===""?n.slice(0,-1):[...n],"","[vars]",...r.map(([m,b])=>i(m,b)),""].join(` 481`);let a=n.length;for(let d=s+1;d<n.length;d+=1)if(/^\s*\[/.test(n[d])){a=d;break}const o=new Map(r),l=new Set,c=n.slice(s+1,a).map(d=>{const h=d.match(/^(\s*)([A-Z][A-Z0-9_]*)\s*=/);return!h||!o.has(h[2])?d:(l.add(h[2]),`${h[1]}${i(h[2],o.get(h[2])||"")}`)}),u=r.filter(([d])=>!l.has(d)).map(([d,h])=>i(d,h));return n.splice(s+1,a-s-1,...c,...u),n.join(` 482`)}function iq(t,e,r){const n=String(e).trim(),s=String(r).trim();if(!n||!s||new RegExp(`binding\\s*=\\s*["']${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["']`).test(t))return t;const a=`[[services]] 483binding = "${ky(n)}" 484service = "${ky(s)}"`;return`${t.endsWith(` 485`)?t.replace(/\n+$/,""):t} 486 487${a} 488`}function oq(t,e,r=id){const n=String(e||"").trim();if(!n)return t;let s=id;try{s=new URL(r||id).origin}catch{s=id}const i=sq(t,{APP_ID:n,CLOUDMYSITE_AUTH_BASE_URL:s});return iq(i,f0,QG)}function Ro(t,e){const r=[],n=e.global?e:new RegExp(e.source,`${e.flags}g`);for(const s of t.matchAll(n)){const i=s.index??0;r.push({index:i})}return r}function aq(t){const e=t.replace(/\\/g,"/");return e.startsWith("/home/project/")||e.startsWith("/workspace/")}function lq(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/home\/project\//,"").replace(/^\/workspace\//,"").replace(/^\.\//,"").replace(/^\/+/,"")}const cq=new Set(["src/lib/appAuth.tsx","src/lib/appData.ts","src/lib/appSchema.ts","src/lib/cloudflareCrud.ts","js/auth-runtime.js","js/auth-worker.js","js/db-runtime.js","js/worker.js","vite.local-db.ts"]),uq=["dist/","build/",".next/",".nuxt/",".svelte-kit/","coverage/","storybook-static/"];function dq(t){return cq.has(t)?!0:uq.some(e=>
488t.startsWith(e))}function hq(t,e){if(e<=0)return 1;let r=1;for(let n=0;n<e;n++)t.charCodeAt(n)===10&&(r+=1);return r}function fq(t,e){const r=t.lastIndexOf(` 489`,e),n=t.indexOf(` 490`,e),s=r===-1?0:r+1,i=n===-1?t.length:n;return t.slice(s,i).trim().slice(0,240)}function pq(t){const e=[];let r=0;const n=t.length;let s="normal",i=-1;for(;r<n;){const a=t[r],o=r+1<n?t[r+1]:"";if(s==="normal"){if(a==="/"&&o==="/"){s="lineComment",i=r,r+=2;continue}if(a==="/"&&o==="*"){s="blockComment",i=r,r+=2;continue}if(a==="'"){s="single",r+=1;continue}if(a==='"'){s="double",r+=1;continue}if(a==="`"){s="template",r+=1;continue}r+=1;continue}if(s==="single"){if(a==="\\"){r+=2;continue}a==="'"&&(s="normal"),r+=1;continue}if(s==="double"){if(a==="\\"){r+=2;continue}a==='"'&&(s="normal"),r+=1;continue}if(s==="template"){if(a==="\\"){r+=2;continue}a==="`"&&(s="normal"),r+=1;continue}if(s==="lineComment"){a===` 491`&&(e.push({start:i,end:r}),i=-1,s="normal"),r+=1;continue}if(s==="blockComment"){if(a==="*"&&o==="/"){e.push({start:i,end:r+2}),i=-1,s="normal",r+=2;continue}r+=1;continue}}return s==="lineComment"&&i>=0&&e.push({start:i,end:n}),s==="blockComment"&&i>=0&&e.push({start:i,end:n}),e}function mq(t,e){for(const r of e)if(t>=r.start&&t<r.end)return!0;return!1}function gq(t){const e=pq(t);return Ro(t,yq).filter(n=>!mq(n.index,e))}const bq=/\b(?:OPENAI_API_KEY|AWS_SECRET(?:_ACCESS_KEY)?|STRIPE_SECRET(?:_KEY)?|SUPABASE_KEY)\b\s*[:=]\s*['"`][^'"`\n]{6,}['"`]/g,NC=/\b(?:api[_-]?key|secret|token|password|passwd|private[_-]?key)\b\s*[:=]\s*['"`][^'"`\s]{8,}['"`]/gi,vq=/\b(?:changeme|example|placeholder|replace[_-]?me|your[_-]?(?:token|key|secret|password)|test|dummy)\b/i,yq=/\beval\s*\(/g,_q=/\bdangerouslySetInnerHTML\b/g,xq=/\b(?:document\.)?[\w$]+\s*\.innerHTML\s*=/g,wq=/\blocalStorage\.(?:setItem|getItem)\s*\(\s*['"`][^'"`]*(?:token|password|secret|auth)[^'"`]*['"`]/gi,Sq=/\bfetch\s*\(\s*['"`]http:\/\//gi,Cq=/\b(?:Access-Control-Allow-Origin|allowOrigin|origin|cors)\b['"`]?\s*[:=]\s*['"`]\*['"`]/gi,Aq=/<iframe\b[^>]*>/gi,Eq=/\b(?:window\.location(?:\.href)?\s*=\s*|window\.location\.(?:assign|replace)\s*\(|redirect(?:To|Url)?\s*\()[^;\n)]*(?:location\.search|searchParams|query|params|document\.referrer|userInput|input)/gi,kq=/\b(?:localStorage|sessionStorage)\.setItem\s*\(\s*['"`][^'"`]*(?:password|passwd|passcode|otp)[^'"`]*['"`]\s*,/gi,LC=/\bconsole\.(?:log|info|debug|warn|error)\s*\(([^)]{0,240})/gi,Pq=/\bfetch\s*\(\s*['"`]http:\/\/[^'"`]+['"`][\s\S]{0,400}\b(?:authorization|password|passwd|passcode|otp|token|credential)\b/gi;function Tq(t){const e=t.content,r=/(?:['"`]?card['"`]?)\s*[:=]\s*\{[\s\S]{0,1600}?\b(?:number|card[_-]?number)\b[\s\S]{0,1600}?\b(?:cvc|cvv|exp_month|exp_year|expiry)\b/i.exec(e);if(r)return[{index:r.index}];const n=/\b(?:card[_-]?number|credit[_-]?card[_-]?number|cardNumber|creditCardNumber)\b/i.exec(e),s=/\b(?:cvv|cvc|security[_-]?code)\b/i.exec(e),i=/\b(?:exp(?:iry|iration)?[_-]?(?:date|month|year)?|exp_month|exp_year)\b/i.exec(e);return n&&(s||i)?[{index:Math.min(n.index,s?.index??1/0,i?.index??1/0)}]:[]}function Rq(t){const e=[],r=new RegExp(LC.source,LC.flags);for(const n of t.content.matchAll(r)){const s=(n[1]||"").replace(/(['"`])(?:\\.|(?!\1).)*\1/g," ");/\b(?:password|passwd|passcode|otp|cvv|cvc|card[_-]?number)\b/i.test(s)&&e.push({index:n.index??0})}return e}function Iq(t){const e=[],r=new RegExp(NC.source,NC.flags);for(const n of t.content.matchAll(r)){const s=n.index??0,i=n[0]||"";vq.test(i)||e.push({index:s})}return e}function Nq(t){const e=[];for(const r of t.content.matchAll(Aq)){const n=r.index??0,s=r[0]||"";/\bsandbox\b/i.test(s)||e.push({index:n})}return e}function bi(t,e,r,n,s,i){return{id:t,type:e,severity:r,message:n,suggestion:s,detect:i}}const Lq=[bi("api-key-exposed","API_KEY_EXPOSED","high","Sensitive API key detected in client-side code.","Move the secret to a server-side environment variable and remove it from client files.",t=>Ro(t.content,bq)),bi("hardcoded-secret","HARDCODED_SECRET","high","Hardcoded secret-like value detected.","Use secure environment variables or secret storage instead of inline credentials.",t=>Iq(t)),bi("eval-usage","EVAL_USAGE","high","Use of eval() detected which can lead to code injection.","Replace eval() with safer parsing or controlled execution logic.",t=>gq(t.content)),bi("dangerously-set-inner-html","XSS_DANGEROUS_HTML","medium","dangerouslySetInnerHTML detected. Ensure content is sanitized.","Avoid raw HTML rendering or sanitize untrusted content before rendering.",t=>Ro(t.content,_q)),bi("inner-html-assignment","XSS_INNER_HTML","medium","innerHTML assignment detected and may introduce XSS risks.","Use textContent or trusted templating with explicit sanitization.",t
491=>Ro(t.content,xq)),bi("insecure-storage","INSECURE_STORAGE","high","Sensitive value appears to be stored in localStorage.","Avoid storing tokens/passwords in localStorage. Prefer secure, httpOnly cookies for auth data.",t=>Ro(t.content,wq)),bi("insecure-http-fetch","INSECURE_HTTP_FETCH","medium","Insecure http:// fetch request detected.","Use https:// endpoints to avoid transmitting data over insecure transport.",t=>Ro(t.content,Sq)),bi("insecure-cors-star","INSECURE_CORS","high","Wildcard CORS origin detected.",'Restrict CORS to trusted origins instead of allowing "*".',t=>Ro(t.content,Cq)),bi("iframe-without-sandbox","IFRAME_NO_SANDBOX","medium","iframe detected without sandbox restrictions.","Add a sandbox attribute with the minimum required permissions.",t=>Nq(t)),bi("unsafe-redirect","UNSAFE_REDIRECT","medium","Redirect logic appears to use user-controlled input.","Validate and allowlist redirect targets before navigation.",t=>Ro(t.content,Eq)),bi("plaintext-password-storage","PLAINTEXT_PASSWORD_STORAGE","critical","Password, passcode, or OTP data appears to be stored in browser storage.","Use a server-side authentication provider and secure, httpOnly session cookies. Never persist plaintext credentials.",t=>Ro(t.content,kq)),bi("sensitive-data-logging","SENSITIVE_DATA_LOGGING","critical","Sensitive authentication or payment data appears to be written to application logs.","Remove sensitive values from logs and record only non-sensitive event metadata.",t=>Rq(t)),bi("raw-card-data-handling","RAW_CARD_DATA_HANDLING","critical","Raw payment-card fields appear to be handled directly by the application.","Use Stripe Checkout, Stripe Elements, or another provider-hosted tokenization flow so raw card data never reaches the app.",t=>Tq(t)),bi("insecure-auth-transport","INSECURE_AUTH_TRANSPORT","critical","Authentication data appears to be sent over an insecure HTTP connection.","Send credentials only to trusted HTTPS endpoints and use secure server-side session handling.",t=>Ro(t.content,Pq))];function Dq(t){const e=new Map;for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||typeof n.content!="string")continue;const s=lq(r);if(dq(s))continue;const i=aq(r),a=e.get(s);if(!a){e.set(s,{file:{path:s,content:n.content},sourceWasWorkspaceAbsolute:i});continue}if(!i&&a.sourceWasWorkspaceAbsolute){e.set(s,{file:{path:s,content:n.content},sourceWasWorkspaceAbsolute:!1});continue}i===a.sourceWasWorkspaceAbsolute&&e.set(s,{file:{path:s,content:n.content},sourceWasWorkspaceAbsolute:i})}return Array.from(e.values()).map(r=>r.file)}function Mq(t){const e=[],r=new Set;for(const n of t)for(const s of Lq){const i=s.detect(n);for(const a of i){const o=hq(n.content,a.index),l=`${n.path}:${s.id}:${o}`;r.has(l)||(r.add(l),e.push({file:n.path,type:s.type,severity:a.severity||s.severity,message:a.message||s.message,suggestion:a.suggestion||s.suggestion,line:o,excerpt:fq(n.content,a.index),ruleId:s.id}))}}return e}function Oq(t){return t.severity==="high"||t.severity==="critical"}function jq(t,e){return{scannedAt:Date.now(),scannedFileCount:t,durationMs:e}}const $q="allow-scripts allow-same-origin allow-popups allow-forms allow-presentation",Bq=/<iframe\b[^>]*>/gi,Fq=/\ssandbox(?:\s*=|\s|\/?>)/i;function Wq(t){return t.type==="IFRAME_NO_SANDBOX"}function Hq(t,e=$q){if(Fq.test(t))return t;const r=t.match(/\/?>$/);if(!r)return t;const n=`sandbox="${e}"`,s=r[0],i=t.length-s.length,a=t.slice(0,i);if(t.includes(` 492`)){const l=a.replace(/[ \t]*$/,""),c=a.slice(l.length);if(l.endsWith(` 493`))return`${l}${c||" "}${n} 494${c}${s}`}const o=/\s$/.test(a)?"":" ";return`${a}${o}${n}${s}`}function Uq(t,e){if(!e.some(Wq))return{content:t,appliedCount:0};let r=0;return{content:t.replace(Bq,s=>{const i=Hq(s);return i!==s&&(r+=1),i}),appliedCount:r}}const Py="cms:security-audit-fix-request",Ty="cms:open-project-integrations",DC=8;function zq(){return typeof window>"u"||typeof navigator>"u"?{indexedDbAvailable:!1,cookieEnabled:null,language:null,userAgent:null,locationPath:null}:{indexedDbAvailable:typeof indexedDB<"u",cookieEnabled:typeof navigator.cookieEnabled=="boolean"?navigator.cookieEnabled:null,language:navigator.language||null,userAgent:navigator.userAgent||null,locationPath:window.location.pathname||null}}function Vq(t){return t instanceof Error?{name:t.name||"Error",message:t.message||"Unknown error"}:{name:"Error",message:String(t)}}function Vu(t){typeof window<"u"&&(window.__genieHistoryDiagnostics=t);const e={...t,browser:{...t.browser,userAgent:t.browser.userAgent?t.browser.userAgent.
494slice(0,240):null}};if(t.status==="failed"){console.error("[history.home] load-failed",e);return}if(t.status==="empty"||t.status==="no-auth"||t.status==="no-db"){console.warn("[history.home] load-warning",e);return}console.info("[history.home] load-state",e)}function Gq(t){switch(t){case"loading":return"Loading";case"ready":return"Ready";case"empty":return"Empty";case"failed":return"Failed";case"no-auth":return"No auth";case"no-db":return"No IndexedDB";case"idle":default:return"Idle"}}function qq(t){if(typeof t=="number"&&Number.isFinite(t))return new Date(t).toISOString();const e=Date.parse(String(t||"").trim());return Number.isFinite(e)?new Date(e).toISOString():new Date().toISOString()}function Kq(t){return t==="failed"?"failed":t==="processing"?"building":"ready"}function kI(t){if(!t)return"ready";switch(t.status){case"failed":return"failed";case"canceled":return"canceled";case"queued":case"running":return"building";case"ready":default:return"ready"}}function Ry(t){switch(t){case"failed":return"Failed";case"canceled":return"Canceled";case"building":return"Building";case"ready":default:return"Ready"}}function MC(t){switch(t){case"failed":return"border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-500/25 dark:bg-rose-500/10 dark:text-rose-200";case"canceled":return"border-slate-300 bg-slate-100 text-slate-700 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200";case"building":return"border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-500/25 dark:bg-sky-500/10 dark:text-sky-200";case"ready":default:return"border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-500/25 dark:bg-emerald-500/10 dark:text-emerald-200"}}function Yq(t){const e=Date.parse(t);return Number.isFinite(e)?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e)):"Updated just now"}function Xq(t){const e=t.currentMode==="site"?"Website":"App",r=kI(t.buildJob),n=t.buildJob?.currentStep||(r==="building"?"Your build is still running in the background.":r==="failed"?t.buildJob?.error||"Open the project to inspect the failed build.":r==="canceled"?"This build was canceled.":"Open the project to continue from the latest saved state.");return{id:`current:${t.currentMode}:${t.currentWorkspaceId}`,workspaceId:t.currentWorkspaceId,mode:t.currentMode,title:t.currentProjectName.trim()||(t.currentMode==="site"?"Current Website Project":"Current App Project"),kindLabel:e,updatedAt:qq(t.buildJob?.updatedAt??Date.now()),summary:n,status:r,statusLabel:Ry(r),isCurrent:!0}}function Jq({currentMode:t,currentProjectName:e,currentWorkspaceId:r,buildJob:n,onOpenBuild:s,onCancelBuild:i,onOpenProject:a}){const o=We(On),[l,c]=x.useState([]),[u,d]=x.useState(null),[h,m]=x.useState(!1),b=j1(n);x.useEffect(()=>{let _=!1;return(async()=>{const C=o?.email,A={attemptedAt:new Date().toISOString(),status:"loading",userEmail:C||null,browser:zq(),db:{opened:!1,name:null,version:null,stores:[]},counts:{appEntries:0,siteEntries:0,totalEntries:0,matchingUserEntries:0,displayableEntries:0,missingUrlIdEntries:0,hiddenByStatusEntries:0,derivedEntries:0,visibleProjects:0},remote:{checked:!1,appEntries:0,siteEntries:0,totalEntries:0,insertedEntries:0,updatedEntries:0,error:null},error:null};if(Vu(A),!C){_||(c([]),d({...A,status:"no-auth"})),Vu({...A,status:"no-auth"});return}const E=await Of(),S={opened:!!E,name:E?.name||null,version:typeof E?.version=="number"?E.version:null,stores:E?Array.from(E.objectStoreNames):[]};if(!E){const k={...A,status:"no-db",db:S,error:{name:"IndexedDBUnavailable",message:"History database could not be opened in this browser session."}};_||(c([]),d(k)),Vu(k);return}try{const k=await sE({db:E,userEmail:C}),O=k.app.items,T=k.site.items,R=[...O,...T],N=R.filter(F=>F.userEmail===C),M=N.filter(F=>{const V=F.metadata?.historyStatusOverride;return V==="processing"||V==="failed"}).length,B=N.filter(F=>iE(F)),U=B.filter(F=>!!F.urlId),X=l2(c2(U),"newest"),oe=X.slice(0,DC).map(F=>{const V=Kq(F.status);return{id:F.id,workspaceId:F.urlId,mode:F.mode,title:F.projectName||F.title,kindLabel:F.kind==="website"?"Website":"App",updatedAt:F.updatedAt||F.createdAt,summary:F.promptSnippet||F.summary,status:V,statusLabel:Ry(V),isCurrent:!1}}),L={...A,status:oe.length>0?"ready":"empty",db:S,counts:{appEntries:O.length,siteEntries:T.length,totalEntries:R.length,matchingUserEntries:N.length,displayableEntries:B.length,missingUrlIdEntries:N.filter(F=>!F.urlId).length,hiddenByStatusEntries:M,derivedEntries:X.length,visibleProjects:oe.length},remote:{checked:k.remoteChecked,appEntries:k.app.remoteEntryCount,siteEntries:k.site.remoteEntryCount,totalEntries:k.app.remoteEntryCount+k.site.remoteEntryCount,insertedEntries:k.app.insertedCount+k.site.insertedCount,updatedEntries:k.app.updatedCount+k.site.updatedCount,error:k.remoteError},error:null};if(_)return;c(oe),d(L),Vu(L)}catch(k){const O={...A,status:"failed",db:S,error:Vq(k)};
494console.error("Failed to load workspace home projects",k,O),_||(c([]),d(O)),Vu(O)}})(),()=>{_=!0}},[o?.email]),x.useEffect(()=>{m(!1)},[u]);const g=x.useMemo(()=>r?Xq({currentMode:t,currentProjectName:e,currentWorkspaceId:r,buildJob:n}):null,[n,t,e,r]),p=x.useMemo(()=>{const _=new Map;return l.forEach(C=>{_.set(`${C.mode}:${C.workspaceId}`,C)}),g&&_.set(`${g.mode}:${g.workspaceId}`,g),[..._.values()].sort((C,A)=>Date.parse(A.updatedAt)-Date.parse(C.updatedAt)).slice(0,DC)},[g,l]),y=x.useCallback(async()=>{!u||typeof navigator>"u"||!navigator.clipboard?.writeText||(await navigator.clipboard.writeText(JSON.stringify(u,null,2)),m(!0))},[u]),v=!!(u&&(u.status==="failed"||u.status==="empty"||u.status==="no-auth"||u.status==="no-db"));return f.jsx("div",{className:"h-full overflow-auto bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.10),transparent_32%),radial-gradient(circle_at_top_right,rgba(99,102,241,0.12),transparent_30%),linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] p-4 dark:bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.14),transparent_28%),radial-gradient(circle_at_top_right,rgba(99,102,241,0.16),transparent_30%),linear-gradient(180deg,rgba(10,15,25,0.98),rgba(7,10,18,0.98))]",children:f.jsxs("div",{className:"mx-auto flex h-full w-full max-w-6xl flex-col gap-5",children:[f.jsx("div",{className:"rounded-[30px] border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-6 shadow-sm",children:f.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[f.jsxs("div",{className:"max-w-2xl",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.24em] text-bolt-elements-textTertiary",children:"Home"}),f.jsx("div",{className:"mt-3 text-3xl font-semibold text-bolt-elements-textPrimary",children:"Your workspace keeps running in the background"}),f.jsx("div",{className:"mt-3 text-sm leading-7 text-bolt-elements-textSecondary",children:"Browse recent projects without losing your current build. Reopen the active project any time to keep following progress."})]}),f.jsxs("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-4 py-3 text-right",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-bolt-elements-textTertiary",children:"Current Status"}),f.jsx("div",{className:"mt-2 text-lg font-semibold text-bolt-elements-textPrimary",children:n?Ry(kI(n)):"Ready"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:n?.currentStep||(b?"Build running in background":"No active background build")})]})]})}),g?f.jsx("div",{className:"rounded-[28px] border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-5 shadow-sm",children:f.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-bolt-elements-textTertiary",children:"Current Project"}),f.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[f.jsx("div",{className:"truncate text-xl font-semibold text-bolt-elements-textPrimary",children:g.title}),f.jsx("span",{className:ue("rounded-full border px-2.5 py-1 text-[11px] font-semibold",MC(g.status)),children:g.statusLabel})]}),f.jsx("div",{className:"mt-2 text-sm leading-6 text-bolt-elements-textSecondary",children:g.summary})]}),f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx(En,{type:"button",onClick:s,className:"rounded-xl",children:b?"Open build":"Open project"}),b&&i?f.jsx(En,{type:"button",variant:"outline",onClick:i,className:"rounded-xl",children:"Cancel build"}):null]})]})}):null,f.jsxs("div",{className:"rounded-[28px] border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-5 shadow-sm",children:[f.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-bolt-elements-textTertiary",children:"Recent Projects"}),f.jsx("div",{className:"mt-2 text-lg font-semibold text-bolt-elements-textPrimary",children:"Resume work without losing the active build"})]}),f.jsx("div",{className:"text-sm text-bolt-elements-textSecondary",children:"Statuses update from saved workspace state."})]}),p.length>0?f.jsx("div",{className:"mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:p.map(_=>f.jsxs("button",{type:"button",onClick:()=>a({workspaceId:_.workspaceId,mode:_.mode,isCurrent:_.isCurrent}),className:ue("rounded-2xl border p-4 text-left transition hover:-translate-y-0.5 hover:border-accent-500/35 hover:shadow-sm",_.isCurrent?"border-accent-500/35 bg-accent-500/5":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2"),children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-bolt-elements-background-depth-3 px-2.5 py-1 text-[11px] font-semibold text-bolt-elements-textSecondary",children:_.kindLabel}),f.jsx("span",{className:ue("rounded-full border px-2.5 py-1 text-[11px] font-semibold",MC(_.status)),children:_.statusLabel}),_.isCurrent?f.jsx("span",{className:"rounded-full bg-bolt-elements-background-depth-3 px-2.5 py-1 text-[11px] font-semibold text-bolt-elements-textSecondary",children:"Current"}):null]}),f.jsx("div",{className:"mt-3 truncate text-base font-semibold text-bolt-elements-textPrimary",children:_.title}),f.jsx("div",{className:"mt-2 min-h-[3rem] text-sm leading-6 text-bolt-elements-textSecondary",children:_.summary}),f.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 text-xs text-bolt-elements-textTertiary",children:[f.jsx("span",{children:Yq(_.updatedAt)}),f.jsx("span",{children:_.isCurrent?"Open current project":"Open project"})]})]},_.id))}):f.jsx("div",{className:"mt-5 rounded-2xl border border-dashed border-bolt-elements-borderColor px-4 py-10 text-center text-sm text-bolt-elements-textSecondary",children:"Recent projects will appear here as soon as they are saved to your workspace history."}),v&&u?f.jsxs("div",{className:"mt-4 rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4",children:[f.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-bolt-elements-textTertiary",children:"History Diagnostics"}),f.jsx("div",{className:"mt-2 text-sm font-semibold text-bolt-elements-textPrimary",children:Gq(u.status)}),f.jsxs("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:["App rows: ",u.counts.appEntries," | Website rows:"," ",u.counts.siteEntries," | Remote rows: ",u.remote.totalEntries," | Visible: ",u.counts.visibleProjects]})]}),f.jsx(En,{type:"button",variant:"outline",size:"sm",onClick:()=>void y(),children:h?"Copied diagnostics":"Copy diagnostics"})]}),f.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-bolt-elements-textSecondary md:grid-cols-2",children:[f.jsxs("div",{children:["IndexedDB available: ",u.browser.indexedDbAvailable?"yes":"no"]}),f.jsxs("div",{children:["Database opened: ",u.db.opened?"yes":"no"]}),f.jsxs("div",{children:["Matching user rows: ",u.counts.matchingUserEntries]}),f.jsxs("div",{children:["Displayable rows: ",u.counts.displayableEntries]}),f.jsxs("div",{children:["Rows missing workspace id: ",u.counts.missingUrlIdEntries]}),f.jsxs("div",{children:["Rows hidden by status: ",u.counts.hiddenByStatusEntries]}),f.jsxs("div",{children:["Remote check completed: ",u.remote.checked?"yes":"no"]}),f.jsxs("div",{children:["Remote app rows: ",u.remote.appEntries]}),f.jsxs("div",{children:["Remote website rows: ",u.remote.siteEntries]}),f.jsxs("div",{children:["Remote rows inserted locally: ",u.remote.insertedEntries]}),f.jsxs("div",{children:["Remote rows refreshed locally: ",u.remote.updatedEntries]})]}),u.remote.error?f.jsxs("div",{className:"mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-200",children:["Remote history check: ",u.remote.error.name,":"," ",u.remote.error.message]}):null,u.error?f.jsxs("div",{className:"mt-3 rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700 dark:border-rose-500/25 dark:bg-rose-500/10 dark:text-rose-200",children:[u.error.name,": ",u.error.message]}):f.jsxs("div",{className:"mt-3 text-xs text-bolt-elements-textTertiary",children:["Full diagnostics are also available in the browser console under"," ",f.jsx("code",{children:"window.__genieHistoryDiagnostics"}),"."]})]}):null]})]})})}const PI=10,Qq=60;function Zq(t,e){return t>=Qq?"Your app is still loading. Larger workspaces can take several minutes on a slow connection.":e||t>=PI?"Your connection is slower than usual. Your app is still loading, so please keep this tab open.":"Preparing your workspace and app preview."}function e7(t){if(t<PI)return null;const e=Math.floor(t/60),r=t%60;return e>0?`Loading for ${e}m ${r.toString().padStart(2,"0")}s`:`Loading for ${r} seconds`}
494function t7(){const t=l_(),[e,r]=x.useState(0);x.useEffect(()=>{const s=Date.now(),i=window.setInterval(()=>{r(Math.floor((Date.now()-s)/1e3))},1e3);return()=>{window.clearInterval(i)}},[]);const n=e7(e);return f.jsx("div",{className:"flex h-full min-h-[18rem] w-full items-center justify-center bg-bolt-elements-background-depth-1 px-5",role:"status","aria-live":"polite","aria-busy":"true",children:f.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-6 py-7 text-center shadow-sm",children:[f.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-bolt-elements-item-backgroundAccent",children:f.jsx("div",{className:"h-7 w-7 animate-spin rounded-full border-[3px] border-bolt-elements-borderColor border-t-bolt-elements-item-contentAccent"})}),f.jsx("div",{className:"mt-4 text-base font-semibold text-bolt-elements-textPrimary",children:"Loading your app workspace..."}),f.jsx("div",{className:"mt-2 text-sm leading-6 text-bolt-elements-textSecondary",children:Zq(e,t.constrained)}),f.jsx("div",{className:"mx-auto mt-5 h-1.5 w-full max-w-xs overflow-hidden rounded-full bg-bolt-elements-background-depth-3",children:f.jsx("div",{className:"h-full w-1/2 animate-[pulse_1.5s_ease-in-out_infinite] rounded-full bg-bolt-elements-item-contentAccent"})}),n?f.jsx("div",{className:"mt-3 text-xs font-medium text-bolt-elements-textTertiary",children:n}):null]})})}const r7="cms_publish_target:",n7="cms_publish_fingerprint:",s7=".cloudmysite.app",i7="cloudmysite.app",o7=".cloudmysite.net",a7="cloudmysite.net",l7=40,Tb=["Preparing your deployment package...","Uploading assets to our global regions...","Connecting the live domain route...","Running final edge checks..."],OC="cloudmysite-ai-app-runtime-worker",jC=5e3,c7=14,u7=new Set(["","my app","my website","untitled app"]),d7=new Set(["app now app","app now platform","app now tool","cloudmysite template","vite app"]),Iy="home",h7="src/lib/appAuth.tsx",f7="js/auth-worker.js",p7="js/auth-runtime.js",m7="js/worker.js",g7="wrangler.toml",b7={ease:Ds};function v7(t){const e=String(t||"").trim().toLowerCase();return!!e&&e!=="template-bootstrap"&&e!=="starter-template-files"&&e!=="imported-files"&&!e.startsWith("implicit-artifact-")&&!e.startsWith("missing-artifact-id-")}const y7={left:{value:"code",text:"Code"},middle:{value:"diff",text:"Diff"},right:{value:"preview",text:"Preview"}},_7={closed:{width:0,transition:{duration:.2,ease:Ds}},open:{width:"var(--workbench-inner-width)",transition:{duration:.2,ease:Ds}}};function Rb(t){return new URLSearchParams(t).get(Iy)==="1"}const x7=x.lazy(()=>H(()=>import("./DiffView-SIFVNEj3.js"),__vite__mapDeps([96,5,6,24,3,8,11,9,10,25,7,12,13,14,15,16,17,18,26,22,23,27,28,29,30,31,32,33,71,19,20,21,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,97])).then(t=>({default:t.DiffView}))),w7=x.lazy(()=>H(()=>import("./Preview-DiF-fRVO.js"),__vite__mapDeps([98,5,6,7,3,8,9,10,11,12,13,14,15,16,17,18,24,25,26,22,23,27,28,29,30,31,32,33,71,99])).then(t=>({default:t.Preview}))),S7=x.lazy(()=>H(()=>import("./AdminWorkspace-NbGkEJF3.js"),__vite__mapDeps([100,5,63,36,37,33,3,41,43,62,23,40,64,46,22,16,14,17,11,10,38,39,20,67,6,71,79,12,13,15,8,18,24,9,25,7,26,27,28,29,30,31,32,35,42,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,65,66,68,34,69,70,72,73,74,75,76,101,19,21,77,78,80,81,82,83,84,85,86,87,88,102])).then(t=>({default:t.AdminWorkspace}))),C7=x.lazy(()=>H(()=>import("./PublishDialog-BFD8pRoX.js"),__vite__mapDeps([103,5,36,37,33,3,22,23,104,14,16,17,11,24,8,9,10,25,7,12,13,15,18,26,6,27,28,29,30,31,32,19,20,21,34,35,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>({default:t.PublishDialog}))),A7=x.lazy(()=>H(()=>import("./SecurityAuditDialog-BcPV1jvR.js"),__vite__mapDeps([105,5,36,37,33,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,35,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>({default:t.SecurityAuditDialog}
494))),E7=x.lazy(()=>H(()=>import("./PricingDialog-TZK6K_5x.js"),__vite__mapDeps([106,5,36,37,33,3,107,25,66,69,108,109,50,32,30,31,42,110,111,47,46,54,112,113,114,16,14,17,11,15,115,79,80,116])).then(t=>({default:t.PricingDialog}))),k7=x.lazy(()=>H(()=>import("./CheckoutDialog-BNmVWL-k.js"),__vite__mapDeps([117,5,36,37,33,3,22,23,6,104,14,16,17,11,79,80,24,8,9,10,25,7,12,13,15,18,26,27,28,29,30,31,32,19,20,21,34,35,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,81,82,83,84,85,86,87,88])).then(t=>({default:t.CheckoutDialog}))),P7=x.lazy(()=>H(()=>import("./PaymentSuccessDialog-C-r3zina.js"),__vite__mapDeps([118,5,6,7,3,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88])).then(t=>({default:t.PaymentSuccessDialog}))),Ib=f.jsx(t7,{}),yd="App published, but managed Google login registration failed.";function T7(t){const e=String(t||"").trim();return e?`${yd} Reason: ${e}.`:yd}function $C(t){if(!t)return;const r=t.split("#")[0].replace(/\/+$/,"").split("/").filter(Boolean),n=r[r.length-1];if(n)return n.replace(/\.git$/i,"")}function R7(t){return/(?:^https?:\/\/|git@)github\.com[/:]/i.test(String(t||"").trim())}function I7(t){const e=String(t||"").trim().toLowerCase();return e==="r2"||e.startsWith("r2://")}function Al(t){if(!t)return;const e=t.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"").replace(/:\d+$/,""),n=[".cloudmysite.app",".cloudmysite.net"].find(i=>e.endsWith(i));return n&&e.slice(0,e.length-n.length).replace(/\.$/,"")||void 0}function BC(t){const e=(t||"").trim();if(e)try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).origin}catch{return}}function Qn(t){return(t||"").trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"").replace(/:\d+$/,"")||void 0}function ni(t){return(t||"").toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,63)||void 0}function TI(t){return/^(?:a|s|ca|cs)-[A-Za-z0-9_-]+$/.test(String(t||"").trim())}function Vn(t){const e=ni(t);if(!(!e||TI(e)))return e}function N7(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L7(t){return ni(String(t||"").replace(/@/g,"-"))}function FC(t,e){const r=Vn(t);if(!r)return;const n=L7(e);if(n){const a=new RegExp(`-${N7(n)}-\\d{3}$`),o=r.replace(a,""),l=ni(o);if(l&&l!==r)return l}const s=r.replace(/-\d{3}$/,""),i=ni(s);return i&&i!==r?i:void 0}function D7(t){return(t||"").toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").slice(0,48)||void 0}const M7=new Set(["my app","my website","website","site","app","untitled","untitled app","untitled project","create initial files","imported files"]),O7=new Set(["a","an","the","i","me","my","we","our","you","your","to","for","with","and","or","of","in","on","at","by","from","into","that","this","these","those","it","is","are","be","been","being","as","if","then","than","so","but","can","should","could","would","will","want","need","user","users","player","players","each","every","all"]),j7=new Set(["create","build","design","make","generate","develop","simple","small","basic","clean","modern","responsive","beautiful","landing","page","website","site","app","application"]),WC=new Set(["add","edit","delete","track","record","store","allow","allows","see","view","show","list","answer","answers","display"]),$7=3,HC=28;function B7(t){const e=(t||"").trim();if(!e)return;const r=e.toLowerCase().replace(/\s+/g," ").trim();if(M7.has(r))return;const n=e.replace(/^\s*(create|build|design|make|generate|develop)\b[:\s-]*/i,"").replace(/\b(a|an|the)\b/gi," ").replace(/\b(page|website|site|app|application)\b/gi," ").replace(/\s+/g," ").trim(),s=(n||e).toLowerCase().replace(/[^a-z0-9\s-]/g," ").replace(/-/g," ").split(/\s+/).filter(Boolean),i=[],a=new Set;for(const l of s){if(WC.has(l)&&i.length>=2)break;if(O7.has(l)||j7.has(l)||WC.has(l)||l.length<2||a.has(l))continue;if([...i,l].join("-").length>HC||(i.push(l),a.add(l),i.length>=$7))break}const o=i.join("-");return ni(o||n||e)?.slice(0,HC)}function UC(t){const e=(t||"").toLowerCase();return e.includes("this worker does not exist on your account")||e.includes("worker does not exist")||e.includes("failed to bind cloudflare worker domain")||e.includes("publish your app before managing secrets")}function Nb(t){const e=(t||"").trim();return e?e.replace(/[-_]+/g," ").replace(/\s+/g," ").replace(/\b\w/g,r=>r.toUpperCase()):"Untitled App"}function F7(t){return u7.has(String(t||"").trim().toLowerCase())}function W7(t){return d7.has(String(t||"").trim().replace(/\s+/g," ").toLowerCase())}function H7(t){const e=t.match(/^\/apps?\/([^/?#]+)/i);if(!e?.[1]||e[1].toLowerCase()==="c"||TI(e[1]))return;const r=Vn(e[1]);return r?r.slice(0,96):void 0}function RI(t,e){const r=(e||"anonymous").toLowerCase(),n=typeof window<"u"?r_(t,window.location.search):t;return`${r7}${r}:${n}`}function II(t,e){const r=(e||"anonymous").toLowerCase(),n=typeof window<"u"?r_(t,window.location.search):t;return`${n7}${r}:${n}`}function Ac(t){const e=(t||"").toLowerCase();return e==="/builder"||e==="/builder-app"||e==="/app"||e==="/apps"?typeof window>"u"?!1:!!am(window.location.pathname,window.location.search):!0}function zC(t,e){if(!(typeof window>"u"))try{const r=window.localStorage.getItem(RI(t,e));if(!r)return;const n=JSON.parse(r);return n&&typeof n=="object"?n:void 0}catch{return}}function U7(t,e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(RI(t,e),JSON.stringify(r))}catch{}}function z7(t,e){if(!(typeof window>"u"))try{return window.localStorage.getItem(II(t,e))?.trim()||void 0}catch{return}}function V7(t,e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(II(t,e),r)}catch{}}function G7(t){let e=2166136261;const r=s=>{for(let i=0;i<s.length;i++)e^=s.charCodeAt(i),e=Math.imul(e,16777619)>>>0},n=Object.keys(t).sort((s,i)=>s.localeCompare(i));for(const s of n){const i=t[s];!i||i.type!=="file"||(r(s),r(` 495`),i.isBinary?r("[binary]"):typeof i.content=="string"&&r(i.content),r(` 496`))}return e.toString(16).padStart(8,"0")}function q7(t,e){const n=Array.from(new Map(t.map(o=>[`${o.file}:${o.type}:${o.line}:${o.ruleId}`,o])).values()).slice(0,120).map(o=>({file:o.file,type:o.type,severity:o.severity,message:o.message,suggestion:o.suggestion,line:o.line})),s=Array.from(new Set(n.map(o=>o.file))),i=8e3,a=s.slice(0,30).map(o=>{const l=e[o],u=(l?.type==="file"&&typeof l.content=="string"?l.content:"").slice(0,i),d=o.split(".").pop()||"txt";return`### ${o} 497\`\`\`${d} 498${u} 499\`\`\``}).join(` 500 501`);return`You are a security engineer. The following project contains security issues detected during an automated security audit. Fix the vulnerabilities while preserving the functionality of the application. 502 503Requirements: 504- Modify only files that need security fixes. 505- Keep current UX and behavior unless required for security. 506- Prefer minimal, production-safe changes. 507- Do not rewrite entire files. Make the smallest possible edit around each warning. 508- Preserve existing JSX/TSX exactly outside the affected security line: do not rename components, change tag casing, convert self-closing tags, or normalize unrelated markup. 509- Keep the edited files syntactically valid and buildable. 510- For IFRAME_NO_SANDBOX warnings, only add a sandbox attribute to the existing iframe tag unless another edit is strictly required. 511 512Security warnings: 513\`\`\`json 514${JSON.stringify(n,null,2)} 515\`\`\` 516 517Affected files and current contents: 518${a}
518 519`}const VC=x.memo(({fileHistory:t,onSelectFile:e})=>{const r=Object.entries(t),n=r.length>0,[s,i]=x.useState(""),a=x.useMemo(()=>r.filter(([o])=>o.toLowerCase().includes(s.toLowerCase())),[r,s]);return f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(Ug,{className:"relative",children:({open:o})=>f.jsxs(f.Fragment,{children:[f.jsxs(Ug.Button,{className:"flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg bg-bolt-elements-background-depth-2 hover:bg-bolt-elements-background-depth-3 transition-colors text-bolt-elements-item-contentDefault",children:[f.jsx("span",{children:"File Changes"}),n&&f.jsx("span",{className:"w-5 h-5 rounded-full bg-accent-500/20 text-accent-500 text-xs flex items-center justify-center border border-accent-500/30",children:r.length})]}),f.jsx(r3,{show:o,enter:"transition duration-100 ease-out",enterFrom:"transform scale-95 opacity-0",enterTo:"transform scale-100 opacity-100",leave:"transition duration-75 ease-out",leaveFrom:"transform scale-100 opacity-100",leaveTo:"transform scale-95 opacity-0",children:f.jsxs(Ug.Panel,{className:"absolute right-0 z-20 mt-2 w-80 origin-top-right rounded-xl bg-bolt-elements-background-depth-2 shadow-xl border border-bolt-elements-borderColor",children:[f.jsxs("div",{className:"p-2",children:[f.jsxs("div",{className:"relative mx-2 mb-2",children:[f.jsx("input",{type:"text",placeholder:"Search files...",value:s,onChange:l=>i(l.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor focus:outline-none focus:ring-2 focus:ring-blue-500/50"}),f.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary",children:f.jsx("div",{className:"i-ph:magnifying-glass"})})]}),f.jsx("div",{className:"max-h-60 overflow-y-auto",children:a.length>0?a.map(([l,c])=>{const u=l.split(".").pop()||"",d=E3(u);return f.jsx("button",{onClick:()=>e(l),className:"w-full px-3 py-2 text-left rounded-md hover:bg-bolt-elements-background-depth-1 transition-colors group bg-transparent",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"shrink-0 w-5 h-5 text-bolt-elements-textTertiary",children:[["typescript","javascript","jsx","tsx"].includes(d)&&f.jsx("div",{className:"i-ph:file-js"}),["css","scss","less"].includes(d)&&f.jsx("div",{className:"i-ph:paint-brush"}),d==="html"&&f.jsx("div",{className:"i-ph:code"}),d==="json"&&f.jsx("div",{className:"i-ph:brackets-curly"}),d==="python"&&f.jsx("div",{className:"i-ph:file-text"}),d==="markdown"&&f.jsx("div",{className:"i-ph:article"}),["yaml","yml"].includes(d)&&f.jsx("div",{className:"i-ph:file-text"}),d==="sql"&&f.jsx("div",{className:"i-ph:database"}),d==="dockerfile"&&f.jsx("div",{className:"i-ph:cube"}),d==="shell"&&f.jsx("div",{className:"i-ph:terminal"}),!["typescript","javascript","css","html","json","python","markdown","yaml","yml","sql","dockerfile","shell","jsx","tsx","scss","less"].includes(d)&&f.jsx("div",{className:"i-ph:file-text"})]}),f.jsx("div",{className:"flex-1 min-w-0",children:f.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f.jsxs("div",{className:"flex flex-col min-w-0",children:[f.jsx("span",{className:"truncate text-sm font-medium text-bolt-elements-textPrimary",children:l.split("/").pop()}),f.jsx("span",{className:"truncate text-xs text-bolt-elements-textTertiary",children:l})]}),(()=>{const{additions:h,deletions:m}=(()=>{if(!c.originalContent)return{additions:0,deletions:0};const g=c.originalContent.replace(/\r\n/g,` 520`),p=c.versions[c.versions.length-1]?.content.replace(/\r\n/g,` 521`)||"";return g===p?{additions:0,deletions:0}:H1(g,p,{newlineIsToken:!1,ignoreWhitespace:!0,ignoreCase:!1}).reduce((v,_)=>(_.added&&(v.additions+=_.value.split(` 522`).length),_.removed&&(v.deletions+=_.value.split(` 523`).length),v),{additions:0,deletions:0})})();return(h>0||m>0)&&f.jsxs("div",{className:"flex items-center gap-1 text-xs shrink-0",children:[h>0&&f.jsxs("span",{className:"text-green-500",children:["+",h]}),m>0&&f.jsxs("span",{className:"text-red-500",children:["-",m]})]})})()]})})]})},l)}):f.jsxs("div",{className:"flex flex-col items-center justify-center p-4 text-center",children:[f.jsx("div",{className:"w-12 h-12 mb-2 text-bolt-elements-textTertiary",children:f.jsx("div",{className:"i-ph:file-dashed"})}),f.jsx("p",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:s?"No matching files":"No modified files"}),f.jsx("p",{className:"text-xs text-bolt-elements-textTertiary mt-1",children:s?"Try another search":"Changes will appear here as you edit"})]})})]}),n&&f.jsx("div",{className:"border-t border-bolt-elements-borderColor p-2",children:f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(a.map(([l])=>l).join(` 524`)),Se("File list copied to clipboard",{icon:f.jsx("div",{className:"i-ph:check-circle text-accent-500"})})},className:"w-full flex items-center justify-center gap-2 px-3 py-1.5 text-sm rounded-lg bg-bolt-elements-background-depth-1 hover:bg-bolt-elements-background-depth-3 transition-colors text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary",children:"Copy File List"})})]})})]})})})}),K7=x.memo(({chatStarted:t,isStreaming:e,isFollowUpRequest:r=!1,buildJob:n,onCancelBuild:s,metadata:i,updateChatMestaData:a,setSelectedElement:o,activePlanId:l,dreamWeaverToken:c,newsletterPreviewContent:u})=>{gu.trace("Workbench");
524const[d,h]=x.useState(!1),[m,b]=x.useState({}),g=x.useMemo(()=>Zl(j.previews,ne=>ne.some(me=>me.ready)),[]),p=We(g),y=We(j.previewVisible),v=We(j.showWorkbench),_=We(j.selectedFile),w=We(j.currentDocument),C=We(j.unsavedFiles),A=We(j.files),E=We(j.userVisibleFiles),S=We(j.currentView),{showChat:k,previewLocked:O,started:T,historyRestoring:R}=We(Ve),N=v||!k,M=typeof window<"u"?window.location.pathname:"",B=typeof window<"u"?window.location.search:"",U=!!u||M==="/newsletter"||M.startsWith("/newsletter/"),[X,oe]=x.useState(()=>typeof window<"u"?Rb(window.location.search):!1),L=`${M}${B}`||"root",F=M.startsWith("/builder")||M.startsWith("/builder-app")||M==="/"||M==="/app"||M==="/apps"||M.startsWith("/app/")||M.startsWith("/apps/")||M.startsWith("/chat/")||M==="/newsletter"||M.startsWith("/newsletter/"),V=M.startsWith("/builder")||M.startsWith("/builder-app"),Z=M==="/newsletter"||M.startsWith("/newsletter/")?"newsletter":M.startsWith("/builder")||M.startsWith("/builder-app")?"site":"app",[K,ie]=x.useState(0),se=We(j.previews),fe=se[K],Y=We(j.restoreProgress),[I,z]=x.useState(!1),[q,ae]=x.useState(),[ee,le]=x.useState(!1),[ve,ye]=x.useState(!1),[Ae,we]=x.useState(!1),[pe,Ye]=x.useState(!1),[ft,pt]=x.useState("overview"),[Lt,nt]=x.useState(null);x.useEffect(()=>{const ne=new URLSearchParams(B).get("admin");!ne||!["overview","domains","analytics"].includes(ne)||(pt(ne),nt(null),Ye(!0))},[L]);const[xt,ct]=x.useState(!1),[_r,ht]=x.useState(null),[Pe,be]=x.useState(!1),[Te,Ne]=x.useState(!1),[Fe,Fr]=x.useState([]),[Jr,Dt]=x.useState(null),[Yt,Os]=x.useState(!1),[ci,Yn]=x.useState(!1),[$n,lt]=x.useState(0),[bs,wn]=x.useState(0),[Bn,an]=x.useState(!1),[vs,ys]=x.useState(null),[Fn,Ir]=x.useState({diff:null,preview:null}),Wn=x.useRef(null),[Hn,is]=x.useState({isDeviceModeOn:!1,isFullscreen:!1,isWindowOptionsOpen:!1,isInspectorMode:!1}),rn=x.useRef(void 0),Jt=x.useRef(null),xr=x.useRef(null),Mt=x.useRef(null),Gs=x.useRef(null),ir=x.useRef(null),Ai=x.useRef(!!e),Xn=x.useRef(!1),os=x.useRef(!1),Ur=We(sp),ui=We(j.artifacts),nn=We(j.activeProgressMessageId),St=x.useMemo(()=>Vn($C(i?.gitUrl)),[i?.gitUrl]),Ei=i?.published_origin||i?.publishedOrigin,Tn=!!(St&&R7(i?.gitUrl)&&!I7(Ei)&&(i?.publishedDomain||Ei)),fr=x.useMemo(()=>Al(i?.publishedDomain),[i?.publishedDomain]),Sn=x.useMemo(()=>kn(i?.appId||i?.app_id||"")||void 0,[i?.appId,i?.app_id]),kr=x.useMemo(()=>H7(M),[M]),[Ot,Or]=x.useState(St),[zr,Pr]=x.useState(fr),[as,$i]=x.useState(Sn),[jt,_s]=x.useState(null),[Rn,jr]=x.useState(void 0),[wr,In]=x.useState(void 0),Xt=St||Ot||kr,ur=Sn||as,ls=(!!St||!!Ot||!!fr||!!zr)&&Xt?ni(Xt):void 0,ln=fr||zr||ls,Gr=x.useMemo(()=>B7(Ur),[Ur]),Bi=x.useMemo(()=>[i?.primaryArtifactId,j.firstArtifact?.id,...Object.values(ui).map(me=>me?.id),nn?ui[nn]?.id:void 0].find(me=>v7(me)),[nn,i?.primaryArtifactId,ui]),br=x.useMemo(()=>{const ne=kn(Xt||kr||Gr||"")||void 0,me=Nb(Xt||kr||Gr||ne||"my_app"),Ee=Kt(A,kb);return IC(Ee,me,ne)},[Xt,A,kr,Gr]),Tr=Bi,Vt=x.useMemo(()=>_I({artifactId:Tr,appSlug:br.app.slug,fallback:Xt||kr||Gr}),[Tr,Xt,kr,Gr,br.app.slug]),Qr=x.useMemo(()=>m_({persistedPrimaryArtifactId:i?.primaryArtifactId||Tr,persistedWorkspaceTitle:i?.workspaceTitle,originalArtifact:Tr?{id:Tr,title:i?.workspaceTitle}:null,fallbackTitle:Nb(Xt||kr||Gr||Vt)}),[Tr,Vt,Xt,i?.primaryArtifactId,i?.workspaceTitle,kr,Gr]),Ar=Qr||Ur?.trim()||"Current Project",cs=x.useCallback(async ne=>{const me=ne.trim();!me||!a||await a({...i||{},primaryArtifactId:i?.primaryArtifactId||Tr,workspaceTitle:me})},[Tr,i,a]),Ut=am(M,B)||n?.workspaceId||null,xs=ln||Gr||Vn(Tr),Nr=x.useMemo(()=>ur||Pb({artifactId:Tr,appSlug:br.app.slug,fallback:Xt||kr||Gr||Ut||void 0}),[Tr,Ut,Xt,ur,kr,Gr,br.app.slug]),js=fr,pn=!!js,te=l||Rn,De=c||wr,je=V?o7:s7,Ge=V?a7:i7,$t=x.useMemo(()=>Qn(i?.customDomain||i?.custom_domain||i?.domainName||i?.domain_name),[i?.customDomain,i?.custom_domain,i?.domainName,i?.domain_name]),[qe,Bt]=x.useState($t);x.useEffect(()=>{$t&&Bt($t)},[$t]),x.useEffect(()=>{Sn&&$i(Sn)},[Sn]),x.useEffect(()=>{if(typeof window>"u")return;const ne=me=>{const Ie=me.detail;!Ie||Ie.integrationId!=="stripe"||(pt("integrations"),nt({...Ie,requestId:Date.now()}),Ye(!0))};
524return window.addEventListener(Ty,ne),()=>{window.removeEventListener(Ty,ne)}},[]);const Lr=x.useCallback((ne,me,Ee)=>{const Ie=Vn(ne);if(!Ie||!M||!Ac(M))return;const $e=ni(me)||Al(Ee);U7(M,On.get()?.email,{repoName:Ie,subdomain:$e,domain:Ee})},[M]),Nn=x.useCallback(ne=>{const me=Vn(ne.repoName);if(!me)return;const Ee={...ne,repoName:me,appId:kn(ne.appId||"")||void 0,domain:Qn(ne.domain||"")||void 0,subdomain:ni(ne.subdomain)||Al(ne.domain)};Gs.current=Ee,_s(Ee),Or(Ee.repoName),Ee.appId&&$i(Ee.appId),Ee.subdomain&&Pr(Ee.subdomain),Lr(Ee.repoName,Ee.subdomain,Ee.domain)},[Lr]),Ln=x.useCallback(async ne=>{const me=Gs.current||jt;if(me?.repoName)return me;const Ee=[Sn,as,Vt,br.app.slug,kn(ne||""),kn(Xt||"")].filter(ze=>!!ze),Ie=[...new Set(Ee)],$e=Ie.length>0?Ie:[void 0];if(!Ut&&$e.length===1&&!$e[0])return null;const Be=await jf();for(const ze of $e){const Qe=new URLSearchParams;if(ze&&Qe.set("appId",ze),Ut&&Qe.set("chatId",Ut),!Qe.toString())continue;const gt=await fetch(`/api/runtime/projects?${Qe.toString()}`,{headers:vg({Authorization:`Bearer ${Be}`})}),Q=await gt.json().catch(()=>null);if(!gt.ok||!Q?.success)throw new Error(Q?.error||Q?.details||"Unable to read saved project publish target.");const dt=Q.project;if(!dt)continue;const rt=Vn(dt.repoName||"");if(!rt)continue;const Br=Qn(dt.publishedDomain||dt.deployedUrl||dt.publishedOrigin||""),sn=Qn(dt.customDomain||dt.domainName||""),Me=Al(Br)||FC(rt,On.get()?.email);return sn&&Bt(sn),{repoName:rt,appId:kn(dt.appId||"")||void 0,domain:Br,subdomain:Me}}return null},[Vt,Sn,Ut,Xt,as,jt,br.app.slug]),qs=x.useCallback(async ne=>{const me=Qn(ne||"");if(!me)return null;const Ee=await fetch("/api/cloudflare-subdomain",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"lookup",targetHostname:me,zoneName:Ge})}),Ie=await Ee.json();if(!Ee.ok||!Ie.success)throw new Error(Ie.error||"Unable to look up the existing published app target.");if(!Ie.found)return null;const $e=Qn(Ie.domain||me),Be=Vn(Ie.workerService||""),ze=Al($e);return!Be||Be===OC?null:{repoName:Be,domain:$e,subdomain:ze}},[Ge]),Sr=x.useCallback(async ne=>{const me=Vn(St||Ot||""),Ee=ni(ne.subdomain||""),Ie=Qn(ne.domain),$e=Qn(i?.publishedDomain),Be=js||Al($e),ze=Be?`${Be}.${Ge}`:void 0,Qe=!!Be;if(me)return{repoName:me,appId:ur,domain:Qe?$e||ze:Ie,subdomain:Qe?Be:Ee||ln};try{const rt=await Ln(ne.fallbackRepoName);if(rt?.repoName)return Nn(rt),console.info("[publish.target] recovered-runtime-project-target",{repoName:rt.repoName,appId:rt.appId||null,domain:rt.domain||null,subdomain:rt.subdomain||null}),rt}catch(rt){console.warn("[publish.target] runtime-project-lookup.failed",{error:rt instanceof Error?rt.message:String(rt)})}const gt=(Qe?Be:Ee)||ni(ln||""),Q=(Qe?$e||ze:Ie)||(gt?`${gt}.${Ge}`:void 0);if(!Q||!pn){const rt=(ne.fallbackRepoName||"").trim();return rt?{repoName:rt,appId:ur,subdomain:gt||void 0,domain:Q}:null}try{const rt=await qs(Q);if(rt?.repoName)return Nn(rt),console.info("[publish.target] recovered-locked-domain-target",{repoName:rt.repoName,appId:rt.appId||null,domain:rt.domain,subdomain:rt.subdomain||null}),rt}catch(rt){console.warn("[publish.target] locked-domain-lookup.failed",{domain:Q,error:rt instanceof Error?rt.message:String(rt)})}const dt=(ne.fallbackRepoName||"").trim();return dt?{repoName:dt,appId:ur,subdomain:gt||void 0,domain:Q}:null},[Nn,St,ln,ur,pn,js,qs,Ln,i?.publishedDomain,Ot,Ge]),or=x.useCallback(()=>{const ne=j.files.get();return G7(ne)},[]),Ks=x.useCallback(()=>{if(!M||!Ac(M))return!0;const ne=z7(M,On.get()?.email);return ne?ne!==or():!0},[M,or]),Ys=x.useCallback(()=>{!M||!Ac(M)||V7(M,On.get()?.email,or())},[M,or]),Vr=x.useCallback(async()=>{const ne=!!j.currentDocument.get(),me=j.unsavedFiles.get().size;!ne&&me===0||(ne&&await j.saveCurrentDocument(),me>0&&await j.saveAllFiles())},[]),Xs=x.useCallback(async(ne,me)=>{const Ee=kn(ne)||"my_app",Ie=kn(me?.appId)||"",$e=Nb(ne),Be=Qr||$e,ze=Kt(j.files.get(),kb),Qe=IC(ze,Be,Ee),gt=Pb({artifactId:Tr,appSlug:Qe.app.slug,fallback:ne||Be}),Q=Ie||gt,dt=F7(Qe.app.name)||W7(Qe.app.name)||Qe.app.name===$e,rt={...Qe,app:{n
524ame:dt?Be:Qe.app.name||Be,slug:Q}},Br=Kf(rt);(!ze.trim()||rt.app.name!==Qe.app.name||rt.app.slug!==Qe.app.slug)&&(await j.writeFile(kb,Br),await j.writeFile(HG,Br));const sn=j.files.get(),Me=Kt(sn,"index.html");if(Me){const yt=JG(Me,rt.app.name);yt!==Me&&await j.writeFile("index.html",yt)}return rt.app.slug},[Tr,Qr]),ki=x.useCallback(async ne=>{const me=[{path:h7,repair:CI},{path:f7,repair:AI},{path:p7,repair:SI},{path:m7,repair:EI},{path:g7,repair:Ie=>oq(nq(Ie),ne||"")}];let Ee=!1;for(const Ie of me){const $e=Kt(j.files.get(),Ie.path);if(!$e)continue;const Be=Ie.repair($e);Be!==$e&&(await j.writeFile(Ie.path,Be),Ee=!0)}Ee&&j.requestWorkspacePersistence("managed Google auth publish repair",1,"admin-settings")},[]),ws=x.useCallback(async ne=>{Ne(!0);try{ne?.flushChanges!==!1&&await Vr();const me=j.files.get(),Ee=Dq(me),Ie=performance.now(),$e=Mq(Ee),Be=performance.now()-Ie;return Fr($e),Dt(jq(Ee.length,Be)),Os(!1),$e}finally{Ne(!1)}},[Vr]),Dn=x.useCallback(async ne=>{const me=new Map;for(const Be of ne){const ze=me.get(Be.file)||[];ze.push(Be),me.set(Be.file,ze)}const Ee=j.files.get();let Ie=0,$e=0;for(const[Be,ze]of me.entries()){const Qe=Kt(Ee,Be);if(!Qe)continue;const gt=Uq(Qe,ze);gt.appliedCount===0||gt.content===Qe||(await j.writeFile(Be,gt.content),Ie+=1,$e+=gt.appliedCount)}return Ie>0&&(j.requestWorkspacePersistence("security audit autofix",Ie,"admin-settings"),j.requestPreviewRefresh(),j.refreshAllPreviews()),{updatedFileCount:Ie,appliedFixCount:$e}},[]),Fi=x.useCallback(async()=>{let ne=Fe;if(ne.length===0){Se.info("No security issues to fix.");return}let me=0;try{if(me=(await Dn(ne)).appliedFixCount,me>0&&(ne=await ws({flushChanges:!1}),ne.length===0)){we(!1),ye(!1),Se.success(`${me} security issue${me===1?"":"s"} fixed automatically.`);return}}catch($e){console.warn("Automatic security autofix failed; falling back to Genie repair prompt:",$e)}const Ee=j.files.get(),Ie=q7(ne,Ee);typeof window<"u"&&window.dispatchEvent(new CustomEvent(Py,{detail:{prompt:Ie}})),Ve.setKey("showChat",!0),we(!1),ye(!1),Se.info(me>0?`${me} security issue${me===1?"":"s"} fixed automatically. Sent ${ne.length} remaining issue${ne.length===1?"":"s"} to Genie.`:"Security fix request sent to Genie.")},[Dn,ws,Fe]),G=x.useCallback(()=>{const ne=Fe.filter(Oq).length;if(ne>0){Se.error(`${ne} blocking security issue${ne===1?"":"s"} must be fixed before publishing.`);return}Os(!0),we(!1),ye(!0)},[Fe]),ce=x.useCallback(()=>{we(!0)},[]);x.useEffect(()=>{Gs.current=null,_s(null)},[L]),x.useEffect(()=>{St&&Or(St)},[St]),x.useEffect(()=>{fr&&Pr(fr)},[fr]);const xe=ne=>{if(!ne)return!1;const me=ne.toLowerCase();return me.endsWith(".cloudmysite.net")||me.endsWith(".cloudmysite.app")||me.includes("workers.dev")};x.useEffect(()=>{let ne=!1;async function me(){try{if(l||c)return;const Ee=On.get()?.email;if(!Ee)return;const Ie=await WG(Ee);if(!Ie||!Array.isArray(Ie))return;const $e=(dt="")=>(dt||"").toString().trim().toLowerCase(),Be=M?.startsWith("/builder")||M?.startsWith("/builder-app"),Qe=Ie.filter(dt=>{const rt=$e(dt.product_type||"");return rt.includes("genie")&&(rt.includes("genie ai")||rt.includes("genie-builder")||rt.includes("genie-ai")||rt.includes("genie builder"))}).filter(dt=>{const rt=$e(dt.product_type||"");return Be?rt.includes("builder"):rt.includes("ai")}),gt=zr||ln||"",Q=dt=>dt&&dt.split(".")[0]?.toLowerCase()||"";for(const dt of Qe){const rt=dt.domain_name||dt.domain||"",Br=Q(rt);if(Br&&Br===gt){if(ne)return;jr(String(dt.id)),Be&&In(String(dt.id));const sn=dt.custom_domain;if(sn){const Me=sn.toLowerCase();xe(Me)||Bt(Me)}return}}}catch(Ee){console.error("detectFromEmail failed",Ee)}}return me(),()=>{ne=!0}},[l,c,M,zr,ln]),x.useEffect(()=>{T||Ac(M)||(St||Or(void 0),fr||Pr(void 0))},[T,M,B,St,fr]),x.useEffect(()=>{const ne=typeof window<"u"?r_(M,window.location.search):M;if(!M||Mt.current===ne)return;if(Mt.current=ne,!Ac(M)){St||Or(void 0),fr||Pr(void 0);return}const me=zC(M,On.get()?.email),Ee=Vn(me?.repoName);Ee&&!St&&Or(Ee),me?.subdomain&&!fr&&Pr(me.subdomain)},[M,B,St,fr]),x.useEffect(()=>{const ne=Qn(i?.publishedDomain);!ne||St||Ot||(async()=>{try{const me=await qs(ne);if(!me?.repoName)return;Nn(me)}catch{}})()},[Nn,St,qs,i?.publishedDomain,Ot]),x.useEffect(()=>{St||Ot||(async()=>{try{const ne=await Ln();ne?.repoName&&Nn(ne)}catch{}})()},[Nn,St,Ln,Ot]),x.useEffect(()=>{if(!Tn||ln||!Xt)return;const ne=Xt,me=`${ne}:${Ge}`;Jt.current!==me&&(Jt.current=me,(async()=>{try{const Ee=await fetch("/api/cloudflare-subdomain",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"lookup",workerService:ne,zoneName:Ge})}),Ie=await Ee.json();if(!Ee.ok||!Ie.success||!Ie.found||!Ie.domain)return;const $e=Al(Ie.domain);if(!$e)return;Ot||Or(Xt),Pr($e),Lr(Xt,$e,Ie.domain),a&&i?.publishedDomain!==Ie.domain&&i?.gitUrl&&await a({...i||{},gitUrl:i.gitUrl,publishedDomain:Ie.domain})}catch{}})())},[Xt,ln,Tn,i,a,Lr,Ot,Ge]),x.useEffect(()=>{if(!ci){lt(0),wn(0);return}lt(0),wn(0);const ne=window.setInterval(()=>{lt(Ee=>(Ee+1)%Tb.length)},5e3),me=window.setInterval(()=>{wn(Ee=>Ee+1)},1e3);return()=>{window.clearInterval(ne),window.clearInterval(me)}},[ci]),x.useEffect(()=>{const ne=new URLSearchParams(window.location.search),me=ne.get("payment"),Ee=ne.get("token"),Ie=ne.get("paypal"),$e=ne.get("recordId"),Be=ne.get("razorpay");me==="success"&&Ee&&(rn.current=Ee,$G(Ee).then(ze=>{const Qe=JSON.parse(ze);Se.success(`Successfully subscribed to ${Qe.product_name}!`),ys({status:Qe.payment_status,orderId:Qe.id,productName:Qe.product_name,amount:(Qe.total_amount_from_stripe/100).toFixed(2),currency:Qe.currency_used?.toUpperCase()??"USD",createdAt:Qe.created_at}),an(!0)}).catch(()=>{Se.error("Failed to verify payment")}).finally(()=>{ne.delete("checkout"),ne.delete("token"),window.history.replaceState({},"",window.location.pathname)})),Ie==="success"&&$e&&(rn.current=$e,BG({id:$e,product_type:"static-website-html",paypalToken:Ee}).then(gt=>{if(gt.startsWith("Redirect :")){const dt=gt.replace("Redirect :","").trim();window.location.href=dt;return}const Q=JSON.parse(gt);Se.success(`Successfully subscribed to ${Q.product_name}!`),ys({status:Q.payment_status,orderId:Q.id,productName:Q.product_name,amount:Q.product_price??"0.00",currency:"USD",createdAt:Q.created_at}),an(!0)}).catch(()=>{Se.error("Failed to verify PayPal payment")}).finally(()=>{ne.delete("paypal"),ne.delete("token"),ne.delete("recordId"),window.history.replaceState({},"",window.location.pathname)})),Be==="success"&&Ee&&(rn.current=Ee,bO(Ee).then(ze=>{const Qe=JSON.parse(ze);Se.success(`Successfully subscribed to ${Qe.product_name}!`),ys({status:Qe.payment_status,orderId:Qe.id,productName:Qe.product_name,amount:Qe.product_price??"0.00",currency:"INR",createdAt:Qe.created_at}),sessionStorage.removeItem("razorpay:returnUrl"),an(!0)}).catch(()=>{Se.error("Failed to verify Razorpay payment")}).finally(()=>{ne.delete("razorpay"),ne.delete("token"),window.history.replaceState({},"",window.location.pathname)}))},[]);const Je=async()=>{an(!1);try{const ne=await ml({token:rn.current});ne&&typeof ne=="object"&&ne.noChanges?Se.info("No changes to publish."):Se.success("Published successfully")}catch{Se.error("Publishing failed")}finally{rn.current=void 0,ys(null)}};x.useEffect(()=>{if(!fe||!fe.ready){ae(void 0);return}const{baseUrl:ne}=fe;ae(ne)},[fe]);const It=Ng(1024),wt=Ng(640),Gt=Ng(1280),Qt=!It,Nt=F&&It,pr=x.useMemo(()=>
524{if(!R)return!1;const ne=!!Y?.some(Ie=>Ie.status==="running"),me=!!Y?.some(Ie=>Ie.status==="pending"),Ee=!!Y?.some(Ie=>Ie.status==="failed");return ne||me&&!Ee},[R,Y]),Ft=!U&&(O||pr),ot=pr?"Preview will be available once project startup finishes.":"Preview will be available once the first draft finishes.",qt=x.useCallback(ne=>{j.currentView.set(ne)},[]);x.useEffect(()=>{U&&S!=="preview"&&qt("preview")},[U,S,qt]);const Zt=S,mn=Fn.diff===L,cn=Fn.preview===L,Ss=Zt==="diff"||mn,Js=Zt==="preview"||cn,ro=x.useMemo(()=>Zt!=="code"||!t||Pe||I?!1:!!e||R||pr||!p,[I,t,Zt,p,R,Pe,e,pr]);x.useEffect(()=>{Zt!=="diff"||mn||Ir(ne=>ne.diff===L?ne:{...ne,diff:L})},[Zt,mn,L]),x.useEffect(()=>{Zt!=="preview"||cn||Ir(ne=>ne.preview===L?ne:{...ne,preview:L})},[Zt,cn,L]),x.useEffect(()=>{Zt!=="preview"&&Hn.isWindowOptionsOpen&&Wn.current?.closeWindowOptions()},[Zt,Hn.isWindowOptionsOpen]),x.useEffect(()=>{S==="admin"&&(Ye(!0),j.currentView.set("code"))},[S]),x.useEffect(()=>{ir.current=null,Xn.current=!1,os.current=!1},[M]),x.useEffect(()=>{typeof window>"u"||oe(Rb(window.location.search))},[L]),x.useEffect(()=>{if(typeof window>"u")return;const ne=()=>{oe(Rb(window.location.search))};return window.addEventListener("popstate",ne),()=>{window.removeEventListener("popstate",ne)}},[]),x.useEffect(()=>{const ne=()=>{le(!0)};return window.addEventListener("cms:open-workspace-upgrade",ne),()=>{window.removeEventListener("cms:open-workspace-upgrade",ne)}},[]),x.useEffect(()=>{Y?.length&&(!p&&!y||j.markRestorePreviewReady())},[p,y,Y]),x.useEffect(()=>{R&&(pr&&!p||Ve.setKey("historyRestoring",!1))},[p,R,pr]),x.useEffect(()=>{R&&(os.current=!0)},[R]),x.useEffect(()=>{if(!Qt){R||(os.current=!1);return}os.current&&(!p||Ft||(S!=="preview"&&qt("preview"),ir.current=M||"root",j.requestPreviewRefresh(),os.current=!1))},[p,R,Ft,M,S,qt,Qt]),x.useEffect(()=>{const ne=Ai.current,me=!!e;if(Ai.current=me,!Qt){Xn.current=!1;return}if(ne&&!me&&(Xn.current=!0),!(!Xn.current||me)){if(S==="preview"){Xn.current=!1;return}!p||Ft||(qt("preview"),ir.current=M||"root",Xn.current=!1)}},[p,Ft,e,M,S,Qt]),x.useEffect(()=>{j.setDocuments(E)},[E]);const Wi=x.useCallback(ne=>{j.setCurrentDocumentContent(ne.content)},[]),rr=x.useCallback(ne=>{j.setCurrentDocumentScrollPosition(ne)},[]),Dr=x.useCallback(ne=>{j.setSelectedFile(ne)},[]),wa=x.useCallback(()=>{j.saveCurrentDocument().then(()=>{j.refreshAllPreviews()}).catch(()=>{Se.error("Failed to update file content")})},[]),Sa=x.useCallback(()=>{j.resetCurrentDocument()},[]);x.useCallback(async()=>{h(!0);try{const ne=await window.showDirectoryPicker();await j.syncFiles(ne),Se.success("Files synced successfully")}catch(ne){console.error("Error syncing files:",ne),Se.error("Failed to sync files")}finally{h(!1)}},[]);const Ca=x.useCallback(ne=>{j.setSelectedFile(ne),j.currentView.set("diff")},[]);x.useCallback(()=>{const ne=Object.entries(A),me=ne.some(([Ie])=>Ie.includes(".eleventy.js")||Ie.includes("eleventy.config.js")),Ee=ne.some(([Ie,$e])=>Ie.includes("package.json")&&$e&&"content"in $e&&$e.content?.includes("@11ty/eleventy"));return me||Ee},[A]);const Qs=x.useCallback(()=>{if(It){Ve.setKey("showChat",!0),j.showWorkbench.set(!1);return}N&&Ve.setKey("showChat",!k)},[N,It,k]);x.useEffect(()=>{if(typeof window>"u"||!t)return;const ne=()=>window.dispatchEvent(new Event("resize")),me=window.requestAnimationFrame(ne),Ee=window.setTimeout(ne,260);return()=>{window.cancelAnimationFrame(me),window.clearTimeout(Ee)}},[t,k,v]);const Aa=It?"Close workspace panel":k?"Hide chat panel":"Show chat panel",pl=f.jsx(iw,{content:Aa,side:"bottom",children:f.jsx("span",{className:"inline-flex",children:f.jsx(Mn,{className:"h-8 w-8 justify-center border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-0 py-0 !text-zinc-700 dark:!text-zinc-300 enabled:hover:!text-zinc-900 dark:enabled:hover:!text-white enabled:hover:!bg-bolt-elements-item-backgroundActive",disabled:!It&&!N,title:Aa,onClick:Qs,children:f.jsx("div",{className:ue(It?"i-ph:x":k?"i-ph:arrow-line-left":"i-ph:arrow-line-right","text-[17px]")})})})}),dc=x.useCallback((ne,me="replace")=>
524{if(typeof window>"u")return;const Ee=new URL(window.location.href);ne?Ee.searchParams.set(Iy,"1"):Ee.searchParams.delete(Iy);const Ie=`${Ee.pathname}${Ee.search}${Ee.hash}`,$e=`${window.location.pathname}${window.location.search}${window.location.hash}`;Ie!==$e&&(me==="push"?window.history.pushState({},"",Ie):window.history.replaceState({},"",Ie)),oe(ne)},[]),us=x.useCallback(()=>{dc(!1)},[dc]),Uo=x.useCallback(()=>{Ve.setKey("backgroundHomeActive",!1),us(),j.setPreviewDevice("responsive"),qt("code")},[us]),zo=x.useCallback(()=>{if(Ve.setKey("backgroundHomeActive",!1),us(),j.setPreviewDevice("responsive"),U){qt("preview");return}if(Ft){Se.info(ot),qt("code");return}qt("preview"),Wa.logDebug("workbench.preview.selection",{previewCount:se.length,fileCount:Object.keys(A).length}),!p&&(async()=>{await j.ensurePreviewRunningFromWorkspace({allowInitialStart:!0,reason:"preview-selection",maxAttempts:2,retryDelayMs:1500,waitForActiveStartMs:45e3,waitForPreviewMs:45e3,skipSetupCommand:!0})})().catch(ne=>{const me=ne instanceof Error?ne.message:"Unknown error";Se.error(`Unable to start preview: ${me}`)})},[us,A,p,U,Ft,ot,se.length,qt]),_o=x.useCallback(()=>{Ve.setKey("backgroundHomeActive",!1),us(),j.setPreviewDevice("responsive"),pt("overview"),nt(null),Ye(!0)},[us]),$r=x.useCallback(()=>{Ve.setKey("backgroundHomeActive",!1),us(),Ye(!1),le(!1),ct(!1),Uo()},[us,Uo]),Su=x.useCallback(ne=>{if(ne.isCurrent||Ut&&ne.workspaceId===Ut&&ne.mode===Z){$r();return}if(j1(n)){Se.info("Your current build is still running. Open it from Home or cancel it before switching projects.");return}us(),window.location.href=ih(ne.mode,ne.workspaceId)},[n,us,Ut,Z,$r]),ds=x.useCallback(()=>{Ye(!1),pt("overview"),nt(null),zo()},[zo]),Pi=x.useCallback(()=>{z(ne=>{const me=!ne;return me&&qt("code"),me})},[qt]),no=x.useCallback(()=>{typeof window>"u"||(Ve.setKey("backgroundHomeActive",!1),Ve.setKey("backgroundHomeReturnPath",""),Ve.setKey("started",!1),Ve.setKey("showChat",!0),Ve.setKey("previewLocked",!1),j.showWorkbench.set(!1),Ye(!1),le(!1),ct(!1),us(),window.location.href="/workspace")},[us]),xo=()=>{if(U){qt("preview");return}if(Ft){Se.info("Your request is being processed. Preview will refresh automatically when the build is ready."),qt("code");return}if(e){Se.info("Your request is being processed. Preview will refresh automatically when the build is ready."),qt("code");return}qt("preview"),j.requestPreviewRefresh(),j.refreshAllPreviews()},mt=x.useCallback(()=>{Wn.current?.toggleDeviceMode()},[]),Pt=x.useCallback(()=>{Wn.current?.toggleFullscreen()},[]);x.useCallback(()=>{Wn.current?.toggleWindowOptions()},[]);const ge=x.useCallback(()=>{Wn.current?.toggleInspectorMode()},[]),Ue=x.useCallback(async(ne,me,Ee,Ie)=>{const $e=Math.max(0,Ie?.initialDelayMs??0),Be=Vn(Ie?.workerService||me)||me;console.info("[publish.domain] reserve.start",{repoName:me,workerService:Be,subdomain:ne,zoneName:Ee,initialDelayMs:$e});const ze=1;for(let Qe=1;Qe<=ze;Qe++){try{console.info("[publish.domain] reserve.attempt",{repoName:me,workerService:Be,subdomain:ne,zoneName:Ee,attempt:Qe,maxAttempts:ze});const gt=await fetch("/api/cloudflare-subdomain",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reserve",subdomain:ne,workerService:Be,zoneName:Ee,projectId:Ie?.projectId,initialDelayMs:Qe===1?$e:0,retryDelayMs:jC,maxAttempts:Qe===1?Math.min(c7,10):1})}),Q=await gt.json();console.info("[publish.domain] reserve.response",{repoName:me,workerService:Be,subdomain:ne,zoneName:Ee,attempt:Qe,status:gt.status,ok:gt.ok,success:Q.success,domain:Q.domain,error:Q.error});const dt=Q.error||"Unable to reserve selected subdomain. Please choose another domain.";if(gt.ok&&Q.success&&Q.domain)return console.info("[publish.domain] reserve.success",{repoName:me,workerService:Be,subdomain:ne,zoneName:Ee,domain:Q.domain,attempt:Qe}),Q.domain;if(!UC(dt))throw new Error(dt);if(Qe>=ze)throw new Error("Deployment is still initializing on Cloudflare. Please wait a moment and try publishing again.")}catch(gt){const Q=gt instanceof Error?gt.message:String(gt);if(console.warn("[publish.domain] reserve.error",{repoName:me,workerService:Be,subdomain:ne,zoneName:Ee,attempt:Qe,error:Q}
524),!UC(Q))throw gt instanceof Error?gt:new Error(Q);if(Qe>=ze)throw new Error("Deployment is still initializing on Cloudflare. Please wait a moment and try publishing again.")}await new Promise(gt=>setTimeout(gt,jC))}throw new Error("Unable to reserve selected subdomain. Please choose another domain.")},[]),er=x.useCallback((ne,me)=>{const Ee=ni(ne),Ie=me.trim().toLowerCase().replace(/^\./,"");if(!Ee||!Ie)return;const $e=`${Ee}.${Ie}`;return Qn(i?.publishedDomain)===$e?$e:!M||!Ac(M)?void 0:Qn(zC(M,On.get()?.email)?.domain)===$e?$e:void 0},[i?.publishedDomain,M]),Ct=x.useCallback(async(ne,me,Ee,Ie)=>{const $e=er(ne,Ee);return $e&&console.info("[publish.domain] reserve.verify-saved-domain",{repoName:me,subdomain:ne,zoneName:Ee,domain:$e}),Ue(ne,me,Ee,Ie)},[er,Ue]),nr=x.useCallback(async ne=>{const me=ne.appId||Vt||kn(ne.repoName||Xt||kr||Ut||""),Ee=BC(ne.publishedDomain);if(!me)return null;const Ie=Vn(ne.repoName)||Vn($C(ne.repoUrl))||Vn(Xt)||Vn(kr)||me;try{const $e=await jf(),Be=await fetch("/api/runtime/projects",{method:"POST",headers:vg({"Content-Type":"application/json",Authorization:`Bearer ${$e}`}),body:JSON.stringify({appId:me,chatId:Ut,chatMode:Z,projectType:Z==="site"?"website_ai":"app_ai",repoName:Ie,appName:Ar,publishedDomain:ne.publishedDomain,publishedOrigin:Ee,deployedUrl:ne.publishedDomain?`https://${ne.publishedDomain}`:void 0,customDomain:qe,status:ne.publishedDomain?"published":void 0})}),ze=await Be.json().catch(()=>null);if(!Be.ok){const Qe=ze?.error||ze?.details||"Unable to save project publish metadata.";if(ze?.centralAuthRegistrationError===yd||Qe===yd)return{appId:ze?.appId||me,publishedOrigin:ze?.publishedOrigin||Ee,centralAuthRegisteredAt:null,centralAuthRegistrationError:yd,centralAuthRegistrationFailureReason:ze?.centralAuthRegistrationFailureReason||null};throw new Error(Qe)}return console.info("[publish.runtime-project] sync.success",{appId:me,chatId:Ut,repoName:Ie,publishedDomain:ne.publishedDomain||null,publishedOrigin:ze?.publishedOrigin||Ee||null,customDomain:qe||null,centralAuthRegisteredAt:ze?.centralAuthRegisteredAt||null,centralAuthRegistrationError:ze?.centralAuthRegistrationError||null,centralAuthRegistrationFailureReason:ze?.centralAuthRegistrationFailureReason||null}),{appId:ze?.appId||me,publishedOrigin:ze?.publishedOrigin||Ee,centralAuthRegisteredAt:ze?.centralAuthRegisteredAt||null,centralAuthRegistrationError:ze?.centralAuthRegistrationError||null,centralAuthRegistrationFailureReason:ze?.centralAuthRegistrationFailureReason||null}}catch($e){const Be=$e?.centralAuthRegistrationFailureReason||null;return console.warn("[publish.runtime-project] sync.failed",{appId:me,chatId:Ut,repoName:Ie,publishedDomain:ne.publishedDomain||null,error:$e instanceof Error?$e.message:String($e),centralAuthRegistrationFailureReason:Be}),Se.warn("Site published, but project domain metadata could not be saved. Please republish to retry."),{appI
524d:me,publishedOrigin:Ee,centralAuthRegisteredAt:null,centralAuthRegistrationError:null,centralAuthRegistrationFailureReason:null}}},[Vt,Ut,Z,Ar,qe,Xt,kr]),Cn=x.useCallback(async(ne,me,Ee)=>{const Ie=Ee?.appId||Vt||kn(Ee?.repoName||Xt||kr||Ut||""),$e=BC(me),ze=await nr({appId:Ee?.appId,repoName:Ee?.repoName,repoUrl:ne,publishedDomain:me});if(ze?.centralAuthRegistrationError&&Se.warn(T7(ze.centralAuthRegistrationFailureReason)),!a){console.info("[publish.metadata] skip.no-updater",{repoUrl:ne,publishedDomain:me||null,publishedOrigin:ze?.publishedOrigin||$e||null});return}const Qe=Qn(qe),gt={...i||{},gitUrl:ne,...Ie?{appId:Ie,app_id:Ie}:{},...me?{publishedDomain:me}:{},...Qe?{customDomain:Qe,custom_domain:Qe,domainName:Qe,domain_name:Qe}:{},...ze?.publishedOrigin||$e?{publishedOrigin:ze?.publishedOrigin||$e,published_origin:ze?.publishedOrigin||$e}:{},...ze?.centralAuthRegisteredAt?{centralAuthRegisteredAt:ze.centralAuthRegisteredAt,central_auth_registered_at:ze.centralAuthRegisteredAt,centralAuthRegistrationError:void 0,central_auth_registration_error:void 0}:{},...ze?.centralAuthRegistrationError?{centralAuthRegistrationError:ze.centralAuthRegistrationError,central_auth_registration_error:ze.centralAuthRegistrationError}:{}},Q=i?.publishedDomain,dt=Qn(i?.customDomain||i?.custom_domain||i?.domainName||i?.domain_name),rt=i?.app_id||i?.appId,Br=i?.published_origin||i?.publishedOrigin,sn=i?.central_auth_registered_at||i?.centralAuthRegisteredAt,Me=i?.central_auth_registration_error||i?.centralAuthRegistrationError;if(!(i?.gitUrl!==ne||!!me&&Q!==me||!!Qe&&dt!==Qe||!!Ie&&rt!==Ie||!!$e&&Br!==$e||!!ze?.centralAuthRegisteredAt&&sn!==ze.centralAuthRegisteredAt||ze?.centralAuthRegistrationError!==void 0&&Me!==ze.centralAuthRegistrationError)){console.info("[publish.metadata] skip.no-changes",{repoUrl:ne,publishedDomain:me||null,publishedOrigin:ze?.publishedOrigin||$e||null,existingGitUrl:i?.gitUrl||null,existingPublishedDomain:i?.publishedDomain||null});return}console.info("[publish.metadata] persist.start",{repoUrl:ne,publishedDomain:me||null,publishedOrigin:ze?.publishedOrigin||$e||null,appId:Ie||null,existingGitUrl:i?.gitUrl||null,existingPublishedDomain:i?.publishedDomain||null}),await a(gt),console.info("[publish.metadata] persist.success",{repoUrl:ne,publishedDomain:me||null,publishedOrigin:ze?.publishedOrigin||$e||null,appId:Ie||null})},[Vt,qe,Ut,Xt,i,kr,nr,a]),Ti=x.useCallback(async(ne,me,Ee)=>{const Ie=Ee?.appId||Vt||kn(Ee?.repoName||Xt||kr||Ut||"");if(!a){console.info("[publish.metadata] skip.r2.no-updater",{appId:Ie||null,repoName:Ee?.repoName||null,publishedDomain:me||null,deploymentId:ne.deploymentId||null});return}const $e=Qn(qe),Be=ne.deployedUrl||(me?`https://${me}`:void 0),ze={...i||{},...Ie?{appId:Ie,app_id:Ie}:{},...me?{publishedDomain:me}:{},...Be?{deployedUrl:Be,deployed_url:Be}:{},...$e?{customDomain:$e,custom_domain:$e,domainName:$e,domain_name:$e}:{},publishedOrigin:"r2",published_origin:"r2",deploymentTarget:"r2",deployment_target:"r2",...ne.deploymentId?{deploymentId:ne.deploymentId,deployment_id:ne.deploymentId}:{},...ne.sourceR2Prefix?{sourceR2Prefix:ne.sourceR2Prefix}:{},...ne.distR2Prefix?{distR2Prefix:ne.distR2Prefix}:{},...ne.framework?{framework:ne.framework}:{}};await a(ze)},[Vt,Ut,qe,Xt,i,kr,a]),Un=x.useCallback(ne=>{const me=Qn(qe)||Qn(ne||"");return me?`https://${me}`:void 0},[qe]),so=x.useCallback(async ne=>{const me=Qn(ne);!me||(Bt(me),pt("domains"),Ye(!0),!a)||Qn(i?.customDomain||i?.custom_domain||i?.domainName||i?.domain_name)===me||await a({...i||{},customDomain:me,custom_domain:me,domainName:me,domain_name:me})},[i,a]);x.useEffect(()=>{const ne=Vn(Xt||""),me=fr||zr||FC(ne,On.get()?.email),Ee=Qn(i?.publishedDomain||i?.publishedOrigin),Ie=i?.gitUrl;if(!Tn||!ne||!me||Ee||!Ie)return;const $e=`${ne}:${me}:${Ge}`;xr.current!==$e&&(xr.current=$e,(async()=>{try{console.info("[publish.domain] recovery.start",{repoName:ne,subdomain:me,zoneName:Ge});const Be=await Ct(me,ne,Ge,{projectId:ur});Or(ne),Pr(me),Lr(ne,me,Be),await Cn(Ie,Be,{appId:ur,repoName:ne}),console.info("[publish.domain] recovery.success",{repoName:ne,subdomain:me,domain:Be})}catch(Be){console.warn("[publish.domain] recovery.failed",{repoName:ne,subdomain:me,zoneName:Ge,error:Be instanceof Error?Be.message:String(Be)})}})())},[Lr,fr,Xt,ur,Ct,Tn,i?.gitUrl,i?.publishedDomain,i?.publishedOrigin,Cn,zr,Ge]);const gn=x.useCallback(async(ne,me)=>{if(D7(Pb({artifactId:Tr,appSlug:br.app.slug,fallback:ne||Xt||kr})))try{const Ie=await jf(),$e=await fetch("/api/database-bootstrap",{method:"POST",headers:vg({"Content-Type":"application/json",Authorization:`Bearer ${Ie}`}),body:JSON.stringify({projectId:me})});if(!$e.ok){const Be=await $e.json().catch(()=>null);throw new Error(Be?.error||Be?.details||"Unable to bootstrap app database table.")}}catch(Ie){console.error("App database bootstrap failed:",Ie),Se.warn("Site published, but app database bootstrap failed. Please republish to retry table creation.")}},[Tr,Xt,kr,br.app.slug]),hi=x.useCallback((ne,me)=>{ht({name:ne,price:me}),le(!1),ct(!0)},[]),ml=x.useCallback(async ne=>{const me=On.get(),Ee=ni((ne?.subdomain||"").trim()),Ie=Vn(ne?.repoName||"")?.slice(0,63);let Be=(Vn(St||Ot||"")||Ie||sx(Ee,me?.email)).trim(),ze;try{await Vr();const Qe=ni((ln||"").trim());let gt=Ee||Qe||ni(Be),dt=(ne?.domain||"").trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"").replace(/:\d+$/,"")||`${gt||Be}${je}`;const rt=await Sr({fallbackRepoName:Be,subdomain:gt,domain:dt});rt?.repoName&&(Be=rt.repoName),rt?.subdomain&&(gt=rt.subdomain),rt?.domain&&(dt=rt.domain),ze=await Xs(Be,{appId:rt?.appId||ur}),await ki(ze),console.info("[publish.checkout] start",{repoName:Be,finalSubdomain:gt||null,requestedDomain:dt,deploymentTarget:"r2",hasChanges:Ks(),metadataGitUrl:i?.gitUrl||null,metadataPublishedDomain:i?.publishedDomain||null}),be(!0),Yn(!0);const Br=dt,sn=await j.publishToR2({projectId:ze||kn(Be)||Be,sourceChatId:Ut||void 0,repoName:Be,publishedDomain:Br}),Me=Un(Br)||sn.url||(Br?`https://${Br}`:"");
524if(Or(Be),gt&&Pr(gt),Lr(Be,gt||void 0,Br),await gn(Be,ze),await Ti(sn,Br,{appId:ze,repoName:Be}),Ys(),Me)try{window.open(Me,"_blank","noopener,noreferrer")||(Se.info(`Your site is ready! Visit: ${Me}`),navigator.clipboard.writeText(Me).catch(()=>{}))}catch(yt){console.warn("Failed to open popup:",yt),Se.info(`Your site is ready! Visit: ${Me}`),navigator.clipboard.writeText(Me).catch(()=>{})}ct(!1),ht(null);return}catch(Qe){throw console.error("Error publishing app:",Qe),Qe}finally{be(!1),Yn(!1)}},[Ks,Vr,Xs,ki,Sr,ln,ur,Ot,St,je,Ge,Ys,gn,Lr,Un,Ti]),Cu=x.useCallback(async()=>{try{const ne=await ws({flushChanges:!0});if(ne.length>0){ye(!1),we(!0),Se.warn(`${ne.length} security issue${ne.length===1?"":"s"} detected before publish.`);return}ye(!0)}catch(ne){console.error("Security audit failed before publish:",ne),Se.error("Security audit failed. You can still review and publish manually."),ye(!0)}},[ws]),Ea=Tb[$n]||Tb[0],Gm=`${Math.floor(bs/60)}:${String(bs%60).padStart(2,"0")}`,qm=Math.min(100,Math.max(6,bs/l7*100));return t&&f.jsxs(ar.div,{initial:"closed",animate:v?"open":"closed",variants:_7,className:"z-workbench",children:[f.jsx("div",{className:ue("fixed w-[var(--workbench-inner-width)] z-0 transition-[left,width] duration-200 bolt-ease-cubic-bezier",{"w-full":It,"top-0 bottom-0":F&&It,"top-2 bottom-2":F&&!It,"top-[90px] bottom-6":!F,"left-0":v&&It,"left-[var(--workbench-left)]":v,"left-[100%]":!v}),children:f.jsx("div",{className:ue("absolute inset-0 lg:px-4",It?"px-0":"px-2"),children:f.jsxs("div",{className:ue("cms-workbench-bg h-full flex flex-col border border-bolt-elements-borderColor shadow-sm overflow-hidden",It?"rounded-none border-x-0 border-y-0":"rounded-lg"),children:[F?f.jsxs("div",{className:ue("cms-workbench-header-bg border-b border-bolt-elements-borderColor",Nt?"flex h-11 items-center gap-1 overflow-x-auto overflow-y-hidden px-2":"flex h-12 flex-nowrap items-center gap-2 overflow-x-auto overflow-y-hidden px-3"),children:[f.jsxs("div",{className:ue("flex min-w-0 items-center",Nt?"shrink-0 flex-nowrap gap-1":"min-w-0 flex-1 flex-wrap gap-1.5"),children:[pl,f.jsx(Mn,{className:ue(Nt?"text-xs":"text-sm"),title:"Workspace",onClick:no,children:"Workspace"}),f.jsx(Mn,{className:ue("h-8 w-8 justify-center px-0",Nt?"text-xs":"text-sm",{"!bg-bolt-elements-item-backgroundAccent !text-bolt-elements-item-contentAccent":Zt==="preview"}),title:"Preview",disabled:Ft,onClick:zo,children:f.jsx("div",{className:"i-ph:eye text-[17px]"})}),f.jsx(Mn,{className:ue(Nt?"text-xs":"text-sm",{"!bg-bolt-elements-item-backgroundAccent !text-bolt-elements-item-contentAccent":pe}),onClick:_o,children:"Admin"}),!U&&!Nt&&f.jsxs(f.Fragment,{children:[f.jsx(iw,{content:"Back to Workspace",side:"bottom",children:f.jsx("span",{children:f.jsx(Mn,{className:"h-8 w-8 justify-center px-0",title:"Back to Workspace",onClick:no,children:f.jsx("div",{className:"i-ph:arrow-left text-[17px]"})})})}),f.jsx("div",{title:"Switch device mode",children:f.jsx(Mn,{className:ue("h-8 w-8 justify-center",{"!bg-bolt-elements-item-backgroundAccent !text-bolt-elements-item-contentAccent":Hn.isDeviceModeOn}),disabled:Ft,onClick:mt,children:f.jsx("div",{className:"i-ph:devices text-[17px]"})})}),f.jsx("div",{title:Hn.isInspectorMode?"Disable element inspector":"Enable element inspector",children:f.jsx(Mn,{className:ue("h-8 w-8 justify-center",{"!bg-bolt-elements-item-backgroundAccent !text-bolt-elements-item-contentAccent":Hn.isInspectorMode}),disabled:Ft,onClick:ge,children:f.jsx("div",{className:"i-ph:cursor-click text-[17px]"})})}),f.jsx("div",{title:Hn.isFullscreen?"Exit full screen":"Enter full screen",children:f.jsx(Mn,{className:ue("h-8 w-8 justify-center",{"!bg-bolt-elements-item-backgroundAccent !text-bolt-elements-item-contentAccent":Hn.isFullscreen}),disabled:Ft,onClick:Pt,children:f.jsx("div",{className:`${Hn.isFullscreen?"i-ph:arrows-in":"i-ph:arrows-out"} text-[17px]`})})})]})]}),f.jsxs("div",{className:ue("flex shrink-0 items-center justify-end",Nt?"gap-1 flex-nowrap":"gap-1.5 pl-2 flex-wrap"),children:[!U&&f.jsxs(Mn,{className:Nt?"text-xs":"text-sm",title:I?"Switch to simple mode":"Switch to advanced mode",onClick:Pi,children:[f.jsx("div",{className:I?"i-ph:eye-slash-duotone":"i-ph:sliders-horizontal-duotone"}),Nt?I?"Simple":"Adv":I?"Simple":"Advanced"]}),Zt==="code"&&I&&f.jsx(Mn,{className:Nt?"text-xs":"text-sm",title:"Toggle terminal",onClick:()=>{j.toggleTerminal(!j.showTerminal.get())},children:f.jsx("div",{className:"i-ph:terminal"})}),Zt==="diff"&&f.jsx(VC,{fileHistory:m,onSelectFile:Ca}),!Nt&&f.jsx(RC,{className:"h-8 w-8 justify-center"}),!U&&f.jsx(Mn,{className:ue("h-8 w-8 justify-center px-0",Nt?"text-xs":"text-sm"),title:"Refresh",onClick:xo,children:f.jsx("div",{className:"i-ph:arrow-clockwise"})}),!Nt&&!Gt&&f.jsxs(Mn,{className:"ml-1 border border-accent-500/40 text-sm text-accent-700 enabled:hover:!bg-accent-100 enabled:hover:!text-accent-900 dark:text-accent-200 dark:enabled:hover:!bg-accent-500/15 dark:enabled:hover:!text-accent-100",onClick:()=>le(!0),children:[f.jsx("div",{className:"i-ph:rocket-launch"}),"Upgrade"]}),!U&&f.jsxs(Mn,{className:ue("!bg-accent-600 enabled:hover:!bg-accent-700 !text-white enabled:hover:!text-white font-semibold px-3 py-1.5",Nt?"text-xs":"ml-1"),onClick:Cu,disabled:Pe,children:[f.jsx("div",{className:"i-ph:cloud-arrow-up"}),Pe?"Publishing...":Nt?"Pub":"Publish"]})]})]}):f.jsxs("div",{className:"cms-workbench-header-bg flex h-12 items-center border-b border-bolt-elements-borderColor px-3 gap-1.5",children:[pl,f.jsx(Tz,{selected:Zt,options:y7,setSelected:qt}),f.jsx("div",{className:"ml-auto"}),f.jsxs("div",{className:"flex overflow-y-auto",children:[f.jsxs(Mn,{className:"mr-1 text-sm",title:I?"Switch to simple mode":"Switch to advanced mode",onClick:Pi,children:[f.jsx("div",{className:I?"i-ph:eye-slash-duotone":"i-ph:sliders-horizontal-duotone"}),I?"Simple":"Advanced"]}),Zt==="code"&&I&&f.jsx(Mn,{className:"mr-1 text-sm",title:"Toggle terminal",onClick:()=>{j.toggleTerminal(!j.showTerminal.get())},children:f.jsx("div",{className:"i-ph:terminal"})})]}),Zt==="diff"&&f.jsx(VC,{fileHistory:m,onSelectFile:Ca}),f.jsx(RC,{className:"h-8 w-8 justify-center"}),f.jsxs(Mn,{className:"ml-2 border border-accent-500/40 text-sm text-accent-700 enabled:hover:!bg-accent-100 enabled:hover:!text-accent-900 dark:text-accent-200 dark:enabled:hover:!bg-accent-500/15 dark:enabled:hover:!text-accent-100",onClick:()=>le(!0),children:[f.jsx("div",{className:"i-ph:rocket-launch"}),"Upgrade"]}),f.jsxs(Mn,{className:"ml-2 !bg-accent-600 enabled:hover:!bg-accent-700 !text-white enabled:hover:!text-white font-semibold px-3 py-1.5",onClick:Cu,disabled:Pe,children:[f.jsx("div",{className:"i-ph:cloud-arrow-up"}),Pe?"Publishing...":"Publish"]})]}),f.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[f.jsx(Lb,{initial:{x:"0%"},animate:{x:Zt==="code"?"0%":"-100%"},children:f.jsxs("div",{className:"relative h-full w-full",children:[f.jsx("div",{className:ue("h-full w-full transition-opacity duration-200",{"pointer-events-none opacity-0":ro||X}),"aria-hidden":ro||X,children:f.jsx(LG,{editorDocument:w,isStreaming:e,isFollowUpRequest:r,buildJob:n,selectedFile:_,advancedMode:I,progressMessage:U?r?"Updating your newsletter campaign":"Working on newsletter":void 0,files:E,unsavedFiles:C,fileHistory:m,onFileSelect:Dr,onEditorScroll:rr,onEditorChange:Wi,onFileSave:wa,onFileReset:Sa,onToggleAdvancedMode:Pi})}),!X&&ro&&f.jsx("div",{className:"absolute inset-0 z-[1]",children:f.jsx(jG,{isMobile:wt,variant:"workspace",onExploreMore:()=>le(!0)})})]})}),f.jsx(Lb,{initial:{x:"100%"},animate:{x:Zt==="diff"?"0%":Zt==="code"?"100%":"-100%"},children:Ss?f.jsx(x.Suspense,{fallback:Ib,children:f.jsx(x7,{fileHistory:m,setFileHistory:b})}):null}),f.jsx(Lb,{initial:{x:"100%"},animate:{x:Zt==="preview"?"0%":"100%"},children:Js?u?f.jsx("div",{className:"h-full w-full overflow-hidden bg-bolt-elements-background-depth-1",children:u}):f.jsx(x.Suspense,{fallback:Ib,children:f.jsx(w7,{ref:Wn,projectId:Ut,setSelectedElement:o,onControlsStateChange:is}
524)}):null}),X?f.jsx("div",{className:"absolute inset-0 z-[5]",children:f.jsx(Jq,{currentMode:Z,currentProjectName:Ar,currentWorkspaceId:Ut,buildJob:n,onOpenBuild:$r,onCancelBuild:s,onOpenProject:Su})}):null]})]})})}),f.jsx(Bl,{open:pe,onOpenChange:ne=>{Ye(ne),ne||(pt("overview"),nt(null))},children:f.jsxs(aM,{children:[f.jsx(lM,{className:"fixed inset-0 z-[9998] bg-black/60 backdrop-blur-sm"}),f.jsxs(cM,{className:"fixed inset-[2.5vh_2.5vw] z-[9999] focus:outline-none",children:[f.jsx(uM,{className:"sr-only",children:"Admin Workspace"}),f.jsx(dM,{className:"sr-only",children:"Manage project settings, data, secrets, users, and publishing controls."}),f.jsxs("div",{className:"h-full overflow-hidden rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 shadow-2xl",children:[f.jsxs("div",{className:"flex h-12 items-center justify-between border-b border-bolt-elements-borderColor px-4",children:[f.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-bolt-elements-textPrimary",children:[f.jsx("div",{className:"i-ph:sliders-horizontal text-base"}),"Admin Workspace"]}),f.jsx(hM,{asChild:!0,children:f.jsx("button",{type:"button",className:"rounded-md p-1.5 text-bolt-elements-textSecondary transition-colors hover:bg-bolt-elements-item-backgroundActive hover:text-bolt-elements-textPrimary","aria-label":"Close admin workspace",children:f.jsx("div",{className:"i-ph:x text-base"})})})]}),f.jsx("div",{className:"h-[calc(100%-3rem)] overflow-hidden",children:f.jsx(x.Suspense,{fallback:Ib,children:f.jsx(S7,{databaseProjectId:Ut||void 0,projectId:ur,appName:Qr,appSlug:Vt,appDescription:Ur,artifactId:Tr,workspaceId:Ut,workspaceMode:Z,repoUrl:i?.gitUrl,publishedDomain:zr?`${zr}.${Ge}`:i?.publishedDomain,previewBaseUrl:fe?.ready?fe.baseUrl:void 0,customDomain:qe,onCustomDomainMapped:so,activePlanId:te||null,dreamWeaverToken:te?null:De||null,onPublishClick:Cu,onOpenPreview:ds,onAppTitleUpdated:cs,securityAuditWarnings:Fe,securityAuditSummary:Jr,isSecurityAuditRunning:Te,onRunSecurityAudit:()=>{ws({flushChanges:!0})},onAskGenieToFixSecurity:Fi,isActive:pe,initialSection:ft,integrationSetupIntent:Lt,onAppDeleted:async()=>{Ye(!1),await vO()}})})})]})]})]})}),ve?f.jsx(x.Suspense,{fallback:null,children:f.jsx(C7,{isOpen:ve,onClose:()=>{ye(!1),Os(!1)},domainSuffix:Ge,zoneName:Ge,initialRepoName:Xt,initialSubdomain:xs,projectId:Nr,domainWorkerService:OC,primaryPublishedUrl:qe?Un(zr?`${zr}.${Ge}`:i?.publishedDomain):void 0,lockDomain:pn,securityWarnings:Fe,securityAuditSummary:Jr,isSecurityAuditRunning:Te,allowPublishWithWarnings:Yt,onReviewSecurity:ce,onPublish:async(ne,me,Ee,Ie)=>{const $e=On.get();let Be=ni((Ie||ln||"").trim());const ze=Vn(ne||"")?.slice(0,96);let gt=Vn(St||Ot||"")||ze||sx(Be||ze,$e?.email);const Q=Ge;let dt=Be?`${Be}.${Q}`:void 0;console.info("[publish.dialog] start",{finalRepoName:gt,normalizedSubdomain:Be||null,requestedDomain:dt||null,deploymentTarget:"r2",hasChanges:Ks(),metadataGitUrl:i?.gitUrl||null,metadataPublishedDomain:i?.publishedDomain||null});let rt;try{await Vr();const Br=await Sr({fallbackRepoName:gt,subdomain:Be,domain:dt});Br?.repoName&&(gt=Br.repoName),Br?.subdomain&&(Be=Br.subdomain),Br?.domain?dt=Br.domain:Be&&(dt=`${Be}.${Q}`),rt=await Xs(gt,{appId:Br?.appId||ur}),await ki(rt),be(!0);const sn=dt,Me=await j.publishToR2({projectId:rt||kn(gt)||gt,repoName:gt,publishedDomain:sn}),yt=Un(sn)||Me.url||(sn?`https://${sn}`:"");return Or(gt),Be&&Pr(Be),Lr(gt,Be||void 0,sn),await gn(gt,rt),await Ti(Me,sn,{appId:rt,repoName:gt}),Ys(),console.info("[publish.dialog] changes.success",{finalRepoName:gt,normalizedSubdomain:Be,reservedDomain:sn,deploymentTarget:"r2",deploymentId:Me.deploymentId||null}),{url:yt||Me.deployedUrl||""}}catch(Br){throw console.error("Error publishing app:",Br),Br}finally{be(!1)}}})}):null,Ae?f.jsx(x.Suspense,{fallback:null,children:f.jsx(A7,{isOpen:Ae,isRunning:Te,warnings:Fe,summary:Jr,onClose:()=>we(!1),onRunAudit:()=>{ws({flushChanges:!0})},onAskGenieToFix:Fi,onPublishAnyway:G})}):null,ee?f.jsx(x.Suspense,{fallback:null,children:f.jsx(E7,{isOpen:ee,onClose:()=>le(!1),onPlanSelect:hi})}):null,xt?f.jsx(x.Suspense,{fallback:null,children:f.jsx(k7,{isOpen:xt,onClose:()=>ct(!1),planName:_r?.name||"",planPrice:_r?.price||"",initialSubdomain:xs,domainSuffix:je,projectId:Nr,onPublish:ml})}):null,Bn?f.jsx(x.Suspense,{fallback:null,children:f.jsx(P7,{isOpen:Bn,payment:vs,onComplete:Je})}):null,ci&&f.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:f.jsxs("div",{className:"bg-white rounded-xl p-8 max-w-md mx-4 text-center border border-bolt-elements-borderColor shadow-xl",children:[f.jsxs("div",{className:"relative h-16 w-16 mx-auto mb-4",children:[f.jsx("div",{className:"absolute inset-0 rounded-full bg-accent-500/20 animate-ping"}),f.jsx("div",{className:"absolute inset-0 rounded-full border border-accent-500/60 flex items-center justify-center bg-white",children:f.jsx("div",{className:"i-ph:rocket-launch-duotone text-2xl text-accent-500 animate-bounce"})})]}),f.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Publishing Your Website"}),f.jsx("p",{className:"text-gray-600 mb-2",children:Ea}),f.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Cloudflare deployment is usually ready in 30-40 seconds."}),f.jsx("div",{className:"w-full h-2 rounded-full bg-gray-200 overflow-hidden mb-2",children:f.jsx("div",{className:"h-full bg-accent-500 transition-all duration-500",style:{width:`${qm}%`}})}),f.jsxs("div",{className:"text-xs text-gray-500",children:["Elapsed time: ",Gm]})]})})]})}),Lb=x.memo(({children:t,...e})=>f.jsx(ar.div,{className:"absolute inset-0",transition:b7,...e,children:t})),NI=[{id:"abap",name:"ABAP",import:()=>H(()=>import("./abap-DsBKuouk.js"),[])},{id:"actionscript-3",name:"ActionScript",import:()=>H(()=>import("./actionscript-3-D_z4Izcz.js"),[])},{id:"ada",name:"Ada",import:()=>H(()=>import("./ada-727ZlQH0.js"),[])},{id:"angular-html",name:"Angular HTML",import:()=>H(()=>import("./angular-html-LfdN0zeE.js").then(t=>t.f),__vite__mapDeps([119,120,121,122]))},{id:"angular-ts",name:"Angular TypeScript",import:()=>H(()=>import("./angular-ts-CKsD7JZE.js"),__vite__mapDeps([123,119,120,121,122,124]))},{id:"apache",name:"Apache Conf",import:()=>H(()=>import("./apache-Dn00JSTd.js"),[])},{id:"apex",name:"Apex",import:()=>H(()=>import("./apex-COJ4H7py.js"),[])},{id:"apl",name:"APL",import:()=>H(()=>import("./apl-BBq3IX1j.js"),__vite__mapDeps([125,120,121,122,126,127,128]))},{id:"applescript",name:"AppleScript",import:()=>H(()=>import("./applescript-Bu5BbsvL.js"),[])},{id:"ara",name:"Ara",import:()=>H(()=>import("./ara-7O62HKoU.js"),[])},{id:"asciidoc",name:"AsciiDoc",aliases:["adoc"],import:()=>H(()=>import("./asciidoc-BPT9niGB.js"),[])},{id:"asm",name:"Assembly",import:()=>H(()=>import("./asm-Dhn9LcZ4.js"),[])},{id:"astro",name:"Astro",import:()=>H(()=>import("./astro-CqkE3fuf.js"),__vite__mapDeps([129,128,121,130,122,131]))},{id:"awk",name:"AWK",import:()=>H(()=>import("./awk-eg146-Ew.js"),[])},{id:"ballerina",name:"Ballerina",import:()=>H(()=>import("./ballerina-Du268qiB.js"),[])},{id:"bat",name:"Batch File",aliases:["batch"],import:()=>H(()=>import("./bat-fje9CFhw.js"),[])},{id:"beancount",name:"Beancount",import:()=>H(()=>import("./beancount-BwXTMy5W.js"),[])},{id:"berry",name:"Berry",aliases:["be"],import:()=>H(()=>import("./berry-3xVqZejG.js"),[])},{id:"bibtex",name:"BibTeX",import:()=>H(()=>import("./bibtex-xW4inM5L.js"),[])},{id:"bicep",name:"Bicep",import:()=>H(()=>import("./bicep-DHo0CJ0O.js"),[])},{id:"blade",name:"Blade",import:()=>H(()=>import("./blade-a8OxSdnT.js"),__vite__mapDeps([132,120,121,122,126,127,133,128]))},{id:"bsl",name:"1C (Enterprise)",aliases:["1c"],import:()=>H(()=>import("./bsl-Dgyn0ogV.js"),__vite__mapDeps([134,135]))},{id:"c",name:"C",import:()=>H(()=>import("./c-C3t2pwGQ.js"),[])},{id:"cadence",name:"Cadence",aliases:["cdc"],import:()=>H(()=>import("./cadence-DNquZEk8.js"),[])},{id:"cairo",name:"Cairo",import:()=>H(()=>import("./cairo--RitsXJZ.js"),__vite__mapDeps([136,137]))},{id:"clarity",name:"Clarity",import:()=>H(()=>import("./clarity-BHOwM8T6.js"),[])},{id:"clojure",name:"Clojure",aliases:["clj"],import:()=>H(()=>import("./clojure-DxSadP1t.js"),[])},{id:"cmake",name:"CMake",import:()=>H(()=>import("./cmake-DbXoA79R.js"),[])},{id:"cobol",name:"COBOL",import:()=>H(()=>import("./cobol-PTqiYgYu.js"),__vite__mapDeps([138,120,121,122,127]))},{id:"codeowners",name:"CODEOWNERS",import:()=>H(()=>import("./codeowners-Bp6g37R7.js"),[])},{id:"codeql",name:"CodeQL",aliases:["ql"],import:()=>H(()=>import("./codeql-sacFqUAJ.js"),[])},{id:"coffee",name:"CoffeeScript",aliases:["coffeescript"],import:()=>H(()=>import("./coffee-dyiR41kL.js"),__vite__mapDeps([139,121]))},{id:"common-lisp",name:"Common Lisp",aliases:["lisp"],import:()=>H(()=>import("./common-lisp-C7gG9l05.js"),[])},{id:"coq",name:"Coq",import:()=>H(()=>import("./coq-Dsg_Bt_b.js"),[])},{id:"cpp",name:"C++",aliases:["c++"],import:()=>H(()=>import("./cpp-BksuvNSY.js"),__vite__mapDeps([140,141,142,143,133]))},{id:"crystal",name:"Crystal",import:()=>H(()=>import("./crystal-DtDmRg-F.js"),__vite__mapDeps([144,120,121,122,133,143,145]))}
524,{id:"csharp",name:"C#",aliases:["c#","cs"],import:()=>H(()=>import("./csharp-D9R-vmeu.js"),[])},{id:"css",name:"CSS",import:()=>H(()=>import("./css-BPhBrDlE.js"),[])},{id:"csv",name:"CSV",import:()=>H(()=>import("./csv-B0qRVHPH.js"),[])},{id:"cue",name:"CUE",import:()=>H(()=>import("./cue-DtFQj3wx.js"),[])},{id:"cypher",name:"Cypher",aliases:["cql"],import:()=>H(()=>import("./cypher-m2LEI-9-.js"),[])},{id:"d",name:"D",import:()=>H(()=>import("./d-BoXegm-a.js"),[])},{id:"dart",name:"Dart",import:()=>H(()=>import("./dart-B9wLZaAG.js"),[])},{id:"dax",name:"DAX",import:()=>H(()=>import("./dax-ClGRhx96.js"),[])},{id:"desktop",name:"Desktop",import:()=>H(()=>import("./desktop-DEIpsLCJ.js"),[])},{id:"diff",name:"Diff",import:()=>H(()=>import("./diff-BgYniUM_.js"),[])},{id:"docker",name:"Dockerfile",aliases:["dockerfile"],import:()=>H(()=>import("./docker-COcR7UxN.js"),[])},{id:"dotenv",name:"dotEnv",import:()=>H(()=>import("./dotenv-D-NiToSL.js"),__vite__mapDeps([146,3]))},{id:"dream-maker",name:"Dream Maker",import:()=>H(()=>import("./dream-maker-C-nORZOA.js"),[])},{id:"edge",name:"Edge",import:()=>H(()=>
524import("./edge-D5gP-w-T.js"),__vite__mapDeps([147,130,120,121,122,148]))},{id:"elixir",name:"Elixir",import:()=>H(()=>import("./elixir-CLiX3zqd.js"),__vite__mapDeps([149,120,121,122]))},{id:"elm",name:"Elm",import:()=>H(()=>import("./elm-CmHSxxaM.js"),__vite__mapDeps([150,142,143]))},{id:"emacs-lisp",name:"Emacs Lisp",aliases:["elisp"],import:()=>H(()=>import("./emacs-lisp-BX77sIaO.js"),[])},{id:"erb",name:"ERB",import:()=>H(()=>import("./erb-BYTLMnw6.js"),__vite__mapDeps([151,120,121,122,152,153,126,127,133,154,130,155,156,140,141,142,143,145,157,158]))},{id:"erlang",name:"Erlang",aliases:["erl"],import:()=>H(()=>import("./erlang-B-DoSBHF.js"),[])},{id:"fennel",name:"Fennel",import:()=>H(()=>import("./fennel-bCA53EVm.js"),[])},{id:"fish",name:"Fish",import:()=>H(()=>import("./fish-w-ucz2PV.js"),[])},{id:"fluent",name:"Fluent",aliases:["ftl"],import:()=>H(()=>import("./fluent-Dayu4EKP.js"),[])},{id:"fortran-fixed-form",name:"Fortran (Fixed Form)",aliases:["f","for","f77"],import:()=>H(()=>import("./fortran-fixed-form-TqA4NnZg.js"),__vite__mapDeps([159,160]))},{id:"fortran-free-form",name:"Fortran (Free Form)",aliases:["f90","f95","f03","f08","f18"],import:()=>H(()=>import("./fortran-free-form-DKXYxT9g.js"),[])},{id:"fsharp",name:"F#",aliases:["f#","fs"],import:()=>H(()=>import("./fsharp-XplgxFYe.js"),__vite__mapDeps([161,162]))},{id:"gdresource",name:"GDResource",import:()=>H(()=>import("./gdresource-BHYsBjWJ.js"),__vite__mapDeps([163,164,165]))},{id:"gdscript",name:"GDScript",import:()=>H(()=>import("./gdscript-DfxzS6Rs.js"),[])},{id:"gdshader",name:"GDShader",import:()=>H(()=>import("./gdshader-SKMF96pI.js"),[])},{id:"genie",name:"Genie",import:()=>H(()=>import("./genie-ajMbGru0.js"),[])},{id:"gherkin",name:"Gherkin",import:()=>H(()=>import("./gherkin--30QC5Em.js"),[])},{id:"git-commit",name:"Git Commit Message",import:()=>H(()=>import("./git-commit-i4q6IMui.js"),__vite__mapDeps([166,167]))},{id:"git-rebase",name:"Git Rebase Message",import:()=>H(()=>import("./git-rebase-B-v9cOL2.js"),__vite__mapDeps([168,145]))},{id:"gleam",name:"Gleam",import:()=>H(()=>import("./gleam-B430Bg39.js"),[])},{id:"glimmer-js",name:"Glimmer JS",aliases:["gjs"],import:()=>H(()=>import("./glimmer-js-D-cwc0-E.js"),__vite__mapDeps([169,121,130,122,120]))},{id:"glimmer-ts",name:"Glimmer TS",aliases:["gts"],import:()=>H(()=>import("./glimmer-ts-pgjy16dm.js"),__vite__mapDeps([170,130,122,121,120]))},{id:"glsl",name:"GLSL",import:()=>H(()=>import("./glsl-DBO2IWDn.js"),__vite__mapDeps([142,143]))},{id:"gnuplot",name:"Gnuplot",import:()=>H(()=>import("./gnuplot-CM8KxXT1.js"),[])},{id:"go",name:"Go",import:()=>H(()=>import("./go-B1SYOhNW.js"),[])},{id:"graphql",name:"GraphQL",aliases:["gql"],import:()=>H(()=>import("./graphql-cDcHW_If.js"),__vite__mapDeps([154,121,130,155,156]))},{id:"groovy",name:"Groovy",import:()=>H(()=>import("./groovy-DkBy-JyN.js"),[])},{id:"hack",name:"Hack",import:()=>H(()=>import("./hack-D1yCygmZ.js"),__vite__mapDeps([171,120,121,122,133]))},{id:"haml",name:"Ruby Haml",import:()=>H(()=>import("./haml-B2EZWmdv.js"),__vite__mapDeps([153,121,122]))},{id:"handlebars",name:"Handlebars",aliases:["hbs"],import:()=>H(()=>import("./handlebars-BQGss363.js"),__vite__mapDeps([172,120,121,122,158]))},{id:"haskell",name:"Haskell",aliases:["hs"],import:()=>H(()=>import("./haskell-BILxekzW.js"),[])},{id:"haxe",name:"Haxe",import:()=>H(()=>import("./haxe-C5wWYbrZ.js"),[])},{id:"hcl",name:"HashiCorp HCL",import:()=>H(()=>import("./hcl-HzYwdGDm.js"),[])},{id:"hjson",name:"Hjson",import:()=>H(()=>import("./hjson-T-Tgc4AT.js"),[])},{id:"hlsl",name:"HLSL",import:()=>H(()=>import("./hlsl-ifBTmRxC.js"),[])},{id:"html",name:"HTML",import:()=>H(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([120,121,122]))},{id:"html-derivative",name:"HTML (Derivative)",import:()=>H(()=>import("./html-derivative-CSfWNPLT.js"),__vite__mapDeps([148,120,121,122]))},{id:"http",name:"HTTP",import:()=>H(()=>import("./http-FRrOvY1W.js"),__vite__mapDeps([173,145,128,126,127,154,121,130,155,156]))},{id:"hxml",name:"HXML",import:()=>H(()=>import("./hxml-TIA70rKU.js"),__vite__mapDeps([174,175]))},{id:"hy",name:"Hy",import:()=>H(()=>
524import("./hy-BMj5Y0dO.js"),[])},{id:"imba",name:"Imba",import:()=>H(()=>import("./imba-bv_oIlVt.js"),__vite__mapDeps([176,130]))},{id:"ini",name:"INI",aliases:["properties"],import:()=>H(()=>import("./ini-BjABl1g7.js"),[])},{id:"java",name:"Java",import:()=>H(()=>import("./java-xI-RfyKK.js"),[])},{id:"javascript",name:"JavaScript",aliases:["js"],import:()=>H(()=>import("./javascript-ySlJ1b_l.js"),[])},{id:"jinja",name:"Jinja",import:()=>H(()=>import("./jinja-DGy0s7-h.js"),__vite__mapDeps([177,120,121,122]))},{id:"jison",name:"Jison",import:()=>H(()=>import("./jison-BqZprYcd.js"),__vite__mapDeps([178,121]))},{id:"json",name:"JSON",import:()=>H(()=>import("./json-BQoSv7ci.js"),[])},{id:"json5",name:"JSON5",import:()=>H(()=>import("./json5-w8dY5SsB.js"),[])},{id:"jsonc",name:"JSON with Comments",import:()=>H(()=>import("./jsonc-TU54ms6u.js"),[])},{id:"jsonl",name:"JSON Lines",import:()=>H(()=>import("./jsonl-DREVFZK8.js"),[])},{id:"jsonnet",name:"Jsonnet",import:()=>H(()=>import("./jsonnet-BfivnA6A.js"),[])},{id:"jssm",name:"JSSM",aliases:["fsl"],import:()=>H(()=>import("./jssm-P4WzXJd0.js"),[])},{id:"jsx",name:"JSX",import:()=>H(()=>import("./jsx-BAng5TT0.js"),[])},{id:"julia",name:"Julia",aliases:["jl"],import:()=>H(()=>import("./julia-BBuGR-5E.js"),__vite__mapDeps([179,140,141,142,143,133,137,121,180]))},{id:"kotlin",name:"Kotlin",aliases:["kt","kts"],import:()=>H(()=>import("./kotlin-B5lbUyaz.js"),[])},{id:"kusto",name:"Kusto",aliases:["kql"],import:()=>H(()=>import("./kusto-mebxcVVE.js"),[])},{id:"latex",name:"LaTeX",import:()=>H(()=>import("./latex-C-cWTeAZ.js"),__vite__mapDeps([181,182,180]))},{id:"lean",name:"Lean 4",aliases:["lean4"],import:()=>H(()=>import("./lean-XBlWyCtg.js"),[])},{id:"less",name:"Less",import:()=>H(()=>import("./less-BfCpw3nA.js"),[])},{id:"liquid",name:"Liquid",import:()=>H(()=>import("./liquid-D3W5UaiH.js"),__vite__mapDeps([183,120,121,122,128]))},{id:"log",name:"Log file",import:()=>H(()=>import("./log-Cc5clBb7.js"),[])},{id:"logo",name:"Logo",import:()=>H(()=>import("./logo-IuBKFhSY.js"),[])},{id:"lua",name:"Lua",import:()=>H(()=>import("./lua-CvWAzNxB.js"),__vite__mapDeps([157,143]))},{id:"luau",name:"Luau",import:()=>H(()=>import("./luau-Du5NY7AG.js"),[])},{id:"make",name:"Makefile",aliases:["makefile"],import:()=>H(()=>import("./make-Bvotw-X0.js"),[])},{id:"markdown",name:"Markdown",aliases:["md"],import:()=>H(()=>import("./markdown-UIAJJxZW.js"),[])},{id:"marko",name:"Marko",import:()=>H(()=>import("./marko-z0MBrx5-.js"),__vite__mapDeps([184,122,185,124,121]))},{id:"matlab",name:"MATLAB",import:()=>H(()=>import("./matlab-D9-PGadD.js"),[])},{id:"mdc",name:"MDC",import:()=>H(()=>import("./mdc-DB_EDNY_.js"),__vite__mapDeps([186,162,158,148,120,121,122]))},{id:"mdx",name:"MDX",import:()=>H(()=>import("./mdx-sdHcTMYB.js"),[])},{id:"mermaid",name:"Mermaid",aliases:["mmd"],import:()=>H(()=>import("./mermaid-Ci6OQyBP.js"),[])},{id:"mipsasm",name:"MIPS Assembly",aliases:["mips"],import:()=>H(()=>import("./mipsasm-BC5c_5Pe.js"),[])},{id:"mojo",name:"Mojo",import:()=>H(()=>import("./mojo-Tz6hzZYG.js"),[])},{id:"move",name:"Move",import:()=>H(()=>import("./move-DB_GagMm.js"),[])},{id:"narrat",name:"Narrat Language",aliases:["nar"],import:()=>H(()=>import("./narrat-DLbgOhZU.js"),[])},{id:"nextflow",name:"Nextflow",aliases:["nf"],import:()=>H(()=>import("./nextflow-B0XVJmRM.js"),[])},{id:"nginx",name:"Nginx",import:()=>H(()=>import("./nginx-D_VnBJ67.js"),__vite__mapDeps([187,157,143]))},{id:"nim",name:"Nim",import:()=>H(()=>import("./nim-ZlGxZxc3.js"),__vite__mapDeps([188,143,120,121,122,126,127,142,162]))},{id:"nix",name:"Nix",import:()=>H(()=>import("./nix-shcSOmrb.js"),[])},{id:"nushell",name:"nushell",aliases:["nu"],import:()=>H(()=>import("./nushell-D4Tzg5kh.js"),[])},{id:"objective-c",name:"Objective-C",aliases:["objc"],import:()=>H(()=>import("./objective-c-Deuh7S70.js"),[])},{id:"objective-cpp",name:"Objective-C++",import:()=>H(()=>import("./objective-cpp-BUEGK8hf.js"),[])},{id:"ocaml",name:"OCaml",import:()=>H(()=>import("./ocaml-BNioltXt.js"),[])},{id:"pascal",name:"Pascal",import:()=>H(()=>import("./pascal-JqZropPD.js"),[])},{id:"perl",name:"Perl",import:()=>H(()=>import("./perl-CHQXSrWU.js"),__vite__mapDeps([189,120,121,122,126,127,133]))},{id:"php",name:"PHP",import:()=>H(()=>
524import("./php-B5ebYQev.js"),__vite__mapDeps([190,120,121,122,126,127,133,128]))},{id:"plsql",name:"PL/SQL",import:()=>H(()=>import("./plsql-LKU2TuZ1.js"),[])},{id:"po",name:"Gettext PO",aliases:["pot","potx"],import:()=>H(()=>import("./po-BFLt1xDp.js"),[])},{id:"polar",name:"Polar",import:()=>H(()=>import("./polar-DKykz6zU.js"),[])},{id:"postcss",name:"PostCSS",import:()=>H(()=>import("./postcss-B3ZDOciz.js"),[])},{id:"powerquery",name:"PowerQuery",import:()=>H(()=>import("./powerquery-CSHBycmS.js"),[])},{id:"powershell",name:"PowerShell",aliases:["ps","ps1"],import:()=>H(()=>import("./powershell-BIEUsx6d.js"),[])},{id:"prisma",name:"Prisma",import:()=>H(()=>import("./prisma-B48N-Iqd.js"),[])},{id:"prolog",name:"Prolog",import:()=>H(()=>import("./prolog-BY-TUvya.js"),[])},{id:"proto",name:"Protocol Buffer 3",aliases:["protobuf"],import:()=>H(()=>import("./proto-zocC4JxJ.js"),[])},{id:"pug",name:"Pug",aliases:["jade"],import:()=>H(()=>import("./pug-CM9l7STV.js"),__vite__mapDeps([191,121,122,120]))},{id:"puppet",name:"Puppet",import:()=>H(()=>import("./puppet-Cza_XSSt.js"),[])},{id:"purescript",name:"PureScript",import:()=>H(()=>import("./purescript-Bg-kzb6g.js"),[])},{id:"python",name:"Python",aliases:["py"],import:()=>H(()=>import("./python-DhUJRlN_.js"),[])},{id:"qml",name:"QML",import:()=>H(()=>import("./qml-D8XfuvdV.js"),__vite__mapDeps([192,121]))},{id:"qmldir",name:"QML Directory",import:()=>H(()=>import("./qmldir-C8lEn-DE.js"),[])},{id:"qss",name:"Qt Style Sheets",import:()=>H(()=>import("./qss-DhMKtDLN.js"),[])},{id:"r",name:"R",import:()=>H(()=>import("./r-CwjWoCRV.js"),[])},{id:"racket",name:"Racket",import:()=>H(()=>import("./racket-CzouJOBO.js"),[])},{id:"raku",name:"Raku",aliases:["perl6"],import:()=>H(()=>import("./raku-B1bQXN8T.js"),[])},{id:"razor",name:"ASP.NET Razor",import:()=>H(()=>import("./razor-CNLDkMZG.js"),__vite__mapDeps([193,120,121,122,194]))},{id:"reg",name:"Windows Registry Script",import:()=>H(()=>import("./reg-5LuOXUq_.js"),[])},{id:"regexp",name:"RegExp",aliases:["regex"],import:()=>H(()=>import("./regexp-DWJ3fJO_.js"),[])},{id:"rel",name:"Rel",import:()=>H(()=>import("./rel-DJlmqQ1C.js"),[])},{id:"riscv",name:"RISC-V",import:()=>H(()=>import("./riscv-QhoSD0DR.js"),[])},{id:"rst",name:"reStructuredText",import:()=>H(()=>import("./rst-4NLicBqY.js"),__vite__mapDeps([195,148,120,121,122,140,141,142,143,133,137,145,158,196,152,153,126,127,154,130,155,156,157]))},{id:"ruby",name:"Ruby",aliases:["rb"],import:()=>H(()=>import("./ruby-DeZ3UC14.js"),__vite__mapDeps([152,120,121,122,153,126,127,133,154,130,155,156,140,141,142,143,145,157,158]))},{id:"rust",name:"Rust",aliases:["rs"],import:()=>H(()=>import("./rust-Be6lgOlo.js"),[])},{id:"sas",name:"SAS",import:()=>H(()=>import("./sas-BmTFh92c.js"),__vite__mapDeps([197,133]))},{id:"sass",name:"Sass",import:()=>H(()=>import("./sass-BJ4Li9vH.js"),[])},{id:"scala",name:"Scala",import:()=>H(()=>import("./scala-DQVVAn-B.js"),[])},{id:"scheme",name:"Scheme",import:()=>H(()=>import("./scheme-BJGe-b2p.js"),[])},{id:"scss",name:"SCSS",import:()=>H(()=>import("./scss-C31hgJw-.js"),__vite__mapDeps([124,122]))},{id:"sdbl",name:"1C (Query)",aliases:["1c-query"],import:()=>H(()=>import("./sdbl-BLhTXw86.js"),[])},{id:"shaderlab",name:"ShaderLab",aliases:["shader"],import:()=>H(()=>import("./shaderlab-B7qAK45m.js"),__vite__mapDeps([198,199]))},{id:"shellscript",name:"Shell",aliases:["bash","sh","shell","zsh"],import:()=>H(()=>import("./shellscript-atvbtKCR.js"),[])},{id:"shellsession",name:"Shell Session",aliases:["console"],import:()=>H(()=>import("./shellsession-C_rIy8kc.js"),__vite__mapDeps([200,145]))},{id:"smalltalk",name:"Smalltalk",import:()=>H(()=>import("./smalltalk-DkLiglaE.js"),[])},{id:"solidity",name:"Solidity",import:()=>H(()=>import("./solidity-C1w2a3ep.js"),[])},{id:"soy",name:"Closure Templates",aliases:["closure-templates"],import:()=>H(()=>import("./soy-C-lX7w71.js"),__vite__mapDeps([201,120,121,122]))},{id:"sparql",name:"SPARQL",import:()=>H(()=>import("./sparql-bYkjHRlG.js"),__vite__mapDeps([202,203]))},{id:"splunk",name:"Splunk Query Language",aliases:["spl"],import:()=>H(()=>import("./splunk-Cf8iN4DR.js"),[])},{id:"sql",name:"SQL",import:()=>H(()=>import("./sql-COK4E0Yg.js"),[])},{id:"ssh-config",name:"SSH Config",import:()=>H(()=>import("./ssh-config-BknIz3MU.js"),[])},{id:"stata",name:"Stata",import:()=>H(()=>import("./stata-DorPZHa4.js"),__vite__mapDeps([204,133]))},{id:"stylus",name:"Stylus",aliases:["styl"],import:()=>H(()=>import("./stylus-BeQkCIfX.js"),[])},{id:"svelte",name:"Svelte",import:()=>H(()=>import("./svelte-MSaWC3Je.js"),__vite__mapDeps([205,121,130,122,131]))},{id:"swift",name:"Swift",import:()=>H(()=>import("./swift-BSxZ-RaX.js"),[])},{id:"system-verilog",name:"SystemVerilog",import:()=>H(()=>import("./system-verilog-C7L56vO4.js"),[])},{id:"systemd",name:"Systemd Units",import:()=>H(()=>import("./systemd-CUnW07Te.js"),[])},{id:"talonscript",name:"TalonScript",aliases:["talon"],import:()=>H(()=>import("./talonscript-C1XDQQGZ.js"),[])},{id:"tasl",name:"Tasl",import:()=>H(()=>import("./tasl-CQjiPCtT.js"),[])},{id:"tcl",name:"Tcl",import:()=>H(()=>import("./tcl-DQ1-QYvQ.js"),[])}
524,{id:"templ",name:"Templ",import:()=>H(()=>import("./templ-dwX3ZSMB.js"),__vite__mapDeps([206,207,121,122]))},{id:"terraform",name:"Terraform",aliases:["tf","tfvars"],import:()=>H(()=>import("./terraform-BbSNqyBO.js"),[])},{id:"tex",name:"TeX",import:()=>H(()=>import("./tex-rYs2v40G.js"),__vite__mapDeps([182,180]))},{id:"toml",name:"TOML",import:()=>H(()=>import("./toml-CB2ApiWb.js"),[])},{id:"ts-tags",name:"TypeScript with Tags",aliases:["lit"],import:()=>H(()=>import("./ts-tags-CipyTH0X.js"),__vite__mapDeps([208,130,122,121,142,143,120,133,126,127]))},{id:"tsv",name:"TSV",import:()=>H(()=>import("./tsv-B_m7g4N7.js"),[])},{id:"tsx",name:"TSX",import:()=>H(()=>import("./tsx-B6W0miNI.js"),[])},{id:"turtle",name:"Turtle",import:()=>H(()=>import("./turtle-BMR_PYu6.js"),[])},{id:"twig",name:"Twig",import:()=>H(()=>import("./twig-NC5TFiHP.js"),__vite__mapDeps([209,122,121,124,190,120,126,127,133,128,137,152,153,154,130,155,156,140,141,142,143,145,157,158]))},{id:"typescript",name:"TypeScript",aliases:["ts"],import:()=>H(()=>import("./typescript-Dj6nwHGl.js"),[])},{id:"typespec",name:"TypeSpec",aliases:["tsp"],import:()=>H(()=>import("./typespec-BpWG_bgh.js"),[])},{id:"typst",name:"Typst",aliases:["typ"],import:()=>H(()=>import("./typst-BVUVsWT6.js"),[])}
524,{id:"v",name:"V",import:()=>H(()=>import("./v-CAQ2eGtk.js"),[])},{id:"vala",name:"Vala",import:()=>H(()=>import("./vala-BFOHcciG.js"),[])},{id:"vb",name:"Visual Basic",aliases:["cmd"],import:()=>H(()=>import("./vb-CdO5JTpU.js"),[])},{id:"verilog",name:"Verilog",import:()=>H(()=>import("./verilog-CJaU5se_.js"),[])},{id:"vhdl",name:"VHDL",import:()=>H(()=>import("./vhdl-DYoNaHQp.js"),[])},{id:"viml",name:"Vim Script",aliases:["vim","vimscript"],import:()=>H(()=>import("./viml-m4uW47V2.js"),[])},{id:"vue",name:"Vue",import:()=>H(()=>import("./vue-BuYVFjOK.js"),__vite__mapDeps([210,120,121,122,130,128,148]))},{id:"vue-html",name:"Vue HTML",import:()=>H(()=>import("./vue-html-xdeiXROB.js"),__vite__mapDeps([211,210,120,121,122,130,128,148]))},{id:"vyper",name:"Vyper",aliases:["vy"],import:()=>H(()=>import("./vyper-nyqBNV6O.js"),[])},{id:"wasm",name:"WebAssembly",import:()=>H(()=>import("./wasm-C6j12Q_x.js"),[])},{id:"wenyan",name:"Wenyan",aliases:["æè¨"],import:()=>H(()=>import("./wenyan-7A4Fjokl.js"),[])},{id:"wgsl",name:"WGSL",import:()=>H(()=>import("./wgsl-CB0Krxn9.js"),[])},{id:"wikitext",name:"Wikitext",aliases:["mediawiki","wiki"],import:()=>H(()=>import("./wikitext-DCE3LsBG.js"),[])},{id:"wolfram",name:"Wolfram",aliases:["wl"],import:()=>H(()=>import("./wolfram-C3FkfJm5.js"),[])},{id:"xml",name:"XML",import:()=>H(()=>import("./xml-e3z08dGr.js"),__vite__mapDeps([126,127]))},{id:"xsl",name:"XSL",import:()=>H(()=>import("./xsl-Dd0NUgwM.js"),__vite__mapDeps([212,126,127]))},{id:"yaml",name:"YAML",aliases:["yml"],import:()=>H(()=>import("./yaml-CVw76BM1.js"),[])},{id:"zenscript",name:"ZenScript",import:()=>H(()=>import("./zenscript-HnGAYVZD.js"),[])},{id:"zig",name:"Zig",import:()=>H(()=>import("./zig-BVz_zdnA.js"),[])}],Y7=Object.fromEntries(NI.map(t=>[t.id,t.import])),X7=Object.fromEntries(NI.flatMap(t=>t.aliases?.map(e=>[e,t.import])||[])),LI={...Y7,...X7},J7=[{id:"andromeeda",displayName:"Andromeeda",type:"dark",import:()=>H(()=>import("./andromeeda-C3khCPGq.js"),[])},{id:"aurora-x",displayName:"Aurora X",type:"dark",import:()=>H(()=>import("./aurora-x-D-2ljcwZ.js"),[])},{id:"ayu-dark",displayName:"Ayu Dark",type:"dark",import:()=>H(()=>import("./ayu-dark-Cv9koXgw.js"),[])},{id:"catppuccin-frappe",displayName:"Catppuccin Frappé",type:"dark",import:()=>H(()=>import("./catppuccin-frappe-CD_QflpE.js"),[])},{id:"catppuccin-latte",displayName:"Catppuccin Latte",type:"light",import:()=>H(()=>import("./catppuccin-latte-DRW-0cLl.js"),[])},{id:"catppuccin-macchiato",displayName:"Catppuccin Macchiato",type:"dark",import:()=>H(()=>import("./catppuccin-macchiato-C-_shW-Y.js"),[])},{id:"catppuccin-mocha",displayName:"Catppuccin Mocha",type:"dark",import:()=>H(()=>import("./catppuccin-mocha-LGGdnPYs.js"),[])},{id:"dark-plus",displayName:"Dark Plus",type:"dark",import:()=>H(()=>import("./dark-plus-C3mMm8J8.js"),[])},{id:"dracula",displayName:"Dracula Theme",type:"dark",import:()=>H(()=>import("./dracula-BzJJZx-M.js"),[])},{id:"dracula-soft",displayName:"Dracula Theme Soft",type:"dark",import:()=>H(()=>import("./dracula-soft-BXkSAIEj.js"),[])},{id:"everforest-dark",displayName:"Everforest Dark",type:"dark",import:()=>H(()=>import("./everforest-dark-BgDCqdQA.js"),[])},{id:"everforest-light",displayName:"Everforest Light",type:"light",import:()=>H(()=>import("./everforest-light-C8M2exoo.js"),[])},{id:"github-dark",displayName:"GitHub Dark",type:"dark",import:()=>H(()=>import("./github-dark-DHJKELXO.js"),[])},{id:"github-dark-default",displayName:"GitHub Dark Default",type:"dark",import:()=>H(()=>import("./github-dark-default-Cuk6v7N8.js"),[])},{id:"github-dark-dimmed",displayName:"GitHub Dark Dimmed",type:"dark",import:()=>H(()=>import("./github-dark-dimmed-DH5Ifo-i.js"),[])},{id:"github-dark-high-contrast",displayName:"GitHub Dark High Contrast",type:"dark",import:()=>H(()=>import("./github-dark-high-contrast-E3gJ1_iC.js"),[])},{id:"github-light",displayName:"GitHub Light",type:"light",import:()=>H(()=>import("./github-light-DAi9KRSo.js"),[])},{id:"github-light-default",displayName:"GitHub Light Default",type:"light",import:()=>H(()=>import("./github-light-default-D7oLnXFd.js"),[])},{id:"github-light-high-contrast",displayName:"GitHub Light High Contrast",type:"light",import:()=>H(()=>import("./github-light-high-contrast-BfjtVDDH.js"),[])},{id:"houston",displayName:"Houston",type:"dark",import:()=>H(()=>
524import("./houston-DnULxvSX.js"),[])},{id:"kanagawa-dragon",displayName:"Kanagawa Dragon",type:"dark",import:()=>H(()=>import("./kanagawa-dragon-CkXjmgJE.js"),[])},{id:"kanagawa-lotus",displayName:"Kanagawa Lotus",type:"light",import:()=>H(()=>import("./kanagawa-lotus-CfQXZHmo.js"),[])},{id:"kanagawa-wave",displayName:"Kanagawa Wave",type:"dark",import:()=>H(()=>import("./kanagawa-wave-DWedfzmr.js"),[])},{id:"laserwave",displayName:"LaserWave",type:"dark",import:()=>H(()=>import("./laserwave-DUszq2jm.js"),[])},{id:"light-plus",displayName:"Light Plus",type:"light",import:()=>H(()=>import("./light-plus-B7mTdjB0.js"),[])},{id:"material-theme",displayName:"Material Theme",type:"dark",import:()=>H(()=>import("./material-theme-D5KoaKCx.js"),[])},{id:"material-theme-darker",displayName:"Material Theme Darker",type:"dark",import:()=>H(()=>import("./material-theme-darker-BfHTSMKl.js"),[])},{id:"material-theme-lighter",displayName:"Material Theme Lighter",type:"light",import:()=>H(()=>import("./material-theme-lighter-B0m2ddpp.js"),[])},{id:"material-theme-ocean",displayName:"Material Theme Ocean",type:"dark",import:()=>H(()=>import("./material-theme-ocean-CyktbL80.js"),[])},{id:"material-theme-palenight",displayName:"Material Theme Palenight",type:"dark",import:()=>H(()=>import("./material-theme-palenight-Csfq5Kiy.js"),[])},{id:"min-dark",displayName:"Min Dark",type:"dark",import:()=>H(()=>import("./min-dark-CafNBF8u.js"),[])},{id:"min-light",displayName:"Min Light",type:"light",import:()=>H(()=>import("./min-light-CTRr51gU.js"),[])},{id:"monokai",displayName:"Monokai",type:"dark",import:()=>H(()=>import("./monokai-D4h5O-jR.js"),[])},{id:"night-owl",displayName:"Night Owl",type:"dark",import:()=>H(()=>import("./night-owl-C39BiMTA.js"),[])},{id:"nord",displayName:"Nord",type:"dark",import:()=>H(()=>import("./nord-Ddv68eIx.js"),[])},{id:"one-dark-pro",displayName:"One Dark Pro",type:"dark",import:()=>H(()=>import("./one-dark-pro-GBQ2dnAY.js"),[])},{id:"one-light",displayName:"One Light",type:"light",import:()=>H(()=>import("./one-light-PoHY5YXO.js"),[])},{id:"plastic",displayName:"Plastic",type:"dark",import:()=>H(()=>import("./plastic-3e1v2bzS.js"),[])},{id:"poimandres",displayName:"Poimandres",type:"dark",import:()=>H(()=>import("./poimandres-CS3Unz2-.js"),[])},{id:"red",displayName:"Red",type:"dark",import:()=>H(()=>import("./red-bN70gL4F.js"),[])},{id:"rose-pine",displayName:"Rosé Pine",type:"dark",import:()=>H(()=>import("./rose-pine-CmCqftbK.js"),[])},{id:"rose-pine-dawn",displayName:"Rosé Pine Dawn",type:"light",import:()=>H(()=>import("./rose-pine-dawn-Ds-gbosJ.js"),[])},{id:"rose-pine-moon",displayName:"Rosé Pine Moon",type:"dark",import:()=>H(()=>import("./rose-pine-moon-CjDtw9vr.js"),[])},{id:"slack-dark",displayName:"Slack Dark",type:"dark",import:()=>H(()=>import("./slack-dark-BthQWCQV.js"),[])},{id:"slack-ochin",displayName:"Slack Ochin",type:"light",import:()=>H(()=>import("./slack-ochin-DqwNpetd.js"),[])},{id:"snazzy-light",displayName:"Snazzy Light",type:"light",import:()=>H(()=>import("./snazzy-light-Bw305WKR.js"),[])},{id:"solarized-dark",displayName:"Solarized Dark",type:"dark",import:()=>H(()=>import("./solarized-dark-DXbdFlpD.js"),[])},{id:"solarized-light",displayName:"Solarized Light",type:"light",import:()=>H(()=>import("./solarized-light-L9t79GZl.js"),[])},{id:"synthwave-84",displayName:"Synthwave '84",type:"dark",import:()=>H(()=>import("./synthwave-84-CbfX1IO0.js"),[])},{id:"tokyo-night",displayName:"Tokyo Night",type:"dark",import:()=>H(()=>import("./tokyo-night-DBQeEorK.js"),[])},{id:"vesper",displayName:"Vesper",type:"dark",import:()=>H(()=>import("./vesper-BEBZ7ncR.js"),[])},{id:"vitesse-black",displayName:"Vitesse Black",type:"dark",import:()=>H(()=>import("./vitesse-black-Bkuqu6BP.js"),[])},{id:"vitesse-dark",displayName:"Vitesse Dark",type:"dark",import:()=>H(()=>import("./vitesse-dark-D0r3Knsf.js"),[])},{id:"vitesse-light",displayName:"Vitesse Light",type:"light",import:()=>H(()=>import("./vitesse-light-CVO1_9PV.js"),[])}],Q7=Object.fromEntries(J7.map(t=>[t.id,t.import]));let fa=class extends Error{constructor(e){super(e),this.name="ShikiError"}}
vendor: 50,975 bytes, lines 524-526
524,p0=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function Z7(){return 2147483648}function e9(){return typeof performance<"u"?performance.now():Date.now()}const t9=(t,e)=>t+(e-t%e)%e;async function r9(t){let e,r;const n={};function s(m){r=m,n.HEAPU8=new Uint8Array(m),n.HEAPU32=new Uint32Array(m)}function i(m,b,g){n.HEAPU8.copyWithin(m,b,b+g)}function a(m){try{return e.grow(m-r.byteLength+65535>>>16),s(e.buffer),1}catch{}}function o(m){const b=n.HEAPU8.length;m=m>>>0;const g=Z7();if(m>g)return!1;for(let p=1;p<=4;p*=2){let y=b*(1+.2/p);y=Math.min(y,m+100663296);const v=Math.min(g,t9(Math.max(m,y),65536));if(a(v))return!0}return!1}const l=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function c(m,b,g=1024){const p=b+g;let y=b;for(;m[y]&&!(y>=p);)++y;if(y-b>16&&m.buffer&&l)return l.decode(m.subarray(b,y));let v="";for(;b<y;){let _=m[b++];if(!(_&128)){v+=String.fromCharCode(_);continue}const w=m[b++]&63;if((_&224)===192){v+=String.fromCharCode((_&31)<<6|w);continue}const C=m[b++]&63;if((_&240)===224?_=(_&15)<<12|w<<6|C:_=(_&7)<<18|w<<12|C<<6|m[b++]&63,_<65536)v+=String.fromCharCode(_);else{const A=_-65536;v+=String.fromCharCode(55296|A>>10,56320|A&1023)}}return v}function u(m,b){return m?c(n.HEAPU8,m,b):""}const d={emscripten_get_now:e9,emscripten_memcpy_big:i,emscripten_resize_heap:o,fd_write:()=>0};async function h(){const b=await t({env:d,wasi_snapshot_preview1:d});e=b.memory,s(e.buffer),Object.assign(n,b),n.UTF8ToString=u}return await h(),n}var n9=Object.defineProperty,s9=(t,e,r)=>e in t?n9(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zn=(t,e,r)=>(s9(t,typeof e!="symbol"?e+"":e,r),r);let fs=null;function i9(t){throw new p0(t.UTF8ToString(t.getLastOnigError()))}class Om{constructor(e){Zn(this,"utf16Length"),Zn(this,"utf8Length"),Zn(this,"utf16Value"),Zn(this,"utf8Value"),Zn(this,"utf16OffsetToUtf8"),Zn(this,"utf8OffsetToUtf16");const r=e.length,n=Om._utf8ByteLength(e),s=n!==r,i=s?new Uint32Array(r+1):null;s&&(i[r]=n);const a=s?new Uint32Array(n+1):null;s&&(a[n]=r);const o=new Uint8Array(n);let l=0;for(let c=0;c<r;c++){const u=e.charCodeAt(c);let d=u,h=!1;if(u>=55296&&u<=56319&&c+1<r){const m=e.charCodeAt(c+1);m>=56320&&m<=57343&&(d=(u-55296<<10)+65536|m-56320,h=!0)}s&&(i[c]=l,h&&(i[c+1]=l),d<=127?a[l+0]=c:d<=2047?(a[l+0]=c,a[l+1]=c):d<=65535?(a[l+0]=c,a[l+1]=c,a[l+2]=c):(a[l+0]=c,a[l+1]=c,a[l+2]=c,a[l+3]=c)),d<=127?o[l++]=d:d<=2047?(o[l++]=192|(d&1984)>>>6,o[l++]=128|(d&63)>>>0):d<=65535?(o[l++]=224|(d&61440)>>>12,o[l++]=128|(d&4032)>>>6,o[l++]=128|(d&63)>>>0):(o[l++]=240|(d&1835008)>>>18,o[l++]=128|(d&258048)>>>12,o[l++]=128|(d&4032)>>>6,o[l++]=128|(d&63)>>>0),h&&c++}this.utf16Length=r,this.utf8Length=n,this.utf16Value=e,this.utf8Value=o,this.utf16OffsetToUtf8=i,this.utf8OffsetToUtf16=a}static _utf8ByteLength(e){let r=0;for(let n=0,s=e.length;n<s;n++){const i=e.charCodeAt(n);let a=i,o=!1;if(i>=55296&&i<=56319&&n+1<s){const l=e.charCodeAt(n+1);l>=56320&&l<=57343&&(a=(i-55296<<10)+65536|l-56320,o=!0)}a<=127?r+=1:a<=2047?r+=2:a<=65535?r+=3:r+=4,o&&n++}return r}createString(e){const r=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,r),r}}const Io=class{constructor(t){if(Zn(this,"id",++Io.LAST_ID),Zn(this,"_onigBinding"),Zn(this,"content"),Zn(this,"utf16Length"),Zn(this,"utf8Length"),Zn(this,"utf16OffsetToUtf8"),Zn(this,"utf8OffsetToUtf16"),Zn(this,"ptr"),!fs)throw new p0("Must invoke loadWasm first.");this._onigBinding=fs,this.content=t;const e=new Om(t);this.utf16Length=e.utf16Length,this.utf8Length=e.utf8Length,this.utf16OffsetToUtf8=e.utf16OffsetToUtf8,this.utf8OffsetToUtf16=e.utf8OffsetToUtf16,this.utf8Length<1e4&&!Io._sharedPtrInUse?(Io._sharedPtr||(Io._sharedPtr=fs.omalloc(1e4)),Io._sharedPtrInUse=!0,fs.HEAPU8.set(e.utf8Value,Io._sharedPtr),this.ptr=Io._sharedPtr):this.ptr=e.createString(fs)}convertUtf8OffsetToUtf16(t){return this.utf8OffsetToUtf16?t<0?0:t>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[t]:t}convertUtf16OffsetToUtf8(t){return this.utf16OffsetToUtf8?t<0?0:t>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[t]:t}dispose(){this.ptr===Io._sharedPtr?Io._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};let _h=Io;Zn(_h,"LAST_ID",0);Zn(_h,"_sharedPtr",0);Zn(_h,"_sharedPtrInUse",!1);class o9{constructor(e){if(Zn(this,"_onigBinding"),Zn(this,"_ptr"),!fs)throw new p0("Must invoke loadWasm first.");const r=[],n=[];for(let o=0,l=e.length;o<l;o++){const c=new Om(e[o]);r[o]=c.createString(fs),n[o]=c.utf8Length}const s=fs.omalloc(4*e.length);fs.HEAPU32.set(r,s/4);const i=fs.omalloc(4*e.length);fs.HEAPU32.set(n,i/4);const a=fs.createOnigScanner(s,i,e.length);for(let o=0,l=e.length;o<l;o++)fs.ofree(r[o]);fs.ofree(i),fs.ofree(s),a===0&&i9(fs),this._onigBinding=fs,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,r,n){let s=0;if(typeof n=="number"&&(s=n),typeof e=="string"){e=new _h(e);const i=this._findNextMatchSync(e,r,!1,s);return e.dispose(),i}return this._findNextMatchSync(e,r,!1,s)}_findNextMatchSync(e,r,n,s){const i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(r),s);if(a===0)return null;const o=i.HEAPU32;let l=a/4;const c=o[l++],u=o[l++],d=[];for(let h=0;h<u;h++){const m=e.convertUtf8OffsetToUtf16(o[l++]),b=e.convertUtf8OffsetToUtf16(o[l++]);d[h]={start:m,end:b,length:b-m}}return{index:c,captureIndices:d}}}function a9(t){return typeof t.instantiator=="function"}function l9(t){return typeof t.default=="function"}function c9(t){return typeof t.data<"u"}function u9(t){return typeof Response<"u"&&t instanceof Response}function d9(t){return typeof ArrayBuffer<"u"&&(t instanceof ArrayBuffer||ArrayBuffer.isView(t))||typeof Nx<"u"&&Nx.isBuffer?.(t)||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||typeof Uint32Array<"u"&&t instanceof Uint32Array}let Af;function h9(t){if(Af)return Af;async function e(){fs=await r9(async r=>{let n=t;return n=await n,typeof n=="function"&&(n=await n(r)),typeof n=="function"&&(n=await n(r)),a9(n)?n=await n.instantiator(r):l9(n)?n=await n.default(r):(c9(n)&&(n=n.data),u9(n)?typeof WebAssembly.instantiateStreaming=="function"?n=await f9(n)(r):n=await p9(n)(r):d9(n)?n=await Db(n)(r):n instanceof WebAssembly.Module?n=await Db(n)(r):"default"in n&&n.default instanceof WebAssembly.Module&&(n=await Db(n.default)(r))),"instance"in n&&(n=n.instance),"exports"in n&&(n=n.exports),n})}return Af=e(),Af}function Db(t){return e=>WebAssembly.instantiate(t,e)}function f9(t){return e=>WebAssembly.instantiateStreaming(t,e)}function p9(t){return async e=>{const r=await t.arrayBuffer();return WebAssembly.instantiate(r,e)}}let m9;function g9(){return m9}async function DI(t){return t&&await h9(t),{createScanner(e){return new o9(e.map(r=>typeof r=="string"?r:r.source))},createString(e){return new _h(e)}}}function b9(t){return m0(t)}function m0(t){return Array.isArray(t)?v9(t):t instanceof RegExp?t:typeof t=="object"?y9(t):t}function v9(t){let e=[];for(let r=0,n=t.length;r<n;r++)e[r]=m0(t[r]);return e}function y9(t){let e={};for(let r in t)e[r]=m0(t[r]);return e}function MI(t,...e){return e.forEach(r=>{for(let n in r)t[n]=r[n]}),t}function OI(t){const e=~t.lastIndexOf("/")||~t.lastIndexOf("\\");return e===0?t:~e===t.length-1?OI(t.substring(0,t.length-1)):t.substr(~e+1)}var Mb=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Ef=class{static hasCaptures(t){return t===null?!1:(Mb.lastIndex=0,Mb.test(t))}static replaceCaptures(t,e,r){return t.replace(Mb,(n,s,i,a)=>{let o=r[parseInt(s||i,10)];if(o){let l=e.substring(o.start,o.end);for(;l[0]===".";)l=l.substring(1);switch(a){case"downcase":return l.toLowerCase();case"upcase":return l.toUpperCase();default:return l}}else return n})}};function jI(t,e){return t<e?-1:t>e?1:0}function $I(t,e){if(t===null&&e===null)return 0;if(!t)return-1;if(!e)return 1;let r=t.length,n=e.length;if(r===n){for(let s=0;s<r;s++){let i=jI(t[s],e[s]);if(i!==0)return i}return 0}return r-n}function GC(t){return!!(/^#[0-9a-f]{6}$/i.test(t)||/^#[0-9a-f]{8}$/i.test(t)||/^#[0-9a-f]{3}$/i.test(t)||/^#[0-9a-f]{4}$/i.test(t))}function BI(t){return t.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var FI=class{constructor(t){this.fn=t}cache=new Map;get(t){if(this.cache.has(t))return this.cache.get(t);const e=this.fn(t);return this.cache.set(t,e),e}},Vp=class{constructor(t,e,r){this._colorMap=t,this._defaults=e,this._root=r}static createFromRawTheme(t,e){return this.createFromParsedTheme(w9(t),e)}static createFromParsedTheme(t,e){return C9(t,e)}_cachedMatchRoot=new FI(t=>this._root.match(t));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(t){if(t===null)return this._defaults;const e=t.scopeName,n=this._cachedMatchRoot.get(e).find(s=>_9(t.parent,s.parentScopes));return n?new WI(n.fontStyle,n.foreground,n.background):null}},Ob=class Yf{constructor(e,r){this.parent=e,this.scopeName=r}static push(e,r){for(const n of r)e=new Yf(e,n);return e}static from(...e){let r=null;for(let n=0;n<e.length;n++)r=new Yf(r,e[n]);return r}push(e){return new Yf(this,e)}getSegments(){let e=this;const r=[];for(;e;)r.push(e.scopeName),e=e.parent;return r.reverse(),r}toString(){return this.getSegments().join(" ")}extends(e){return this===e?!0:this.parent===null?!1:this.parent.extends(e)}getExtensionIfDefined(e){const r=[];let n=this;for(;n&&n!==e;)r.push(n.scopeName),n=n.parent;return n===e?r.reverse():void 0}};function _9(t,e){if(e.length===0)return!0;for(let r=0;r<e.length;r++){let n=e[r],s=!1;if(n===">"){if(r===e.length-1)return!1;n=e[++r],s=!0}for(;t&&!x9(t.scopeName,n);){if(s)return!1;t=t.parent}if(!t)return!1;t=t.parent}return!0}function x9(t,e){return e===t||t.startsWith(e)&&t[e.length]==="."}var WI=class{constructor(t,e,r){this.fontStyle=t,this.foregroundId=e,this.backgroundId=r}};function w9(t){if(!t)return[];if(!t.settings||!Array.isArray(t.settings))return[];let e=t.settings,r=[],n=0;for(let s=0,i=e.length;s<i;s++){let a=e[s];if(!a.settings)continue;let o;if(typeof a.scope=="string"){let d=a.scope;d=d.replace(/^[,]+/,""),d=d.replace(/[,]+$/,""),o=d.split(",")}else Array.isArray(a.scope)?o=a.scope:o=[""];let l=-1;if(typeof a.settings.fontStyle=="string"){l=0;let d=a.settings.fontStyle.split(" ");for(let h=0,m=d.length;h<m;h++)switch(d[h]){case"italic":l=l|1;break;case"bold":l=l|2;break;case"underline":l=l|4;break;case"strikethrough":l=l|8;break}}let c=null;typeof a.settings.foreground=="string"&&GC(a.settings.foreground)&&(c=a.settings.foreground);let u=null;typeof a.settings.background=="string"&&GC(a.settings.background)&&(u=a.settings.background);for(let d=0,h=o.length;d<h;d++){let b=o[d].trim().split(" "),g=b[b.length-1],p=null;b.length>1&&(p=b.slice(0,b.length-1),p.reverse()),r[n++]=new S9(g,p,s,l,c,u)}}return r}var S9=class{constructor(t,e,r,n,s,i){this.scope=t,this.parentScopes=e,this.index=r,this.fontStyle=n,this.foreground=s,this.background=i}},ua=(t=>(t[t.NotSet=-1]="NotSet",t[t.None=0]="None",t[t.Italic=1]="Italic",t[t.Bold=2]="Bold",t[t.Underline=4]="Underline",t[t.Strikethrough=8]="Strikethrough",t))(ua||{});function C9(t,e){t.sort((l,c)=>{let u=jI(l.scope,c.scope);return u!==0||(u=$I(l.parentScopes,c.parentScopes),u!==0)?u:l.index-c.index});let r=0,n="#000000",s="#ffffff";for(;t.length>=1&&t[0].scope==="";){let l=t.shift();l.fontStyle!==-1&&(r=l.fontStyle),l.foreground!==null&&(n=l.foreground),l.background!==null&&(s=l.background)}let i=new A9(e),a=new WI(r,i.getId(n),i.getId(s)),o=new k9(new Ny(0,null,-1,0,0),[]);for(let l=0,c=t.length;l<c;l++){let u=t[l];o.insert(0,u.scope,u.parentScopes,u.fontStyle,i.getId(u.foreground),i.getId(u.background))}return new Vp(i,a,o)}var A9=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(t){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(t)){this._isFrozen=!0;for(let e=0,r=t.length;e<r;e++)this._color2id[t[e]]=e,this._id2color[e]=t[e]}else this._isFrozen=!1}getId(t){if(t===null)return 0;t=t.toUpperCase();let e=this._color2id[t];if(e)return e;if(this._isFrozen)throw new Error(`Missing color in color map - ${t}`);return e=++this._lastColorId,this._color2id[t]=e,this._id2color[e]=t,e}getColorMap(){return this._id2color.slice(0)}},E9=Object.freeze([]),Ny=class HI{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,r,n,s,i){this.scopeDepth=e,this.parentScopes=r||E9,this.fontStyle=n,this.foreground=s,this.background=i}clone(){return new HI(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let r=[];for(let n=0,s=e.length;n<s;n++)r[n]=e[n].clone();return r}acceptOverwrite(e,r,n,s){this.scopeDepth>e?console.log("how did this happen?"):this.scopeDepth=e,r!==-1&&(this.fontStyle=r),n!==0&&(this.foreground=n),s!==0&&(this.background=s)}},k9=class Ly{constructor(e,r=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=r}_rulesWithParentScopes;static _cmpBySpecificity(e,r){if(e.scopeDepth!==r.scopeDepth)return r.scopeDepth-e.scopeDepth;let n=0,s=0;for(;e.parentScopes[n]===">"&&n++,r.parentScopes[s]===">"&&s++,!(n>=e.parentScopes.length||s>=r.parentScopes.length);){const i=r.parentScopes[s].length-e.parentScopes[n].length;if(i!==0)return i;n++,s++}return r.parentScopes.length-e.parentScopes.length}match(e){if(e!==""){let n=e.indexOf("."),s,i;if(n===-1?(s=e,i=""):(s=e.substring(0,n),i=e.substring(n+1)),this._children.hasOwnProperty(s))return this._children[s].match(i)}const r=this._rulesWithParentScopes.concat(this._mainRule);return r.sort(Ly._cmpBySpecificity),r}insert(e,r,n,s,i,a){if(r===""){this._doInsertHere(e,n,s,i,a);return}let o=r.indexOf("."),l,c;o===-1?(l=r,c=""):(l=r.substring(0,o),c=r.substring(o+1));let u;this._children.hasOwnProperty(l)?u=this._children[l]:(u=new Ly(this._mainRule.clone(),Ny.cloneArr(this._rulesWithParentScopes)),this._children[l]=u),u.insert(e+1,c,n,s,i,a)}_doInsertHere(e,r,n,s,i){if(r===null){this._mainRule.acceptOverwrite(e,n,s,i);return}for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let l=this._rulesWithParentScopes[a];if($I(l.parentScopes,r)===0){l.acceptOverwrite(e,n,s,i);return}}n===-1&&(n=this._mainRule.fontStyle),s===0&&(s=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new Ny(e,r,n,s,i))}},uu=class Vi{static toBinaryStr(e){return e.toString(2).padStart(32,"0")}static print(e){const r=Vi.getLanguageId(e),n=Vi.getTokenType(e),s=Vi.getFontStyle(e),i=Vi.getForeground(e),a=Vi.getBackground(e);console.log({languageId:r,tokenType:n,fontStyle:s,foreground:i,background:a})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return(e&1024)!==0}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(e,r,n,s,i,a,o){let l=Vi.getLanguageId(e),c=Vi.getTokenType(e),u=Vi.containsBalancedBrackets(e)?1:0,d=Vi.getFontStyle(e),h=Vi.getForeground(e),m=Vi.getBackground(e);return r!==0&&(l=r),n!==8&&(c=n),s!==null&&(u=s?1:0),i!==-1&&(d=i),a!==0&&(h=a),o!==0&&(m=o),(l<<0|c<<8|u<<10|d<<11|h<<15|m<<24)>>>0}};function Gp(t,e){const r=[],n=P9(t);let s=n.next();for(;s!==null;){let l=0;if(s.length===2&&s.charAt(1)===":"){switch(s.charAt(0)){case"R":l=1;break;case"L":l=-1;break;default:console.log(`Unknown priority ${s} in scope selector`)}s=n.next()}let c=a();if(r.push({matcher:c,priority:l}),s!==",")break;s=n.next()}return r;function i(){if(s==="-"){s=n.next();const l=i();return c=>!!l&&!l(c)}if(s==="("){s=n.next();const l=o();return s===")"&&(s=n.next()),l}if(qC(s)){const l=[];do l.push(s),s=n.next();while(qC(s));return c=>e(l,c)}return null}function a(){const l=[];let c=i();for(;c;)l.push(c),c=i();return u=>l.every(d=>d(u))}function o(){const l=[];let c=a();for(;c&&(l.push(c),s==="|"||s===",");){do s=n.next();while(s==="|"||s===",");c=a()}return u=>l.some(d=>d(u))}}function qC(t){return!!t&&!!t.match(/[\w\.:]+/)}function P9(t){let e=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,r=e.exec(t);return{next:()=>{if(!r)return null;const n=r[0];return r=e.exec(t),n}}}function UI(t){typeof t.dispose=="function"&&t.dispose()}var qd=class{constructor(t){this.scopeName=t}toKey(){return this.scopeName}},T9=class{constructor(t,e){this.scopeName=t,this.ruleName=e}toKey(){return`${this.scopeName}#${this.ruleName}`}},R9=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(t){const e=t.toKey();this._seenReferenceKeys.has(e)||(this._seenReferenceKeys.add(e),this._references.push(t))}},I9=class{constructor(t,e){this.repo=t,this.initialScopeName=e,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new qd(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){const t=this.Q;this.Q=[];const e=new R9;for(const r of t)N9(r,this.initialScopeName,this.repo,e);for(const r of e.references)if(r instanceof qd){if(this.seenFullScopeRequests.has(r.scopeName))continue;this.seenFullScopeRequests.add(r.scopeName),this.Q.push(r)}else{if(this.seenFullScopeRequests.has(r.scopeName)||this.seenPartialScopeRequests.has(r.toKey()))continue;this.seenPartialScopeRequests.add(r.toKey()),this.Q.push(r)}}};function N9(t,e,r,n){const s=r.lookup(t.scopeName);if(!s){if(t.scopeName===e)throw new Error(`No grammar provided for <${e}>`);return}const i=r.lookup(e);t instanceof qd?Xf({baseGrammar:i,selfGrammar:s},n):Dy(t.ruleName,{baseGrammar:i,selfGrammar:s,repository:s.repository},n);const a=r.injections(t.scopeName);if(a)for(const o of a)n.add(new qd(o))}function Dy(t,e,r){if(e.repository&&e.repository[t]){const n=e.repository[t];qp([n],e,r)}}function Xf(t,e){t.selfGrammar.patterns&&Array.isArray(t.selfGrammar.patterns)&&qp(t.selfGrammar.patterns,{...t,repository:t.selfGrammar.repository},e),t.selfGrammar.injections&&qp(Object.values(t.selfGrammar.injections),{...t,repository:t.selfGrammar.repository},e)}function qp(t,e,r){for(const n of t){if(r.visitedRule.has(n))continue;r.visitedRule.add(n);const s=n.repository?MI({},e.repository,n.repository):e.repository;Array.isArray(n.patterns)&&qp(n.patterns,{...e,repository:s},r);const i=n.include;if(!i)continue;const a=zI(i);switch(a.kind){case 0:Xf({...e,selfGrammar:e.baseGrammar},r);break;case 1:Xf(e,r);break;case 2:Dy(a.ruleName,{...e,repository:s},r);break;case 3:case 4:const o=a.scopeName===e.selfGrammar.scopeName?e.selfGrammar:a.scopeName===e.baseGrammar.scopeName?e.baseGrammar:void 0;if(o){const l={baseGrammar:e.baseGrammar,selfGrammar:o,repository:s};a.kind===4?Dy(a.ruleName,l,r):Xf(l,r)}else a.kind===4?r.add(new T9(a.scopeName,a.ruleName)):r.add(new qd(a.scopeName));break}}}var L9=class{kind=0},D9=class{kind=1},M9=class{constructor(t){this.ruleName=t}kind=2},O9=class{constructor(t){this.scopeName=t}kind=3},j9=class{constructor(t,e){this.scopeName=t,this.ruleName=e}kind=4};function zI(t){if(t==="$base")return new L9;if(t==="$self")return new D9;const e=t.indexOf("#");if(e===-1)return new O9(t);if(e===0)return new M9(t.substring(1));{const r=t.substring(0,e),n=t.substring(e+1);return new j9(r,n)}}var $9=/\\(\d+)/,KC=/\\(\d+)/g,B9=-1,VI=-2;var xh=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(t,e,r,n){this.$location=t,this.id=e,this._name=r||null,this._nameIsCapturing=Ef.hasCaptures(this._name),this._contentName=n||null,this._contentNameIsCapturing=Ef.hasCaptures(this._contentName)}get debugName(){const t=this.$location?`${OI(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${t}`}getName(t,e){return!this._nameIsCapturing||this._name===null||t===null||e===null?this._name:Ef.replaceCaptures(this._name,t,e)}getContentName(t,e){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Ef.replaceCaptures(this._contentName,t,e)}},F9=class extends xh{retokenizeCapturedWithRuleId;constructor(t,e,r,n,s){super(t,e,r,n),this.retokenizeCapturedWithRuleId=s}dispose(){}collectPatterns(t,e){throw new Error("Not supported!")}compile(t,e){throw new Error("Not supported!")}compileAG(t,e,r,n){throw new Error("Not supported!")}},W9=class extends xh{_match;captures;_cachedCompiledPatterns;constructor(t,e,r,n,s){super(t,e,r,null),this._match=new Kd(n,this.id),this.captures=s,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(t,e){e.push(this._match)}compile(t,e){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,e,r,n){return this._getCachedCompiledPatterns(t).compileAG(t,r,n)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Yd,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},YC=class extends xh{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(t,e,r,n,s){super(t,e,r,n),this.patterns=s.patterns,this.hasMissingPatterns=s.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(t,e){for(const r of this.patterns)t.getRule(r).collectPatterns(t,e)}compile(t,e){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,e,r,n){return this._getCachedCompiledPatterns(t).compileAG(t,r,n)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Yd,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},My=class extends xh{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(t,e,r,n,s,i,a,o,l,c){super(t,e,r,n),this._begin=new Kd(s,this.id),this.beginCaptures=i,this._end=new Kd(a||"ï¿¿",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=o,this.applyEndPatternLast=l||!1,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(t,e){return this._end.resolveBackReferences(t,e)}collectPatterns(t,e){e.push(this._begin)}compile(t,e){return this._getCachedCompiledPatterns(t,e).compile(t)}compileAG(t,e,r,n){return this._getCachedCompiledPatterns(t,e).compileAG(t,r,n)}_getCachedCompiledPatterns(t,e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Yd;for(const r of this.patterns)t.getRule(r).collectPatterns(t,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,e):this._cachedCompiledPatterns.setSource(0,e)),this._cachedCompiledPatterns}},Kp=class extends xh{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(t,e,r,n,s,i,a,o,l){super(t,e,r,n),this._begin=new Kd(s,this.id),this.beginCaptures=i,this.whileCaptures=o,this._while=new Kd(a,VI),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(t,e){return this._while.resolveBackReferences(t,e)}collectPatterns(t,e){e.push(this._begin)}compile(t,e){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,e,r,n){return this._getCachedCompiledPatterns(t).compileAG(t,r,n)}_getCachedCompiledPatterns(t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Yd;for(const e of this.patterns)t.getRule(e).collectPatterns(t,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(t,e){return this._getCachedCompiledWhilePatterns(t,e).compile(t)}compileWhileAG(t,e,r,n){return this._getCachedCompiledWhilePatterns(t,e).compileAG(t,r,n)}_getCachedCompiledWhilePatterns(t,e){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Yd,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,e||"ï¿¿"),this._cachedCompiledWhilePatterns}},GI=class Bs{static createCaptureRule(e,r,n,s,i){return e.registerRule(a=>new F9(r,a,n,s,i))}static getCompiledRuleId(e,r,n){return e.id||r.registerRule(s=>{if(e.id=s,e.match)return new W9(e.$vscodeTextmateLocation,e.id,e.name,e.match,Bs._compileCaptures(e.captures,r,n));if(typeof e.begin>"u"){e.repository&&(n=MI({},n,e.repository));let i=e.patterns;return typeof i>"u"&&e.include&&(i=[{include:e.include}]),new YC(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,Bs._compilePatterns(i,r,n))}return e.while?new Kp(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,Bs._compileCaptures(e.beginCaptures||e.captures,r,n),e.while,Bs._compileCaptures(e.whileCaptures||e.captures,r,n),Bs._compilePatterns(e.patterns,r,n)):new My(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,Bs._compileCaptures(e.beginCaptures||e.captures,r,n),e.end,Bs._compileCaptures(e.endCaptures||e.captures,r,n),e.applyEndPatternLast,Bs._compilePatterns(e.patterns,r,n))}),e.id}static _compileCaptures(e,r,n){let s=[];if(e){let i=0;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const o=parseInt(a,10);o>i&&(i=o)}for(let a=0;a<=i;a++)s[a]=null;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const o=parseInt(a,10);let l=0;e[a].patterns&&(l=Bs.getCompiledRuleId(e[a],r,n)),s[o]=Bs.createCaptureRule(r,e[a].$vscodeTextmateLocation,e[a].name,e[a].contentName,l)}}return s}static _compilePatterns(e,r,n){let s=[];if(e)for(let i=0,a=e.length;i<a;i++){const o=e[i];let l=-1;if(o.include){const c=zI(o.include);switch(c.kind){case 0:case 1:l=Bs.getCompiledRuleId(n[o.include],r,n);break;case 2:let u=n[c.ruleName];u&&(l=Bs.getCompiledRuleId(u,r,n));break;case 3:case 4:const d=c.scopeName,h=c.kind===4?c.ruleName:null,m=r.getExternalGrammar(d,n);if(m)if(h){let b=m.repository[h];b&&(l=Bs.getCompiledRuleId(b,r,m.repository))}else l=Bs.getCompiledRuleId(m.repository.$self,r,m.repository);break}}else l=Bs.getCompiledRuleId(o,r,n);if(l!==-1){const c=r.getRule(l);let u=!1;if((c instanceof YC||c instanceof My||c instanceof Kp)&&c.hasMissingPatterns&&c.patterns.length===0&&(u=!0),u)continue;s.push(l)}}return{patterns:s,hasMissingPatterns:(e?e.length:0)!==s.length}}},Kd=class qI{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,r){if(e&&typeof e=="string"){const n=e.length;let s=0,i=[],a=!1;for(let o=0;o<n;o++)if(e.charAt(o)==="\\"&&o+1<n){const c=e.charAt(o+1);c==="z"?(i.push(e.substring(s,o)),i.push("$(?!\\n)(?<!\\n)"),s=o+2):(c==="A"||c==="G")&&(a=!0),o++}this.hasAnchor=a,s===0?this.source=e:(i.push(e.substring(s,n)),this.source=i.join(""))}else this.hasAnchor=!1,this.source=e;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=r,typeof this.source=="string"?this.hasBackReferences=$9.test(this.source):this.hasBackReferences=!1}clone(){return new qI(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,r){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let n=r.map(s=>e.substring(s.start,s.end));return KC.lastIndex=0,this.source.replace(KC,(s,i)=>BI(n[parseInt(i,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let e=[],r=[],n=[],s=[],i,a,o,l;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,r[i]=o,n[i]=o,s[i]=o,o==="\\"&&i+1<a&&(l=this.source.charAt(i+1),l==="A"?(e[i+1]="ï¿¿",r[i+1]="ï¿¿",n[i+1]="A",s[i+1]="A"):l==="G"?(e[i+1]="ï¿¿",r[i+1]="G",n[i+1]="ï¿¿",s[i+1]="G"):(e[i+1]=l,r[i+1]=l,n[i+1]=l,s[i+1]=l),i++);return{A0_G0:e.join(""),A0_G1:r.join(""),A1_G0:n.join(""),A1_G1:s.join("")}}resolveAnchors(e,r){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:e?r?this._anchorCache.A1_G1:this._anchorCache.A1_G0:r?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Yd=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(),this._cached=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(t){this._items.push(t),this._hasAnchors=this._hasAnchors||t.hasAnchor}unshift(t){this._items.unshift(t),this._hasAnchors=this._hasAnchors||t.hasAnchor}length(){return this._items.length}setSource(t,e){this._items[t].source!==e&&(this._disposeCaches(),this._items[t].setSource(e))}compile(t){if(!this._cached){let e=this._items.map(r=>r.source);this._cached=new XC(t,e,this._items.map(r=>r.ruleId))}return this._cached}compileAG(t,e,r){return this._hasAnchors?e?r?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(t,e,r)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(t,e,r)),this._anchorCache.A1_G0):r?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(t,e,r)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(t,e,r)),this._anchorCache.A0_G0):this.compile(t)}_resolveAnchors(t,e,r){let n=this._items.map(s=>s.resolveAnchors(e,r));return new XC(t,n,this._items.map(s=>s.ruleId))}},XC=class{constructor(t,e,r){this.regExps=e,this.rules=r,this.scanner=t.createOnigScanner(e)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){const t=[];for(let e=0,r=this.rules.length;e<r;e++)t.push(" - "+this.rules[e]+": "+this.regExps[e]);return t.join(` 525`)}findNextMatchSync(t,e,r){const n=this.scanner.findNextMatchSync(t,e,r);return n?{ruleId:this.rules[n.index],captureIndices:n.captureIndices}:null}},jb=class{constructor(t,e){this.languageId=t,this.tokenType=e}},H9=class Oy{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,r){this._defaultAttributes=new jb(e,8),this._embeddedLanguagesMatcher=new U9(Object.entries(r||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(e){return e===null?Oy._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(e)}static _NULL_SCOPE_METADATA=new jb(0,0);_getBasicScopeAttributes=new FI(e=>{const r=this._scopeToLanguage(e),n=this._toStandardTokenType(e);return new jb(r,n)});_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(e){const r=e.match(Oy.STANDARD_TOKEN_TYPE_REGEXP);if(!r)return 8;switch(r[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},U9=class{values;scopesRegExp;constructor(t){if(t.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(t);const e=t.map(([r,n])=>BI(r));e.sort(),e.reverse(),this.scopesRegExp=new RegExp(`^((${e.join(")|(")}))($|\\.)`,"")}}match(t){if(!this.scopesRegExp)return;const e=t.match(this.scopesRegExp);if(e)return this.values.get(e[1])}},JC=class{constructor(t,e){this.stack=t,this.stoppedEarly=e}};function KI(t,e,r,n,s,i,a,o){const l=e.content.length;let c=!1,u=-1;if(a){const m=z9(t,e,r,n,s,i);s=m.stack,n=m.linePos,r=m.isFirstLine,u=m.anchorPosition}const d=Date.now();for(;!c;){if(o!==0&&Date.now()-d>o)return new JC(s,!0);h()}return new JC(s,!1);function h(){const m=V9(t,e,r,n,s,u);if(!m){i.produce(s,l),c=!0;return}const b=m.captureIndices,g=m.matchedRuleId,p=b&&b.length>0?b[0].end>n:!1;if(g===B9){const y=s.getRule(t);i.produce(s,b[0].start),s=s.withContentNameScopesList(s.nameScopesList),od(t,e,r,s,i,y.endCaptures,b),i.produce(s,b[0].end);const v=s;if(s=s.parent,u=v.getAnchorPos(),!p&&v.getEnterPos()===n){s=v,i.produce(s,l),c=!0;return}}else{const y=t.getRule(g);i.produce(s,b[0].start);const v=s,_=y.getName(e.content,b),w=s.contentNameScopesList.pushAttributed(_,t);if(s=s.push(g,n,u,b[0].end===l,null,w,w),y instanceof My){const C=y;od(t,e,r,s,i,C.beginCaptures,b),i.produce(s,b[0].end),u=b[0].end;const A=C.getContentName(e.content,b),E=w.pushAttributed(A,t);if(s=s.withContentNameScopesList(E),C.endHasBackReferences&&(s=s.withEndRule(C.getEndWithResolvedBackReferences(e.content,b))),!p&&v.hasSameRuleAs(s)){s=s.pop(),i.produce(s,l),c=!0;return}}else if(y instanceof Kp){const C=y;od(t,e,r,s,i,C.beginCaptures,b),i.produce(s,b[0].end),u=b[0].end;const A=C.getContentName(e.content,b),E=w.pushAttributed(A,t);if(s=s.withContentNameScopesList(E),C.whileHasBackReferences&&(s=s.withEndRule(C.getWhileWithResolvedBackReferences(e.content,b))),!p&&v.hasSameRuleAs(s)){s=s.pop(),i.produce(s,l),c=!0;return}}else if(od(t,e,r,s,i,y.captures,b),i.produce(s,b[0].end),s=s.pop(),!p){s=s.safePop(),i.produce(s,l),c=!0;return}}b[0].end>n&&(n=b[0].end,r=!1)}}function z9(t,e,r,n,s,i){let a=s.beginRuleCapturedEOL?0:-1;const o=[];for(let l=s;l;l=l.pop()){const c=l.getRule(t);c instanceof Kp&&o.push({rule:c,stack:l})}for(let l=o.pop();l;l=o.pop()){const{ruleScanner:c,findOptions:u}=K9(l.rule,t,l.stack.endRule,r,n===a),d=c.findNextMatchSync(e,n,u);if(d){if(d.ruleId!==VI){s=l.stack.pop();break}d.captureIndices&&d.captureIndices.length&&(i.produce(l.stack,d.captureIndices[0].start),od(t,e,r,l.stack,i,l.rule.whileCaptures,d.captureIndices),i.produce(l.stack,d.captureIndices[0].end),a=d.captureIndices[0].end,d.captureIndices[0].end>n&&(n=d.captureIndices[0].end,r=!1))}else{s=l.stack.pop();break}}return{stack:s,linePos:n,anchorPosition:a,isFirstLine:r}}function V9(t,e,r,n,s,i){const a=G9(t,e,r,n,s,i),o=t.getInjections();if(o.length===0)return a;const l=q9(o,t,e,r,n,s,i);if(!l)return a;if(!a)return l;const c=a.captureIndices[0].start,u=l.captureIndices[0].start;return u<c||l.priorityMatch&&u===c?l:a}function G9(t,e,r,n,s,i){const a=s.getRule(t),{ruleScanner:o,findOptions:l}=YI(a,t,s.endRule,r,n===i),c=o.findNextMatchSync(e,n,l);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function q9(t,e,r,n,s,i,a){let o=Number.MAX_VALUE,l=null,c,u=0;const d=i.contentNameScopesList.getScopeNames();for(let h=0,m=t.length;h<m;h++){const b=t[h];if(!b.matcher(d))continue;const g=e.getRule(b.ruleId),{ruleScanner:p,findOptions:y}=YI(g,e,null,n,s===a),v=p.findNextMatchSync(r,s,y);if(!v)continue;const _=v.captureIndices[0].start;if(!(_>=o)&&(o=_,l=v.captureIndices,c=v.ruleId,u=b.priority,o===s))break}return l?{priorityMatch:u===-1,captureIndices:l,matchedRuleId:c}:null}function YI(t,e,r,n,s){return{ruleScanner:t.compileAG(e,r,n,s),findOptions:0}}function K9(t,e,r,n,s){return{ruleScanner:t.compileWhileAG(e,r,n,s),findOptions:0}}function od(t,e,r,n,s,i,a){if(i.length===0)return;const o=e.content,l=Math.min(i.length,a.length),c=[],u=a[0].end;for(let d=0;d<l;d++){const h=i[d];if(h===null)continue;const m=a[d];if(m.length===0)continue;if(m.start>u)break;for(;c.length>0&&c[c.length-1].endPos<=m.start;)s.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?s.produceFromScopes(c[c.length-1].scopes,m.start):s.produce(n,m.start),h.retokenizeCapturedWithRuleId){const g=h.getName(o,a),p=n.contentNameScopesList.pushAttributed(g,t),y=h.getContentName(o,a),v=p.pushAttributed(y,t),_=n.push(h.retokenizeCapturedWithRuleId,m.start,-1,!1,null,p,v),w=t.createOnigString(o.substring(0,m.end));KI(t,w,r&&m.start===0,m.start,_,s,!1,0),UI(w);continue}const b=h.getName(o,a);if(b!==null){const p=(c.length>0?c[c.length-1].scopes:n.contentNameScopesList).pushAttributed(b,t);c.push(new Y9(p,m.end))}}for(;c.length>0;)s.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var Y9=class{scopes;endPos;constructor(t,e){this.scopes=t,this.endPos=e}};function X9(t,e,r,n,s,i,a,o){return new Q9(t,e,r,n,s,i,a,o)}function QC(t,e,r,n,s){const i=Gp(e,Yp),a=GI.getCompiledRuleId(r,n,s.repository);for(const o of i)t.push({debugSelector:e,matcher:o.matcher,ruleId:a,grammar:s,priority:o.priority})}function Yp(t,e){if(e.length<t.length)return!1;let r=0;return t.every(n=>{for(let s=r;s<e.length;s++)if(J9(e[s],n))return r=s+1,!0;return!1})}function J9(t,e){if(!t)return!1;if(t===e)return!0;const r=e.length;return t.length>r&&t.substr(0,r)===e&&t[r]==="."}var Q9=class{constructor(t,e,r,n,s,i,a,o){if(this._rootScopeName=t,this.balancedBracketSelectors=i,this._onigLib=o,this._basicScopeAttributesProvider=new H9(r,n),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=a,this._grammar=ZC(e,null),this._injections=null,this._tokenTypeMatchers=[],s)for(const l of Object.keys(s)){const c=Gp(l,Yp);for(const u of c)this._tokenTypeMatchers.push({matcher:u.matcher,type:s[l]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(const t of this._ruleId2desc)t&&t.dispose()}createOnigScanner(t){return this._onigLib.createOnigScanner(t)}createOnigString(t){return this._onigLib.createOnigString(t)}getMetadataForScope(t){return this._basicScopeAttributesProvider.getBasicScopeAttributes(t)}_collectInjections(){const t={lookup:s=>s===this._rootScopeName?this._grammar:this.getExternalGrammar(s),injections:s=>this._grammarRepository.injections(s)},e=[],r=this._rootScopeName,n=t.lookup(r);if(n){const s=n.injections;if(s)for(let a in s)QC(e,a,s[a],this,n);const i=this._grammarRepository.injections(r);i&&i.forEach(a=>{const o=this.getExternalGrammar(a);if(o){const l=o.injectionSelector;l&&QC(e,l,o,this,o)}})}return e.sort((s,i)=>s.priority-i.priority),e}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(t){const e=++this._lastRuleId,r=t(e);return this._ruleId2desc[e]=r,r}getRule(t){return this._ruleId2desc[t]}getExternalGrammar(t,e){if(this._includedGrammars[t])return this._includedGrammars[t];if(this._grammarRepository){const r=this._grammarRepository.lookup(t);if(r)return this._includedGrammars[t]=ZC(r,e&&e.$base),this._includedGrammars[t]}}tokenizeLine(t,e,r=0){const n=this._tokenize(t,e,!1,r);return{tokens:n.lineTokens.getResult(n.ruleStack,n.lineLength),ruleStack:n.ruleStack,stoppedEarly:n.stoppedEarly}}tokenizeLine2(t,e,r=0){const n=this._tokenize(t,e,!0,r);return{tokens:n.lineTokens.getBinaryResult(n.ruleStack,n.lineLength),ruleStack:n.ruleStack,stoppedEarly:n.stoppedEarly}}_tokenize(t,e,r,n){this._rootId===-1&&(this._rootId=GI.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let s;if(!e||e===jy.NULL){s=!0;const c=this._basicScopeAttributesProvider.getDefaultAttributes(),u=this.themeProvider.getDefaults(),d=uu.set(0,c.languageId,c.tokenType,null,u.fontStyle,u.foregroundId,u.backgroundId),h=this.getRule(this._rootId).getName(null,null);let m;h?m=_d.createRootAndLookUpScopeName(h,d,this):m=_d.createRoot("unknown",d),e=new jy(null,this._rootId,-1,-1,!1,null,m,m)}else s=!1,e.reset();t=t+` 526`;const i=this.createOnigString(t),a=i.content.length,o=new eK(r,t,this._tokenTypeMatchers,this.balancedBracketSelectors),l=KI(this,i,s,0,e,o,!0,n);return UI(i),{lineLength:a,lineTokens:o,ruleStack:l.stack,stoppedEarly:l.stoppedEarly}}};function ZC(t,e){return t=b9(t),t.repository=t.repository||{},t.repository.$self={$vscodeTextmateLocation:t.$vscodeTextmateLocation,patterns:t.patterns,name:t.scopeName},t.repository.$base=e||t.repository.$self,t}var _d=class No{constructor(e,r,n){this.parent=e,this.scopePath=r,this.tokenAttributes=n}static fromExtension(e,r){let n=e,s=e?.scopePath??null;for(const i of r)s=Ob.push(s,i.scopeNames),n=new No(n,s,i.encodedTokenAttributes);return n}static createRoot(e,r){return new No(null,new Ob(null,e),r)}static createRootAndLookUpScopeName(e,r,n){const s=n.getMetadataForScope(e),i=new Ob(null,e),a=n.themeProvider.themeMatch(i),o=No.mergeAttributes(r,s,a);return new No(null,i,o)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(e){return No.equals(this,e)}static equals(e,r){do{if(e===r||!e&&!r)return!0;if(!e||!r||e.scopeName!==r.scopeName||e.tokenAttributes!==r.tokenAttributes)return!1;e=e.parent,r=r.parent}while(!0)}static mergeAttributes(e,r,n){let s=-1,i=0,a=0;return n!==null&&(s=n.fontStyle,i=n.foregroundId,a=n.backgroundId),uu.set(e,r.languageId,r.tokenType,null,s,i,a)}pushAttributed(e,r){if(e===null)return this;if(e.indexOf(" ")===-1)return No._pushAttributed(this,e,r);const n=e.split(/ /g);let s=this;for(const i of n)s=No._pushAttributed(s,i,r);return s}static _pushAttributed(e,r,n){const s=n.getMetadataForScope(r),i=e.scopePath.push(r),a=n.themeProvider.themeMatch(i),o=No.mergeAttributes(e.tokenAttributes,s,a);return new No(e,i,o)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){const r=[];let n=this;for(;n&&n!==e;)r.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?r.reverse():void 0}},jy=class Dl{constructor(e,r,n,s,i,a,o,l){this.parent=e,this.ruleId=r,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=l,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=s}_stackElementBrand=void 0;static NULL=new Dl(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(e){return e===null?!1:Dl._equals(this,e)}static _equals(e,r){return e===r?!0:this._structuralEquals(e,r)?_d.equals(e.contentNameScopesList,r.contentNameScopesList):!1}static _structuralEquals(e,r){do{if(e===r||!e&&!r)return!0;if(!e||!r||e.depth!==r.depth||e.ruleId!==r.ruleId||e.endRule!==r.endRule)return!1;e=e.parent,r=r.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){Dl._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(e,r,n,s,i,a,o){return new Dl(this,e,r,n,s,i,a,o)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){const e=[];return this._writeString(e,0),"["+e.join(",")+"]"}_writeString(e,r){return this.parent&&(r=this.parent._writeString(e,r)),e[r++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,r}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(e){return this.endRule===e?this:new Dl(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,e,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let r=this;for(;r&&r._enterPos===e._enterPos;){if(r.ruleId===e.ruleId)return!0;r=r.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(e,r){const n=_d.fromExtension(e?.nameScopesList??null,r.nameScopesList);return new Dl(e,r.ruleId,r.enterPos??-1,r.anchorPos??-1,r.beginRuleCapturedEOL,r.endRule,n,_d.fromExtension(n,r.contentNameScopesList))}},Z9=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(t,e){this.balancedBracketScopes=t.flatMap(r=>r==="*"?(this.allowAny=!0,[]):Gp(r,Yp).map(n=>n.matcher)),this.unbalancedBracketScopes=e.flatMap(r=>Gp(r,Yp).map(n=>n.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(t){for(const e of this.unbalancedBracketScopes)if(e(t))return!1;for(const e of this.balancedBracketScopes)if(e(t))return!0;return this.allowAny}},eK=class{constructor(t,e,r,n){this.balancedBracketSelectors=n,this._emitBinaryTokens=t,this._tokenTypeOverrides=r,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(t,e){this.produceFromScopes(t.contentNameScopesList,e)}produceFromScopes(t,e){if(this._lastTokenEndIndex>=e)return;if(this._emitBinaryTokens){let n=t?.tokenAttributes??0,s=!1;if(this.balancedBracketSelectors?.matchesAlways&&(s=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){const i=t?.getScopeNames()??[];for(const a of this._tokenTypeOverrides)a.matcher(i)&&(n=uu.set(n,0,a.type,null,-1,0,0));this.balancedBracketSelectors&&(s=this.balancedBracketSelectors.match(i))}if(s&&(n=uu.set(n,0,8,s,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=e;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=e;return}const r=t?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:e,scopes:r}),this._lastTokenEndIndex=e}getResult(t,e){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===e-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(t,e),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(t,e){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===e-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(t,e),this._binaryTokens[this._binaryTokens.length-2]=0);const r=new Uint32Array(this._binaryTokens.length);for(let n=0,s=this._binaryTokens.length;n<s;n++)r[n]=this._binaryTokens[n];return r}},tK=class{constructor(t,e){this._onigLib=e,this._theme=t}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(const t of this._grammars.values())t.dispose()}setTheme(t){this._theme=t}getColorMap(){return this._theme.getColorMap()}addGrammar(t,e){this._rawGrammars.set(t.scopeName,t),e&&this._injectionGrammars.set(t.scopeName,e)}lookup(t){return this._rawGrammars.get(t)}injections(t){return this._injectionGrammars.get(t)}getDefaults(){return this._theme.getDefaults()}themeMatch(t){return this._theme.match(t)}grammarForScopeName(t,e,r,n,s){if(!this._grammars.has(t)){let i=this._rawGrammars.get(t);if(!i)return null;this._grammars.set(t,X9(t,i,e,r,n,s,this,this._onigLib))}return this._grammars.get(t)}},rK=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new tK(Vp.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,r){this._syncRegistry.setTheme(Vp.createFromRawTheme(e,r))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,r,n){return this.loadGrammarWithConfiguration(e,r,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,r,n){return this._loadGrammar(e,r,n.embeddedLanguages,n.tokenTypes,new Z9(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,r,n,s,i){const a=new I9(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(o=>this._loadSingleGrammar(o.scopeName)),a.processQueue();return this._grammarForScopeName(e,r,n,s,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){const r=this._options.loadGrammar(e);if(r){const n=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(r,n)}}addGrammar(e,r=[],n=0,s=null){return this._syncRegistry.addGrammar(e,r),this._grammarForScopeName(e.scopeName,n,s)}_grammarForScopeName(e,r=0,n=null,s=null,i=null){return this._syncRegistry.grammarForScopeName(e,r,n,s,i)}},$y=jy.NULL;const nK=/["&'<>`]/g,sK=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,iK=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,oK=/[|\\{}()[\]^$+*?.]/g,eA=new WeakMap;function aK(t,e){if(t=t.replace(e.subset?lK(e.subset):nK,n),e.subset||e.escapeOnly)return t;return t.replace(sK,r).replace(iK,n);function r(s,i,a){return e.format((s.charCodeAt(0)-55296)*1024+s.charCodeAt(1)-56320+65536,a.charCodeAt(i+2),e)}function n(s,i,a){return e.format(s.charCodeAt(0),a.charCodeAt(i+1),e)}}function lK(t){let e=eA.get(t);return e||(e=cK(t),eA.set(t,e)),e}function cK(t){const e=[];let r=-1;for(;++r<t.length;)e.push(t[r].replace(oK,"\\$&"));return new RegExp("(?:"+e.join("|")+")","g")}const uK=/[\dA-Fa-f]/;function dK(t,e,r){const n="&#x"+t.toString(16).toUpperCase();return r&&e&&!uK.test(String.fromCharCode(e))?n:n+";"}const hK=/\d/;function fK(t,e,r){const n="&#"+String(t);return r&&e&&!hK.test(String.fromCharCode(e))?n:n+";"}const pK=["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","oslas
526h","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"],$b={nbsp:" ",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
vendor: 11,654 bytes, lines 526-534
526:"â",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:"â¬"},mK=["cent","copy","divide","gt","lt","not","para","times"],XI={}.hasOwnProperty,By={};let kf;for(kf in $b)XI.call($b,kf)&&(By[$b[kf]]=kf);const gK=/[^\dA-Za-z]/;function bK(t,e,r,n){const s=String.fromCharCode(t);if(XI.call(By,s)){const i=By[s],a="&"+i;return r&&pK.includes(i)&&!mK.includes(i)&&(!n||e&&e!==61&&gK.test(String.fromCharCode(e)))?a:a+";"}return""}function vK(t,e,r){let n=dK(t,e,r.omitOptionalSemicolons),s;if((r.useNamedReferences||r.useShortestReferences)&&(s=bK(t,e,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!s)&&r.useShortestReferences){const i=fK(t,e,r.omitOptionalSemicolons);i.length<n.length&&(n=i)}return s&&(!r.useShortestReferences||s.length<n.length)?s:n}function Zc(t,e){return aK(t,Object.assign({format:vK},e))}const yK=/^>|^->|<!--|-->|--!>|<!-$/g,_K=[">"],xK=["<",">"];function wK(t,e,r,n){return n.settings.bogusComments?"<?"+Zc(t.value,Object.assign({},n.settings.characterReferences,{subset:_K}))+">":"<!--"+t.value.replace(yK,s)+"-->";function s(i){return Zc(i,Object.assign({},n.settings.characterReferences,{subset:xK}))}}function SK(t,e,r,n){return"<!"+(n.settings.upperDoctype?"DOCTYPE":"doctype")+(n.settings.tightDoctype?"":" ")+"html>"}const ss=QI(1),JI=QI(-1),CK=[];function QI(t){return e;function e(r,n,s){const i=r?r.children:CK;let a=(n||0)+t,o=i[a];if(!s)for(;o&&d_(o);)a+=t,o=i[a];return o}}const AK={}.hasOwnProperty;function ZI(t){return e;function e(r,n,s){return AK.call(t,r.tagName)&&t[r.tagName](r,n,s)}}const g0=ZI({body:kK,caption:Bb,colgroup:Bb,dd:IK,dt:RK,head:Bb,html:EK,li:TK,optgroup:NK,option:LK,p:PK,rp:tA,rt:tA,tbody:MK,td:rA,tfoot:OK,th:rA,thead:DK,tr:jK});function Bb(t,e,r){const n=ss(r,e,!0);return!n||n.type!=="comment"&&!(n.type==="text"&&d_(n.value.charAt(0)))}function EK(t,e,r){const n=ss(r,e);return!n||n.type!=="comment"}function kK(t,e,r){const n=ss(r,e);return!n||n.type!=="comment"}function PK(t,e,r){const n=ss(r,e);return n?n.type==="element"&&(n.tagName==="address"||n.tagName==="article"||n.tagName==="aside"||n.tagName==="blockquote"||n.tagName==="details"||n.tagName==="div"||n.tagName==="dl"||n.tagName==="fieldset"||n.tagName==="figcaption"||n.tagName==="figure"||n.tagName==="footer"||n.tagName==="form"||n.tagName==="h1"||n.tagName==="h2"||n.tagName==="h3"||n.tagName==="h4"||n.tagName==="h5"||n.tagName==="h6"||n.tagName==="header"||n.tagName==="hgroup"||n.tagName==="hr"||n.tagName==="main"||n.tagName==="menu"||n.tagName==="nav"||n.tagName==="ol"||n.tagName==="p"||n.tagName==="pre"||n.tagName==="section"||n.tagName==="table"||n.tagName==="ul"):!r||!(r.type==="element"&&(r.tagName==="a"||r.tagName==="audio"||r.tagName==="del"||r.tagName==="ins"||r.tagName==="map"||r.tagName==="noscript"||r.tagName==="video"))}function TK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&n.tagName==="li"}function RK(t,e,r){const n=ss(r,e);return!!(n&&n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd"))}function IK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd")}function tA(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&(n.tagName==="rp"||n.tagName==="rt")}function NK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&n.tagName==="optgroup"}function LK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&(n.tagName==="option"||n.tagName==="optgroup")}function DK(t,e,r){const n=ss(r,e);return!!(n&&n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot"))}function MK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot")}function OK(t,e,r){return!ss(r,e)}function jK(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&n.tagName==="tr"}function rA(t,e,r){const n=ss(r,e);return!n||n.type==="element"&&(n.tagName==="td"||n.tagName==="th")}const $K=ZI({body:WK,colgroup:HK,head:FK,html:BK,tbody:UK});function BK(t){const e=ss(t,-1);return!e||e.type!=="comment"}function FK(t){const e=new Set;for(const n of t.children)if(n.type==="element"&&(n.tagName==="base"||n.tagName==="title")){if(e.has(n.tagName))return!1;e.add(n.tagName)}const r=t.children[0];return!r||r.type==="element"}function WK(t){const e=ss(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&d_(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function HK(t,e,r){const n=JI(r,e),s=ss(t,-1,!0);return r&&n&&n.type==="element"&&n.tagName==="colgroup"&&g0(n,r.children.indexOf(n),r)?!1:!!(s&&s.type==="element"&&s.tagName==="col")}function UK(t,e,r){const n=JI(r,e),s=ss(t,-1);return r&&n&&n.type==="element"&&(n.tagName==="thead"||n.tagName==="tbody")&&g0(n,r.children.indexOf(n),r)?!1:!!(s&&s.type==="element"&&s.tagName==="tr")}const Pf={name:[[` 527\f\r &/=>`.split(""),` 528\f\r "&'/=>\``.split("")],[`\0 529\f\r "&'/<=>`.split(""),`\0 530\f\r "&'/<=>\``.split("")]],unquoted:[[` 531\f\r &>`.split(""),`\0 532\f\r "&'<=>\``.split("")],[`\0 533\f\r "&'<=>\``.split(""),`\0 534\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function zK(t,e,r,n){const s=n.schema,i=s.space==="svg"?!1:n.settings.omitOptionalTags;let a=s.space==="svg"?n.settings.closeEmptyElements:n.settings.voids.includes(t.tagName.toLowerCase());const o=[];let l;s.space==="html"&&t.tagName==="svg"&&(n.schema=oE);const c=VK(n,t.properties),u=n.all(s.space==="html"&&t.tagName==="template"?t.content:t);return n.schema=s,u&&(a=!1),(c||!i||!$K(t,e,r))&&(o.push("<",t.tagName,c?" "+c:""),a&&(s.space==="svg"||n.settings.closeSelfClosing)&&(l=c.charAt(c.length-1),(!n.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&o.push(" "),o.push("/")),o.push(">")),o.push(u),!a&&(!i||!g0(t,e,r))&&o.push("</"+t.tagName+">"),o.join("")}function VK(t,e){const r=[];let n=-1,s;if(e){for(s in e)if(e[s]!==null&&e[s]!==void 0){const i=GK(t,s,e[s]);i&&r.push(i)}}for(;++n<r.length;){const i=t.settings.tightAttributes?r[n].charAt(r[n].length-1):void 0;n!==r.length-1&&i!=='"'&&i!=="'"&&(r[n]+=" ")}return r.join("")}function GK(t,e,r){const n=u2(t.schema,e),s=t.settings.allowParseErrors&&t.schema.space==="html"?0:1,i=t.settings.allowDangerousCharacters?0:1;let a=t.quote,o;if(n.overloadedBoolean&&(r===n.attribute||r==="")?r=!0:(n.boolean||n.overloadedBoolean)&&(typeof r!="string"||r===n.attribute||r==="")&&(r=!!r),r==null||r===!1||typeof r=="number"&&Number.isNaN(r))return"";const l=Zc(n.attribute,Object.assign({},t.settings.characterReferences,{subset:Pf.name[s][i]}));return r===!0||(r=Array.isArray(r)?(n.commaSeparated?d2:h2)(r,{padLeft:!t.settings.tightCommaSeparatedLists}):String(r),t.settings.collapseEmptyAttributes&&!r)?l:(t.settings.preferUnquoted&&(o=Zc(r,Object.assign({},t.settings.characterReferences,{attribute:!0,subset:Pf.unquoted[s][i]}))),o!==r&&(t.settings.quoteSmart&&lx(r,a)>lx(r,t.alternative)&&(a=t.alternative),o=a+Zc(r,Object.assign({},t.settings.characterReferences,{subset:(a==="'"?Pf.single:Pf.double)[s][i],attribute:!0}))+a),l+(o&&"="+o))}const qK=["<","&"];function eN(t,e,r,n){return r&&r.type==="element"&&(r.tagName==="script"||r.tagName==="style")?t.value:Zc(t.value,Object.assign({},n.settings.characterReferences,{subset:qK}))}function KK(t,e,r,n){return n.settings.allowDangerousHtml?t.value:eN(t,e,r,n)}function YK(t,e,r,n){return n.all(t)}const XK=VD("type",{invalid:JK,unknown:QK,handlers:{comment:wK,doctype:SK,element:zK,raw:KK,root:YK,text:eN}});function JK(t){throw new Error("Expected node, not `"+t+"`")}function QK(t){const e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}const ZK={},eY={},tY=[];function rY(t,e){const r=ZK,n=r.quote||'"',s=n==='"'?"'":'"';if(n!=='"'&&n!=="'")throw new Error("Invalid quote `"+n+"`, expected `'` or `\"`");return{one:nY,all:sY,settings:{omitOptionalTags:r.omitOptionalTags||!1,allowParseErrors:r.allowParseErrors||!1,allowDangerousCharacters:r.allowDangerousCharacters||!1,quoteSmart:r.quoteSmart||!1,preferUnquoted:r.preferUnquoted||!1,tightAttributes:r.tightAttributes||!1,upperDoctype:r.upperDoctype||!1,tightDoctype:r.tightDoctype||!1,bogusComments:r.bogusComments||!1,tightCommaSeparatedLists:r.tightCommaSeparatedLists||!1,tightSelfClosing:r.tightSelfClosing||!1,collapseEmptyAttributes:r.collapseEmptyAttributes||!1,allowDangerousHtml:r.allowDangerousHtml||!1,voids:r.voids||GD,characterReferences:r.characterReferences||eY,closeSelfClosing:r.closeSelfClosing||!1,closeEmptyElements:r.closeEmptyElements||!1},schema:r.space==="svg"?oE:f2,quote:n,alternative:s}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function nY(t,e,r){return XK(t,e,r,this)}function sY(t){const e=[],r=t&&t.children||tY;let n=-1;for(;++n<r.length;)e[n]=this.one(r[n],n,t);return e.join("")}function iY(t){return Array.isArray(t)?t:[t]}function jm(t,e=!1){const r=t.split(/(\r?\n)/g);let n=0;const s=[];for(let i=0;i<r.length;i+=2){const a=e?r[i]+(r[i+1]||""):r[i];s.push([a,n]),n+=r[i].length,n+=r[i+1]?.length||0}return s}function b0(t){return!t||["plaintext","txt","text","plain"].includes(t)}function v0(t){return t==="ansi"||b0(t)}function y0(t){return t==="none"}function tN(t){return y0(t)}function rN(t,e){if(!e)return t;t.properties||={},t.properties.class||=[],typeof t.properties.class=="string"&&(t.properties.class=t.properties.class.split(/\s+/g)),Array.isArray(t.properties.class)||(t.properties.class=[]);const r=Array.isArray(e)?e:e.split(/\s+/g);for(const n of r)n&&!t.properties.class.includes(n)&&t.properties.class.push(n);return t}function oY(t,e){let r=0;const n=[];for(const s of e)s>r&&n.push({...t,content:t.content.slice(r,s),offset:t.offset+r}),r=s;return r<t.content.length&&n.push({...t,content:t.content.slice(r),offset:t.offset+r}),n}function aY(t,e){const r=Array.from(e instanceof Set?e:new Set(e)).sort((n,s)=>n-s);return r.length?t.map(n=>n.flatMap(s=>{const i=r.filter(a=>s.offset<a&&a<s.offset+s.content.length).map(a=>a-s.offset).sort((a,o)=>a-o);return i.length?oY(s,i):s})):t}async function nN(t){return Promise.resolve(typeof t=="function"?t():t).then(e=>e.default||e)}function Xp(t,e){const r=typeof t=="string"?{}:{...t.colorReplacements},n=typeof t=="string"?t:t.name;for(const[s,i]of Object.entries(e?.colorReplacements||{}))typeof i=="string"?r[s]=i:s===n&&Object.assign(r,i);return r}function ql(t,e){return t&&(e?.[t?.toLowerCase()]||t)}function sN(t){const e={};return t.color&&(e.color=t.color),t.bgColor&&(e["background-color"]=t.bgColor),t.fontStyle&&(t.fontStyle&ua.Italic&&(e["font-style"]="italic"),t.fontStyle&ua.Bold&&(e["font-weight"]="bold"),t.fontStyle&ua.Underline&&(e["text-decoration"]="underline")),e}function lY(t){return typeof t=="string"?t:Object.entries(t).map(([e,r])=>`${e}:${r}`).join(";")}function cY(t){const e=jm(t,!0).map(([s])=>s);function r(s){if(s===t.length)return{line:e.length-1,character:e[e.length-1].length};let i=s,a=0;for(const o of e){if(i<o.length)break;i-=o.length,a++}return{line:a,character:i}}function n(s,i){let a=0;for(let o=0;o<s;o++)a+=e[o].length;return a+=i,a}return{lines:e,indexToPos:r,posToIndex:n}}
534class ii extends Error{constructor(e){super(e),this.name="ShikiError"}}const iN=new WeakMap;function $m(t,e){iN.set(t,e)}function Xd(t){return iN.get(t)}class wu{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(e,r){return new wu(Object.fromEntries(iY(r).map(n=>[n,$y])),e)}constructor(...e){if(e.length===2){const[r,n]=e;this.lang=n,this._stacks=r}else{const[r,n,s]=e;this.lang=n,this._stacks={[s]:r}}}getInternalStack(e=this.theme){return this._stacks[e]}get scopes(){return nA(this._stacks[this.theme])}getScopes(e=this.theme){return nA(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.scopes}}}function nA(t){const e=[],r=new Set;function n(s){if(r.has(s))return;r.add(s);const i=s?.nameScopesList?.scopeName;i&&e.push(i),s.parent&&n(s.parent)}return n(t),e}function uY(t,e){if(!(t instanceof wu))throw new ii("Invalid grammar state");return t.getInternalStack(e)}function dY(){const t=new WeakMap;function e(r){if(!t.has(r.meta)){let n=function(a){if(typeof a=="number"){if(a<0||a>r.source.length)throw new ii(`Invalid decoration offset: ${a}. Code length: ${r.source.length}`);return{...s.indexToPos(a),offset:a}}else{const o=s.lines[a.line];if(o===void 0)throw new ii(`Invalid decoration position ${JSON.stringify(a)}. Lines length: ${s.lines.length}`);if(a.character<0||a.character>o.length)throw new ii(`Invalid decoration position ${JSON.stringify(a)}. Line ${a.line} length: ${o.length}`);return{...a,offset:s.posToIndex(a.line,a.character)}}};const s=cY(r.source),i=(r.options.decorations||[]).map(a=>({...a,start:n(a.start),end:n(a.end)}));hY(i),t.set(r.meta,{decorations:i,converter:s,source:r.source})}return t.get(r.meta)}return{name:"shiki:decorations",tokens(r){if(!this.options.decorations?.length)return;const s=e(this).decorations.flatMap(a=>[a.start.offset,a.end.offset]);return aY(r,s)},code(r){if(!this.options.decorations?.length)return;const n=e(this),s=Array.from(r.children).filter(u=>u.type==="element"&&u.tagName==="span");if(s.length!==n.converter.lines.length)throw new ii(`Number of lines in code element (${s.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(u,d,h,m){const b=s[u];let g="",p=-1,y=-1;if(d===0&&(p=0),h===0&&(y=0),h===Number.POSITIVE_INFINITY&&(y=b.children.length),p===-1||y===-1)for(let _=0;_<b.children.length;_++)g+=oN(b.children[_]),p===-1&&g.length===d&&(p=_+1),y===-1&&g.length===h&&(y=_+1);if(p===-1)throw new ii(`Failed to find start index for decoration ${JSON.stringify(m.start)}`);if(y===-1)throw new ii(`Failed to find end index for decoration ${JSON.stringify(m.end)}`);const v=b.children.slice(p,y);if(!m.alwaysWrap&&v.length===b.children.length)o(b,m,"line");else if(!m.alwaysWrap&&v.length===1&&v[0].type==="element")o(v[0],m,"token");else{const _={type:"element",tagName:"span",properties:{},children:v};o(_,m,"wrapper"),b.children.splice(p,v.length,_)}}function a(u,d){s[u]=o(s[u],d,"line")}function o(u,d,h){const m=d.properties||{},b=d.transform||(g=>g);return u.tagName=d.tagName||"span",u.properties={...u.properties,...m,class:u.properties.class},d.properties?.class&&rN(u,d.properties.class),u=b(u,h)||u,u}const l=[],c=n.decorations.sort((u,d)=>d.start.offset-u.start.offset);for(const u of c){const{start:d,end:h}=u;if(d.line===h.line)i(d.line,d.character,h.character,u);else if(d.line<h.line){i(d.line,d.character,Number.POSITIVE_INFINITY,u);for(let m=d.line+1;m<h.line;m++)l.unshift(()=>a(m,u));i(h.line,0,h.character,u)}}l.forEach(u=>u())}}}function hY(t){for(let e=0;e<t.length;e++){const r=t[e];if(r.start.offset>r.end.offset)throw new ii(`Invalid decoration range: ${JSON.stringify(r.start)} - ${JSON.stringify(r.end)}`);for(let n=e+1;n<t.length;n++){const s=t[n],i=r.start.offset<s.start.offset&&s.start.offset<r.end.offset,a=r.start.offset<s.end.offset&&s.end.offset<r.end.offset,o=s.start.offset<r.start.offset&&r.start.offset<s.end.offset,l=s.start.offset<r.end.offset&&r.end.offset<s.end.offset;if(i||a||o||l){if(a&&a||o&&l)continue;throw new ii(`Decorations ${JSON.stringify(r.start)} and ${JSON.stringify(s.start)} intersect.`)}}}}function oN(t){return t.type==="text"?t.value:t.type==="element"?t.children.map(oN).join(""):""}const fY=[dY()];function Jp(t){return[...t.transformers||[],...fY]}var Kl=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],Fb={1:"bold",2:"dim",3:"italic",4:"underline",7:"reverse",9:"strikethrough"};function pY(t,e){const r=t.indexOf("\x1B[",e);if(r!==-1){const n=t.indexOf("m",r);return{sequence:t.substring(r+2,n).split(";"),startPosition:r,position:n+1}}return{position:t.length}}function sA(t,e){let r=1;const n=t[e+r++];let s;if(n==="2"){const i=[t[e+r++],t[e+r++],t[e+r]].map(a=>Number.parseInt(a));i.length===3&&!i.some(a=>Number.isNaN(a))&&(s={type:"rgb",rgb:i})}else if(n==="5"){const i=Number.parseInt(t[e+r]);Number.isNaN(i)||(s={type:"table",index:Number(i)})}return[r,s]}function mY(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r],s=Number.parseInt(n);
vendor: 15,416 bytes, lines 534-535
534if(!Number.isNaN(s))if(s===0)e.push({type:"resetAll"});else if(s<=9)Fb[s]&&e.push({type:"setDecoration",value:Fb[s]});else if(s<=29){const i=Fb[s-20];i&&e.push({type:"resetDecoration",value:i})}else if(s<=37)e.push({type:"setForegroundColor",value:{type:"named",name:Kl[s-30]}});else if(s===38){const[i,a]=sA(t,r);a&&e.push({type:"setForegroundColor",value:a}),r+=i}else if(s===39)e.push({type:"resetForegroundColor"});else if(s<=47)e.push({type:"setBackgroundColor",value:{type:"named",name:Kl[s-40]}});else if(s===48){const[i,a]=sA(t,r);a&&e.push({type:"setBackgroundColor",value:a}),r+=i}else s===49?e.push({type:"resetBackgroundColor"}):s>=90&&s<=97?e.push({type:"setForegroundColor",value:{type:"named",name:Kl[s-90+8]}}):s>=100&&s<=107&&e.push({type:"setBackgroundColor",value:{type:"named",name:Kl[s-100+8]}})}return e}function gY(){let t=null,e=null,r=new Set;return{parse(n){const s=[];let i=0;do{const a=pY(n,i),o=a.sequence?n.substring(i,a.startPosition):n.substring(i);if(o.length>0&&s.push({value:o,foreground:t,background:e,decorations:new Set(r)}),a.sequence){const l=mY(a.sequence);for(const c of l)c.type==="resetAll"?(t=null,e=null,r.clear()):c.type==="resetForegroundColor"?t=null:c.type==="resetBackgroundColor"?e=null:c.type==="resetDecoration"&&r.delete(c.value);for(const c of l)c.type==="setForegroundColor"?t=c.value:c.type==="setBackgroundColor"?e=c.value:c.type==="setDecoration"&&r.add(c.value)}i=a.position}while(i<n.length);return s}}}var bY={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 vY(t=bY){function e(o){return t[o]}function r(o){return`#${o.map(l=>Math.max(0,Math.min(l,255)).toString(16).padStart(2,"0")).join("")}`}let n;function s(){if(n)return n;n=[];for(let c=0;c<Kl.length;c++)n.push(e(Kl[c]));let o=[0,95,135,175,215,255];for(let c=0;c<6;c++)for(let u=0;u<6;u++)for(let d=0;d<6;d++)n.push(r([o[c],o[u],o[d]]));let l=8;for(let c=0;c<24;c++,l+=10)n.push(r([l,l,l]));return n}function i(o){return s()[o]}function a(o){switch(o.type){case"named":return e(o.name);case"rgb":return r(o.rgb);case"table":return i(o.index)}}return{value:a}}function yY(t,e,r){const n=Xp(t,r),s=jm(e),i=vY(Object.fromEntries(Kl.map(o=>[o,t.colors?.[`terminal.ansi${o[0].toUpperCase()}${o.substring(1)}`]]))),a=gY();return s.map(o=>a.parse(o[0]).map(l=>{let c,u;l.decorations.has("reverse")?(c=l.background?i.value(l.background):t.bg,u=l.foreground?i.value(l.foreground):t.fg):(c=l.foreground?i.value(l.foreground):t.fg,u=l.background?i.value(l.background):void 0),c=ql(c,n),u=ql(u,n),l.decorations.has("dim")&&(c=_Y(c));let d=ua.None;return l.decorations.has("bold")&&(d|=ua.Bold),l.decorations.has("italic")&&(d|=ua.Italic),l.decorations.has("underline")&&(d|=ua.Underline),{content:l.value,offset:o[1],color:c,bgColor:u,fontStyle:d}}))}function _Y(t){const e=t.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);if(e)if(e[3]){const n=Math.round(Number.parseInt(e[3],16)/2).toString(16).padStart(2,"0");return`#${e[1]}${e[2]}${n}`}else return e[2]?`#${e[1]}${e[2]}80`:`#${Array.from(e[1]).map(n=>`${n}${n}`).join("")}80`;const r=t.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return r?`var(${r[1]}-dim)`:t}function _0(t,e,r={}){const{lang:n="text",theme:s=t.getLoadedThemes()[0]}=r;if(b0(n)||y0(s))return jm(e).map(l=>[{content:l[0],offset:l[1]}]);const{theme:i,colorMap:a}=t.setTheme(s);if(n==="ansi")return yY(i,e,r);const o=t.getLanguage(n);if(r.grammarState){if(r.grammarState.lang!==o.name)throw new fa(`Grammar state language "${r.grammarState.lang}" does not match highlight language "${o.name}"`);if(!r.grammarState.themes.includes(i.name))throw new fa(`Grammar state themes "${r.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return wY(e,o,i,a,r)}function xY(...t){if(t.length===2)return Xd(t[1]);const[e,r,n={}]=t,{lang:s="text",theme:i=e.getLoadedThemes()[0]}=n;if(b0(s)||y0(i))throw new fa("Plain language does not have grammar state");if(s==="ansi")throw new fa("ANSI language does not have grammar state");const{theme:a,colorMap:o}=e.setTheme(i),l=e.getLanguage(s);return new wu(Qp(r,l,a,o,n).stateStack,l.name,a.name)}function wY(t,e,r,n,s){const i=Qp(t,e,r,n,s),a=new wu(Qp(t,e,r,n,s).stateStack,e.name,r.name);return $m(i.tokens,a),i.tokens}function Qp(t,e,r,n,s){const i=Xp(r,s),{tokenizeMaxLineLength:a=0,tokenizeTimeLimit:o=500}=s,l=jm(t);let c=s.grammarState?uY(s.grammarState,r.name)??$y:s.grammarContextCode!=null?Qp(s.grammarContextCode,e,r,n,{...s,grammarState:void 0,grammarContextCode:void 0}).stateStack:$y,u=[];const d=[];for(let h=0,m=l.length;h<m;h++){const[b,g]=l[h];if(b===""){u=[],d.push([]);continue}if(a>0&&b.length>=a){u=[],d.push([{content:b,offset:g,color:"",fontStyle:0}]);continue}let p,y,v;s.includeExplanation&&(p=e.tokenizeLine(b,c),y=p.tokens,v=0);const _=e.tokenizeLine2(b,c,o),w=_.tokens.length/2;for(let C=0;C<w;C++){const A=_.tokens[2*C],E=C+1<w?_.tokens[2*C+2]:b.length;if(A===E)continue;const S=_.tokens[2*C+1],k=ql(n[uu.getForeground(S)],i),O=uu.getFontStyle(S),T={content:b.substring(A,E),offset:g+A,color:k,fontStyle:O};if(s.includeExplanation){const R=[];if(s.includeExplanation!=="scopeName")for(const M of r.settings){let B;switch(typeof M.scope){case"string":B=M.scope.split(/,/).map(U=>U.trim());break;case"object":B=M.scope;break;default:continue}R.push({settings:M,selectors:B.map(U=>U.split(/ /))})}T.explanation=[];let N=0;for(;A+N<E;){const M=y[v],B=b.substring(M.startIndex,M.endIndex);N+=B.length,T.explanation.push({content:B,scopes:s.includeExplanation==="scopeName"?SY(M.scopes):CY(R,M.scopes)}),v+=1}}u.push(T)}d.push(u),u=[],c=_.ruleStack}return{tokens:d,stateStack:c}}function SY(t){return t.map(e=>({scopeName:e}))}function CY(t,e){const r=[];for(let n=0,s=e.length;n<s;n++){const i=e[n];r[n]={scopeName:i,themeMatches:EY(t,i,e.slice(0,n))}}return r}function iA(t,e){return t===e||e.substring(0,t.length)===t&&e[t.length]==="."}function AY(t,e,r){if(!iA(t[t.length-1],e))return!1;let n=t.length-2,s=r.length-1;for(;n>=0&&s>=0;)iA(t[n],r[s])&&(n-=1),s-=1;return n===-1}function EY(t,e,r){const n=[];for(const{selectors:s,settings:i}of t)for(const a of s)if(AY(a,e,r)){n.push(i);break}return n}function aN(t,e,r){const n=Object.entries(r.themes).filter(l=>l[1]).map(l=>({color:l[0],theme:l[1]})),s=n.map(l=>{const c=_0(t,e,{...r,theme:l.theme}),u=Xd(c),d=typeof l.theme=="string"?l.theme:l.theme.name;return{tokens:c,state:u,theme:d}}),i=kY(...s.map(l=>l.tokens)),a=i[0].map((l,c)=>l.map((u,d)=>{const h={content:u.content,variants:{},offset:u.offset};return"includeExplanation"in r&&r.includeExplanation&&(h.explanation=u.explanation),i.forEach((m,b)=>{const{content:g,explanation:p,offset:y,...v}=m[c][d];h.variants[n[b].color]=v}),h})),o=s[0].state?new wu(Object.fromEntries(s.map(l=>[l.theme,l.state?.getInternalStack(l.theme)])),s[0].state.lang):void 0;return o&&$m(a,o),a}function kY(...t){const e=t.map(()=>[]),r=t.length;for(let n=0;n<t[0].length;n++){const s=t.map(l=>l[n]),i=e.map(()=>[]);e.forEach((l,c)=>l.push(i[c]));const a=s.map(()=>0),o=s.map(l=>l[0]);for(;o.every(l=>l);){const l=Math.min(...o.map(c=>c.content.length));for(let c=0;c<r;c++){const u=o[c];u.content.length===l?(i[c].push(u),a[c]+=1,o[c]=s[c][a[c]]):(i[c].push({...u,content:u.content.slice(0,l)}),o[c]={...u,content:u.content.slice(l),offset:u.offset+l})}}}return e}function Zp(t,e,r){let n,s,i,a,o,l;if("themes"in r){const{defaultColor:c="light",cssVariablePrefix:u="--shiki-"}=r,d=Object.entries(r.themes).filter(p=>p[1]).map(p=>({color:p[0],theme:p[1]})).sort((p,y)=>p.color===c?-1:y.color===c?1:0);if(d.length===0)throw new fa("`themes` option must not be empty");const h=aN(t,e,r);if(l=Xd(h),c&&!d.find(p=>p.color===c))throw new fa(`\`themes\` option must contain the defaultColor key \`${c}\``);const m=d.map(p=>t.getTheme(p.theme)),b=d.map(p=>p.color);i=h.map(p=>p.map(y=>PY(y,b,u,c))),l&&$m(i,l);const g=d.map(p=>Xp(p.theme,r));s=d.map((p,y)=>(y===0&&c?"":`${u+p.color}:`)+(ql(m[y].fg,g[y])||"inherit")).join(";"),n=d.map((p,y)=>(y===0&&c?"":`${u+p.color}-bg:`)+(ql(m[y].bg,g[y])||"inherit")).join(";"),a=`shiki-themes ${m.map(p=>p.name).join(" ")}`,o=c?void 0:[s,n].join(";")}else if("theme"in r){const c=Xp(r.theme,r);i=_0(t,e,r);const u=t.getTheme(r.theme);n=ql(u.bg,c),s=ql(u.fg,c),a=u.name,l=Xd(i)}else throw new fa("Invalid options, either `theme` or `themes` must be provided");return{tokens:i,fg:s,bg:n,themeName:a,rootStyle:o,grammarState:l}}function PY(t,e,r,n){const s={content:t.content,explanation:t.explanation,offset:t.offset},i=e.map(l=>sN(t.variants[l])),a=new Set(i.flatMap(l=>Object.keys(l))),o={};return i.forEach((l,c)=>{for(const u of a){const d=l[u]||"inherit";if(c===0&&n)o[u]=d;else{const h=u==="color"?"":u==="background-color"?"-bg":`-${u}`,m=r+e[c]+(u==="color"?"":h);o[m]=d}}}),s.htmlStyle=o,s}function em(t,e,r,n={meta:{},options:r,codeToHast:(s,i)=>em(t,s,i),codeToTokens:(s,i)=>Zp(t,s,i)}){let s=e;for(const m of Jp(r))s=m.preprocess?.call(n,s,r)||s;let{tokens:i,fg:a,bg:o,themeName:l,rootStyle:c,grammarState:u}=Zp(t,s,r);const{mergeWhitespaces:d=!0}=r;d===!0?i=RY(i):d==="never"&&(i=IY(i));const h={...n,get source(){return s}};for(const m of Jp(r))i=m.tokens?.call(h,i)||i;return TY(i,{...r,fg:a,bg:o,themeName:l,rootStyle:c},h,u)}function TY(t,e,r,n=Xd(t)){const s=Jp(e),i=[],a={type:"root",children:[]},{structure:o="classic",tabindex:l="0"}=e;let c={type:"element",tagName:"pre",properties:{class:`shiki ${e.themeName||""}`,style:e.rootStyle||`background-color:${e.bg};color:${e.fg}`,...l!==!1&&l!=null?{tabindex:l.toString()}:{},...Object.fromEntries(Array.from(Object.entries(e.meta||{})).filter(([b])=>!b.startsWith("_")))},children:[]},u={type:"element",tagName:"code",properties:{},children:i};const d=[],h={...r,structure:o,addClassToHast:rN,get source(){return r.source},get tokens(){return t},get options(){return e},get root(){return a},get pre(){return c},get code(){return u},get lines(){return d}};if(t.forEach((b,g)=>{g&&(o==="inline"?a.children.push({type:"element",tagName:"br",properties:{},children:[]}):o==="classic"&&i.push({type:"text",value:` 535`}));let p={type:"element",tagName:"span",properties:{class:"line"},children:[]},y=0;for(const v of b){let _={type:"element",tagName:"span",properties:{...v.htmlAttrs},children:[{type:"text",value:v.content}]};v.htmlStyle;const w=lY(v.htmlStyle||sN(v));w&&(_.properties.style=w);for(const C of s)_=C?.span?.call(h,_,g+1,y,p,v)||_;o==="inline"?a.children.push(_):o==="classic"&&p.children.push(_),y+=v.content.length}if(o==="classic"){for(const v of s)p=v?.line?.call(h,p,g+1)||p;d.push(p),i.push(p)}}),o==="classic"){for(const b of s)u=b?.code?.call(h,u)||u;c.children.push(u);for(const b of s)c=b?.pre?.call(h,c)||c;a.children.push(c)}let m=a;for(const b of s)m=b?.root?.call(h,m)||m;return n&&$m(m,n),m}function RY(t){return t.map(e=>{const r=[];let n="",s=0;return e.forEach((i,a)=>{const l=!(i.fontStyle&&i.fontStyle&ua.Underline);l&&i.content.match(/^\s+$/)&&e[a+1]?(s||(s=i.offset),n+=i.content):n?(l?r.push({...i,offset:s,content:n+i.content}):r.push({content:n,offset:s},i),s=0,n=""):r.push(i)}),r})}function IY(t){return t.map(e=>e.flatMap(r=>{if(r.content.match(/^\s+$/))return r;const n=r.content.match(/^(\s*)(.*?)(\s*)$/);if(!n)return r;const[,s,i,a]=n;if(!s&&!a)return r;const o=[{...r,offset:r.offset+s.length,content:i}];return s&&o.unshift({content:s,offset:r.offset}),a&&o.push({content:a,offset:r.offset+s.length+i.length}),o}))}function NY(t,e,r){const n={meta:{},options:r,codeToHast:(i,a)=>em(t,i,a),codeToTokens:(i,a)=>Zp(t,i,a)};let s=rY(em(t,e,r,n));for(const i of Jp(r))s=i.postprocess?.call(n,s,r)||s;return s}const oA={light:"#333333",dark:"#bbbbbb"},aA={light:"#fffffe",dark:"#1e1e1e"},lA="__shiki_resolved";function x0(t){if(t?.[lA])return t;const e={...t};e.tokenColors&&!e.settings&&(e.settings=e.tokenColors,delete e.tokenColors),e.type||="dark",e.colorReplacements={...e.colorReplacements},e.settings||=[];let{bg:r,fg:n}=e;if(!r||!n){const o=e.settings?e.settings.find(l=>!l.name&&!l.scope):void 0;o?.settings?.foreground&&(n=o.settings.foreground),o?.settings?.background&&(r=o.settings.background),!n&&e?.colors?.["editor.foreground"]&&(n=e.colors["editor.foreground"]),!r&&e?.colors?.["editor.background"]&&(r=e.colors["editor.background"]),n||(n=e.type==="light"?oA.light:oA.dark),r||(r=e.type==="light"?aA.light:aA.dark),e.fg=n,e.bg=r}e.settings[0]&&e.settings[0].settings&&!e.settings[0].scope||e.settings.unshift({settings:{foreground:e.fg,background:e.bg}});let s=0;const i=new Map;function a(o){if(i.has(o))return i.get(o);s+=1;const l=`#${s.toString(16).padStart(8,"0").toLowerCase()}`;return e.colorReplacements?.[`#${l}`]?a(o):(i.set(o,l),l)}e.settings=e.settings.map(o=>{const l=o.settings?.foreground&&!o.settings.foreground.startsWith("#"),c=o.settings?.background&&!o.settings.background.startsWith("#");if(!l&&!c)return o;const u={...o,settings:{...o.settings}};if(l){const d=a(o.settings.foreground);e.colorReplacements[d]=o.settings.foreground,u.settings.foreground=d}if(c){const d=a(o.settings.background);e.colorReplacements[d]=o.settings.background,u.settings.background=d}return u});for(const o of Object.keys(e.colors||{}))if((o==="editor.foreground"||o==="editor.background"||o.startsWith("terminal.ansi"))&&!e.colors[o]?.startsWith("#")){const l=a(e.colors[o]);e.colorReplacements[l]=e.colors[o],e.colors[o]=l}return Object.defineProperty(e,lA,{enumerable:!1,writable:!1,value:!0}),e}async function lN(t){return Array.from(new Set((await Promise.all(t.filter(e=>!v0(e)).map(async e=>await nN(e).then(r=>Array.isArray(r)?r:[r])))).flat()))}async function cN(t){return(await Promise.all(t.map(async r=>tN(r)?null:x0(await nN(r))))).filter(r=>!!r)}class LY extends rK{constructor(e,r,n,s={}){super(e),this._resolver=e,this._themes=r,this._langs=n,this._alias=s,this._themes.map(i=>this.loadTheme(i)),this.loadLanguages(this._langs)}_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;getTheme(e){return typeof e=="string"?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){const r=x0(e);return r.name&&(this._resolvedThemes.set(r.name,r),this._loadedThemesCache=null),r}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(e){let r=this._textmateThemeCache.get(e);r||(r=Vp.createFromRawTheme(e),this._textmateThemeCache.set(e,r)),this._syncRegistry.setTheme(r)}getGrammar(e){if(this._alias[e]){const r=new Set([e]);for(;this._alias[e];){if(e=this._alias[e],r.has(e))throw new ii(`Circular alias \`${Array.from(r).join(" -> ")} -> ${e}\``);r.add(e)}}return this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;const r=new Set([...this._langMap.values()].filter(i=>i.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);const n={balancedBracketSelectors:e.balancedBracketSelectors||["*"],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);const s=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(s.name=e.name,this._resolvedGrammars.set(e.name,s),e.aliases&&e.aliases.forEac
535h(i=>{this._alias[i]=e.name}),this._loadedLanguagesCache=null,r.size)for(const i of r)this._resolvedGrammars.delete(i.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(i.scopeName),this._syncRegistry?._grammars?.delete(i.scopeName),this.loadLanguage(this._langMap.get(i.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(const s of e)this.resolveEmbeddedLanguages(s);const r=Array.from(this._langGraph.entries()),n=r.filter(([s,i])=>!i);if(n.length){const s=r.filter(([i,a])=>a&&a.embeddedLangs?.some(o=>n.map(([l])=>l).includes(o))).filter(i=>!n.includes(i));throw new ii(`Missing languages ${n.map(([i])=>`\`${i}\``).join(", ")}, required by ${s.map(([i])=>`\`${i}\``).join(", ")}`)}for(const[s,i]of r)this._resolver.addLanguage(i);for(const[s,i]of r)this.loadLanguage(i)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(e){if(this._langMap.set(e.name,e),this._langGraph.set(e.name,e),e.embeddedLangs)for(const r of e.embeddedLangs)this._langGraph.set(r,this._langMap.get(r))}}class DY{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,r){this._onigLib={createOnigScanner:n=>e.createScanner(n),createOnigString:n=>e.createString(n)},r.forEach(n=>this.addLanguage(n))}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(r=>{this._langs.set(r,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(r=>{this._injections.get(r)||this._injections.set(r,[]),this._injections.get(r).push(e.scopeName)})}getInjections(e){const r=e.split(".");let n=[];for(let s=1;s<=r.length;s++){const i=r.slice(0,s).join(".");n=[...n,...this._injections.get(i)||[]]}return n}}let Gu=0;function MY(t){Gu+=1,t.warnings!==!1&&Gu>=10&&Gu%10===0&&console.warn(`[Shiki] ${Gu} 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 e=!1;if(!t.engine)throw new ii("`engine` option is required for synchronous mode");const r=(t.langs||[]).flat(1),n=(t.themes||[]).flat(1).map(x0),s=new DY(t.engine,r),i=new LY(s,n,r,t.langAlias);let a;function o(v){p();const _=i.getGrammar(typeof v=="string"?v:v.name);if(!_)throw new ii(`Language \`${v}\` not found, you may need to load it first`);return _}function l(v){if(v==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};p();const _=i.getTheme(v);if(!_)throw new ii(`Theme \`${v}\` not found, you may need to load it first`);return _}function c(v){p();const _=l(v);a!==v&&(i.setTheme(_),a=v);const w=i.getColorMap();return{theme:_,colorMap:w}}function u(){return p(),i.getLoadedThemes()}function d(){return p(),i.getLoadedLanguages()}function h(...v){p(),i.loadLanguages(v.flat(1))}async function m(...v){return h(await lN(v))}function b(...v){p();for(const _ of v.flat(1))i.loadTheme(_)}async function g(...v){return p(),b(await cN(v))}function p(){if(e)throw new ii("Shiki instance has been disposed")}function y(){e||(e=!0,i.dispose(),Gu-=1)}return{setTheme:c,getTheme:l,getLanguage:o,getLoadedThemes:u,getLoadedLanguages:d,loadLanguage:m,loadLanguageSync:h,loadTheme:g,loadThemeSync:b,dispose:y,[Symbol.dispose]:y}}async function OY(t={}){t.loadWasm;const[e,r,n]=await Promise.all([cN(t.themes||[]),lN(t.langs||[]),t.engine||DI(t.loadWasm||g9())]);return MY({...t,themes:e,langs:r,engine:n})}async function jY(t={}){const e=await OY(t);return{getLastGrammarState:(...r)=>xY(e,...r),codeToTokensBase:(r,n)=>_0(e,r,n),codeToTokensWithThemes:(r,n)=>aN(e,r,n),codeToTokens:(r,n)=>Zp(e,r,n),codeToHast:(r,n)=>em(e,r,n),codeToHtml:(r,n)=>NY(e,r,n),...e,getInternalContext:()=>e}}function $Y(t,e,r){let n,s,i;{const o=t;n=o.langs,s=o.themes,i=o.engine}async function a(o){function l(m){if(typeof m=="string"){if(v0(m))return[];const b=n[m];if(!b)throw new fa(`Language \`${m}\` is not included in this bundle. You may want to load it from external source.`);return b}return m}function c(m){if(tN(m))return"none";if(typeof m=="string"){const b=s[m];if(!b)throw new fa(`Theme \`${m}\` is not included in this bundle. You may want to load it from external source.`);return b}return m}const u=(o.themes??[]).map(m=>c(m)),d=(o.langs??[]).map(m=>l(m)),h=await jY({engine:o.engine??i(),...o,themes:u,langs:d});return{...h,loadLanguage(...m){return h.loadLanguage(...m.map(l))},loadTheme(...m){return h.loadTheme(...m.map(c))}}}return a}function BY(t){let e;async function r(n={}){if(e){const s=await e;return await Promise.all([s.loadTheme(...n.themes||[]),s.loadLanguage(...n.langs||[])]),s}else return e=t({...n,themes:n.themes||[],langs:n.langs||[]}),e}return r}function FY(t){const e=BY(t);return{getSingletonHighlighter(r){return e(r)},async codeToHtml(r,n){return(await e({langs:[n.lang],themes:"theme"in n?[n.theme]:Object.values(n.themes)})).codeToHtml(r,n)},async codeToHast(r,n){return(await e({langs:[n.lang],themes:"theme"in n?[n.theme]:Object.values(n.themes)})).codeToHast(r,n)},async codeToTokens(r,n){return(await e({langs:[n.lang],themes:"theme"in n?[n.theme]:Object.values(n.themes)})).codeToTokens(r,n)},async codeToTokensBase(r,n){return(await e({langs:[n.lang],themes:[n.theme]})).codeToTokensBase(r,n)},async codeToTokensWithThemes(r,n){return(await e({langs:[n.lang],themes:Object.values(n.themes).filter(
535Boolean)})).codeToTokensWithThemes(r,n)},async getLastGrammarState(r,n){return(await e({langs:[n.lang],themes:[n.theme]})).getLastGrammarState(r,n)}}}const Bm=$Y({langs:LI,themes:Q7,engine:()=>DI(H(()=>import("./wasm-CG6Dc4jp.js"),[]))}),{codeToHtml:WY}=FY(Bm),$oe=t=>Bm(t),HY={langs:["shell"],themes:["light-plus","dark-plus"]},UY=await Bm(HY),zY=oh({}),VY=x.memo(({messageId:t})=>{const e=x.useRef(!1),[r,n]=x.useState(!1),[s,i]=x.useState(!1),a=We(j.artifacts),o=We(j.previews),l=We(j.generatedProjectKind),c=We(j.activeProgressMessageId),u=a[t],d=c?a[c]:void 0,h=o.length>0,m=h$(l),b=f$(l),g=We(Zl(u?.runner.actions??zY,_=>Object.values(_))),p=()=>{e.current=!0,n(!r)};if(x.useEffect(()=>{if(u&&(g.length&&!r&&!e.current&&n(!0),u.type==="bundled")){const _=g.some(C=>C.status==="pending"||C.status==="running"&&C.type!=="start"),w=h||(u.closed||g.length>0)&&!_;s!==w&&i(w)}},[g,u,s,h,r]),!u||u.type==="bundled"&&!!d&&d.type==="bundled"&&c!==t)return null;const v=u?.type==="bundled"?s?u.id==="restored-project-setup"?`${b} Restored`:`${b} Ready`:u.id==="restored-project-setup"?`Restoring ${b}...`:`Creating ${b}...`:u?.title;return f.jsx(f.Fragment,{children:f.jsxs("div",{className:"artifact border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150",children:[f.jsxs("div",{className:"flex",children:[f.jsx("button",{className:"flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden",onClick:()=>{const _=j.showWorkbench.get();j.showWorkbench.set(!_)},children:f.jsxs("div",{className:"px-5 p-3.5 w-full text-left",children:[f.jsx("div",{className:"w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm",children:v}),f.jsx("div",{className:"w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5",children:"Click to open Workbench"})]})}),u.type!=="bundled"&&f.jsx("div",{className:"bg-bolt-elements-artifacts-borderColor w-[1px]"}),f.jsx(Si,{children:g.length&&u.type!=="bundled"&&f.jsx(ar.button,{initial:{width:0},animate:{width:"auto"},exit:{width:0},transition:{duration:.15,ease:Ds},className:"bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover",onClick:p,children:f.jsx("div",{className:"p-4",children:f.jsx("div",{className:r?"i-ph:caret-up-bold":"i-ph:caret-down-bold"})})})})]}),u.type==="bundled"&&f.jsxs("div",{className:"flex items-center gap-1.5 p-5 bg-bolt-elements-actions-background border-t border-bolt-elements-artifacts-borderColor",children:[f.jsx("div",{className:ue("text-lg",dN(s?"complete":"running")),children:s?f.jsx("div",{className:"i-ph:check"}):f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg"})}),f.jsx("div",{className:"text-bolt-elements-textPrimary font-medium leading-5 text-sm",children:s?u.id==="restored-project-setup"?`${b} restored`:`${b} draft ready`:`Preparing your ${m}`})]}),f.jsx(Si,{children:u.type!=="bundled"&&r&&g.length>0&&f.jsxs(ar.div,{className:"actions",initial:{height:0},animate:{height:"auto"},exit:{height:"0px"},transition:{duration:.15},children:[f.jsx("div",{className:"bg-bolt-elements-artifacts-borderColor h-[1px]"}),f.jsx("div",{className:"p-5 text-left bg-bolt-elements-actions-background",children:f.jsx(KY,{actions:g})})]})})]})})});function GY({classsName:t,code:e}){return f.jsx("div",{className:ue("text-xs",t),dangerouslySetInnerHTML:{__html:UY.codeToHtml(e,{lang:"shell",theme:"dark-plus"})}})}const qY={hidden:{opacity:0,y:20},visible:{opacity:1,y:0}};function uN(t){j.currentView.get()!=="code"&&j.currentView.set("code"),j.setSelectedFile(`${Za}/${t}`)}const KY=x.memo(({actions:t})=>f.jsx(ar.div,{initial:{opacity:0}
535,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:f.jsx("ul",{className:"list-none space-y-2.5",children:t.map((e,r)=>{const{status:n,type:s,content:i}=e,a=r===t.length-1;return f.jsxs(ar.li,{variants:qY,initial:"hidden",animate:"visible",transition:{duration:.2,ease:Ds},children:[f.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[f.jsx("div",{className:ue("text-lg",dN(e.status)),children:n==="running"?f.jsx(f.Fragment,{children:s!=="start"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg"}):f.jsx("div",{className:"i-ph:terminal-window-duotone"})}):n==="pending"?f.jsx("div",{className:"i-ph:circle-duotone"}):n==="complete"?f.jsx("div",{className:"i-ph:check"}):n==="failed"||n==="aborted"?f.jsx("div",{className:"i-ph:x"}):null}),s==="file"?f.jsxs("div",{children:["Create"," ",f.jsx("code",{className:"bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md text-bolt-elements-item-contentAccent hover:underline cursor-pointer",onClick:()=>uN(e.filePath),children:e.filePath})]}):s==="shell"?f.jsx("div",{className:"flex items-center w-full min-h-[28px]",children:f.jsx("span",{className:"flex-1",children:"Run command"})}):s==="start"?f.jsx("a",{onClick:o=>{o.preventDefault(),j.currentView.set("preview")},className:"flex items-center w-full min-h-[28px]",children:f.jsx("span",{className:"flex-1",children:"Start Application"})}):null]}),(s==="shell"||s==="start")&&f.jsx(GY,{classsName:ue("mt-1",{"mb-3.5":!a}),code:i})]},r)})})}));function dN(t){switch(t){case"pending":return"text-bolt-elements-textTertiary";case"running":return"text-bolt-elements-loader-progress";case"complete":return"text-bolt-elements-icon-success";case"aborted":return"text-bolt-elements-textSecondary";case"failed":return"text-bolt-elements-icon-error";default:return}}const YY="A",XY={CopyButtonContainer:YY},cA=ya("CodeBlock"),JY=x.memo(({className:t,code:e,language:r="plaintext",theme:n="dark-plus",disableCopy:s=!1})=>{const[i,a]=x.useState(void 0),[o,l]=x.useState(!1),c=()=>{o||(navigator.clipboard.writeText(e),l(!0),setTimeout(()=>{l(!1)},2e3))};return x.useEffect(()=>{let u=r;r&&!v0(r)&&!(r in LI)&&(cA.warn(`Unsupported language '${r}', falling back to plaintext`),u="plaintext"),cA.trace(`Language = ${u}`),(async()=>{a(await WY(e,{lang:u,theme:n}))})()},[e,r,n]),f.jsxs("div",{className:ue("relative group text-left",t),children:[f.jsx("div",{className:ue(XY.CopyButtonContainer,"bg-transparant absolute top-[10px] right-[10px] rounded-md z-10 text-lg flex items-center justify-center opacity-0 group-hover:opacity-100",{"rounded-l-0 opacity-100":o}),children:!s&&f.jsx("button",{className:ue("flex items-center bg-accent-500 p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300 rounded-md transition-theme",{"before:opacity-0":!o,"before:opacity-100":o}),title:"Copy Code",onClick:()=>c(),children:f.jsx("div",{className:"i-ph:clipboard-text-duotone"})})}),f.jsx("div",{dangerouslySetInnerHTML:{__html:i??""}})]})}),QY="z",ZY={MarkdownContent:QY},eX=({title:t,children:e})=>{const[r,n]=x.useState(!1);return f.jsxs("div",{onClick:()=>n(!r),className:` 536 bg-bolt-elements-background-depth-2 537 shadow-md 538 rounded-lg 539 cursor-pointer 540 transition-all 541 duration-300 542 ${r?"max-h-96":"max-h-13"} 543 overflow-auto 544 border border-bolt-elements-borderColor 545 `,children:[f.jsxs("div",{className:"p-4 flex items-center gap-4 roun
545ded-lg text-bolt-elements-textSecondary font-medium leading-5 text-sm border border-bolt-elements-borderColor",children:[f.jsx("div",{className:"i-ph:brain-thin text-2xl"}),f.jsxs("div",{className:"div",children:[f.jsxs("span",{children:[" ",t]})," ",!r&&f.jsx("span",{className:"text-bolt-elements-textTertiary",children:" - Click to expand"})]})]}),f.jsx("div",{className:` 546 transition-opacity 547 duration-300 548 p-4 549 rounded-lg 550 ${r?"opacity-100":"opacity-0"} 551 `,children:e})]})},Wb=ya("MarkdownComponent");function ko(...t){return t.filter(Boolean).join(" ")}const Jd=x.memo(({children:t,html:e=!1,limitedMarkdown:r=!1,append:n,setChatMode:s,model:i,provider:a})=>{Wb.trace("Render");const o=x.useMemo(()=>({h1:({className:c,children:u,...d})=>f.jsx("h1",{className:ko("text-3xl font-semibold leading-tight text-bolt-elements-textPrimary pb-1 border-b border-bolt-elements-borderColor mb-4 mt-6 first:mt-0",c),...d,children:u}),h2:({className:c,children:u,...d})=>f.jsx("h2",{className:ko("text-2xl font-semibold leading-tight text-bolt-elements-textPrimary pb-1 border-b border-bolt-elements-borderColor mb-4 mt-6 first:mt-0",c),...d,children:u}),h3:({className:c,children:u,...d})=>f.jsx("h3",{className:ko("text-xl font-semibold leading-tight text-bolt-elements-textPrimary mb-4 mt-6 first:mt-0",c),...d,children:u}),h4:({className:c,children:u,...d})=>f.jsx("h4",{className:ko("text-lg font-semibold leading-tight text-bolt-elements-textPrimary mb-4 mt-5 first:mt-0",c),...d,children:u}),h5:({className:c,children:u,...d})=>f.jsx("h5",{className:ko("text-base font-semibold leading-tight text-bolt-elements-textPrimary mb-3 mt-5 first:mt-0",c),...d,children:u}),h6:({className:c,children:u,...d})=>f.jsx("h6",{className:ko("text-sm font-semibold leading-tight text-bolt-elements-textSecondary mb-3 mt-5 first:mt-0",c),...d,children:u}),p:({className:c,children:u,...d})=>f.jsx("p",{className:ko("whitespace-pre-wrap text-[15px] leading-7 text-bolt-elements-textPrimary mb-4 last:mb-0",c),...d,children:u}),ol:({className:c,children:u,...d})=>f.jsx("ol",{className:ko("mb-4 list-decimal pl-8 text-[15px] leading-7 text-bolt-elements-textPrimary",c),...d,children:u}),ul:({className:c,children:u,...d})=>f.jsx("ul",{className:ko("mb-4 list-disc pl-8 text-[15px] leading-7 text-bolt-elements-textPrimary",c),...d,children:u}),li:({className:c,children:u,...d})=>f.jsx("li",{className:ko("mb-2 last:mb-0",c),...d,children:u}),div:({className:c,children:u,node:d,...h})=>{const m=d?.properties;if(c?.includes("__boltArtifact__")){const b=d?.properties.dataMessageId;return b||Wb.error(`Invalid message id ${b}`),f.jsx(VY,{messageId:b})}if(c?.includes("__boltSelectedElement__")){const b=d?.properties.dataMessageId,g=d?.properties.dataElement;let p=null;if(g)try{p=JSON.parse(g)}catch(y){console.error("Failed to parse element data:",y)}return b||Wb.error(`Invalid message id ${b}`),f.jsxs("div",{className:"bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor rounded-lg p-3 my-2",children:[f.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[f.jsx("span",{className:"text-xs font-mono bg-bolt-elements-background-depth-2 px-2 py-1 rounded text-bolt-elements-textTer",children:p?.tagName}),p?.className&&f.jsxs("span",{className:"text-xs text-bolt-elements-textSecondary",children:[".",p.className]})]}),f.jsx("code",{className:"block text-sm !text-bolt-elements-textSecondary !bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor p-2 rounded",children:p?.dis
551playText})]})}return c?.includes("__boltThought__")?f.jsx(eX,{title:"Thought process",children:u}):c?.includes("__boltQuickAction__")||m?.dataBoltQuickAction?f.jsx("div",{className:"flex items-center gap-2 flex-wrap mt-3.5",children:u}):f.jsx("div",{className:c,...h,children:u})},pre:c=>{const{children:u,node:d,...h}=c,[m]=d?.children??[];if(m&&m.type==="element"&&m.tagName==="code"&&m.children[0].type==="text"){const{className:b,...g}=m.properties,[,p="plaintext"]=/language-(\w+)/.exec(String(b)||"")??[];return f.jsx(JY,{code:m.children[0].value,language:p,...g})}return f.jsx("pre",{...h,children:u})},button:({node:c,children:u,...d})=>{const h=c?.properties;if(h?.class?.toString().includes("__boltQuickAction__")||h?.dataBoltQuickAction==="true"){const m=h["data-type"]||h.dataType,b=h["data-message"]||h.dataMessage,g=h["data-path"]||h.dataPath,p=h["data-href"]||h.dataHref,_={file:"i-ph:file",message:"i-ph:chats",implement:"i-ph:code",link:"i-ph:link"}[typeof m=="string"?m:""]??"i-ph:question";return f.jsxs("button",{className:"rounded-md justify-center px-3 py-1.5 text-xs bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent opacity-90 hover:opacity-100 flex items-center gap-2 cursor-pointer","data-type":m,"data-message":b,"data-path":g,"data-href":p,onClick:()=>{if(m==="file")uN(g);else if(m==="message"&&n)n({id:`quick-action-message-${Date.now()}`,content:[{type:"text",text:`[Model: ${i}] 552 553[Provider: ${a?.name}] 554 555${b}`}],role:"user"}),console.log("Message appended:",b);else if(m==="implement"&&n&&s)s("build"),n({id:`quick-action-implement-${Date.now()}`,content:[{type:"text",text:`[Model: ${i}] 556 557[Provider: ${a?.name}] 558 559${b}`}],role:"user"});else if(m==="link"&&typeof p=="string")try{const w=new URL(p,window.location.origin);window.open(w.toString(),"_blank","noopener,noreferrer")}catch(w){console.error("Invalid URL:",p,w)}},children:[f.jsx("div",{className:`text-lg ${_}`}),u]})}return f.jsx("button",{...d,children:u})}}),[]),l=x.useMemo(()=>{const c=tX(t),u=hN(c),d=fN(u);return pN(d)},[t]);return f.jsx(_O,{allowedElements:YD,className:ZY.MarkdownContent,components:o,remarkPlugins:KD(r),rehypePlugins:qD(e),children:l})});function tX(t){if(!t||!t.includes("__boltArtifact__"))return t;const e=/<div[^>]*class=["'][^"']*__boltArtifact__[^"']*["'][^>]*><\/div>/gi;let r=!1;return t.replace(e,n=>r?"":(r=!0,n))}const hN=t=>{if(!t||!t.includes("__boltArtifact__"))return t;const e=t.split(` 560`),r=e.findIndex(n=>n.includes("__boltArtifact__"));return r===-1?t:(r>0&&e[r-1]?.trim().match(/^```\w*$/)&&(e[r-1]=""),r<e.length-1&&e[r+1]?.trim().match(/^```$/)&&(e[r+1]=""),e.join(` 561`))},fN=t=>{if(!t||!t.includes("__boltArtifact__"))return t;const e=t.split(` 562`),r=[];let n=!1,s=[],i=!1;for(const a of e){if(/^```/.test(a.trim())){s.push(a),n&&(s.join(` 563`).includes("__boltArtifact__")?r.push(...s):i=!0,s=[]),n=!n;continue}if(n){s.push(a);continue}r.push(a)}return s.length>0&&r.push(...s),i?r.join(` 564`).replace(/\n{3,}/g,` 565 566`).trimEnd():r.join(` 567`)},rX=/^(?:import\s+|export\s+|const\s+|let\s+|var\s+|function\s+|interface\s+|type\s+|class\s+|return\s+|if\s*\(|for\s*\(|while\s*\(|switch\s*\(|case\s+|default:|try\s*{|catch\s*\(|await\s+|async\s+|new\s+)/,nX=/(?:=>|<\/?[A-Za-z][\w:-]*(?:\s[^>]*)?>|\b[a-zA-Z_$][\w$]*\s*[:=]\s*[{[\w"']|\b[a-zA-Z_$][\w$]*\([^)]*\)\s*{|\bconsole\.[a-z]+\(|\bCREATE\s+TABLE\b|\bALTER\s+TABLE\b)/;function sX(t){const e=t.trim();if(!e||e.includes("__boltArtifact__")||e.includes("__boltQuickAction__")||/^#{1,6}\s/.test(e)||/^[-*]\s+/.test(e)||/^\d+\.\s+/.test(e)||/^\|.+\|$/.test(e))return!1;if(/^`{3}/.test(e)||/^<bolt(?:Artifact|Action)\b/.test(e)||rX.test(e)||nX.test(e)||/^[{}[\]();,]+$/.test(e))return!0;const r=(e.match(/[{}()[\];=<>]/g)||[]).length,n=/[A-Za-z]{4,}\s+[A-Za-z]{4,}/.test(e);return r>=5&&!n}function iX(t){if(t.length>=3)return!0;const e=t.join(` 568`);return/\bimport\s+|\bexport\s+|=>|<\w+[^>]*>|<\/\w+>|\bconst\s+\w+\s*=|\bfunction\s+\w+\s*\(|\binterface\s+\w+/.test(e)&&t.length>=2}const pN=t=>{if(!t||!t.includes("__boltArtifact__"))return t;const e=t.split(` 569`),r=[];let n=[],s=!1;const i=()=>{n.length!==0&&(iX(n)?s=!0:r.push(...n),n=[])};for(const a of e){if(sX(a)){n.push(a);continue}i(),r.push(a)}return i(),s?r.join(` 570`).replace(/\n{3,}/g,` 571 572`).trimEnd():r.join(` 573`)},oX=Object.freeze(Object.defineProperty({__proto__:null,Markdown:Jd,stripCodeFenceFromArtifact:hN,stripFencedCodeBlocksWhenArtifactsPresent:fN,stripInlineCodeLikeBlocksWhenArtifactsPresent:pN},Symbol.toStringTag,{value:"Module"}));var Fm="Popover",[mN]=fE(Fm,[dE]),wh=dE(),[aX,fl]=mN(Fm),gN=t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:s,onOpenChange:i,modal:
573a=!1}=t,o=wh(e),l=x.useRef(null),[c,u]=x.useState(!1),[d,h]=nO({prop:n,defaultProp:s??!1,onChange:i,caller:Fm});return f.jsx(Q2,{...o,children:f.jsx(aX,{scope:e,contentId:sO(),triggerRef:l,open:d,onOpenChange:h,onOpenToggle:x.useCallback(()=>h(m=>!m),[h]),hasCustomAnchor:c,onCustomAnchorAdd:x.useCallback(()=>u(!0),[]),onCustomAnchorRemove:x.useCallback(()=>u(!1),[]),modal:a,children:r})})};gN.displayName=Fm;var bN="PopoverAnchor",vN=x.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,s=fl(bN,r),i=wh(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:o}=s;return x.useEffect(()=>(a(),()=>o()),[a,o]),f.jsx(hE,{...i,...n,ref:e})});vN.displayName=bN;var yN="PopoverTrigger",_N=x.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,s=fl(yN,r),i=wh(r),a=pE(e,s.triggerRef),o=f.jsx(i_.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":EN(s.open),...n,ref:a,onClick:Lo(t.onClick,s.onOpenToggle)});return s.hasCustomAnchor?o:f.jsx(hE,{asChild:!0,...i,children:o})});_N.displayName=yN;var w0="PopoverPortal",[lX,cX]=mN(w0,{forceMount:void 0}),xN=t=>{const{__scopePopover:e,forceMount:r,children:n,container:s}=t,i=fl(w0,e);return f.jsx(lX,{scope:e,forceMount:r,children:f.jsx(mE,{present:r||i.open,children:f.jsx(iO,{asChild:!0,container:s,children:n})})})};xN.displayName=w0;var du="PopoverContent",wN=x.forwardRef((t,e)=>{const r=cX(du,t.__scopePopover),{forceMount:n=r.forceMount,...s}=t,i=fl(du,t.__scopePopover);return f.jsx(mE,{present:n||i.open,children:i.modal?f.jsx(dX,{...s,ref:e}):f.jsx(hX,{...s,ref:e})})});wN.displayName=du;var uX=lO("PopoverContent.RemoveScroll"),dX=x.forwardRef((t,e)=>{const r=fl(du,t.__scopePopover),n=x.useRef(null),s=pE(e,n),i=x.useRef(!1);return x.useEffect(()=>{const a=n.current;if(a)return oO(a)},[]),f.jsx(aO,{as:uX,allowPinchZoom:!0,children:f.jsx(SN,{...t,ref:s,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Lo(t.onCloseAutoFocus,a=>{a.preventDefault(),i.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Lo(t.onPointerDownOutside,a=>{const o=a.detail.originalEvent,l=o.button===0&&o.ctrlKey===!0,c=o.button===2||l;i.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Lo(t.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),hX=x.forwardRef((t,e)=>{const r=fl(du,t.__scopePopover),n=x.useRef(!1),s=x.useRef(!1);return f.jsx(SN,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{t.onCloseAutoFocus?.(i),i.defaultPrevented||(n.current||r.triggerRef.current?.focus(),i.preventDefault()),n.current=!1,s.current=!1},onInteractOutside:i=>{t.onInteractOutside?.(i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;r.triggerRef.current?.contains(a)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),SN=x.forwardRef((t,e)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=t,h=fl(du,r),m=wh(r);return cO(),f.jsx(uO,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:i,children:f.jsx(dO,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>h.onOpenChange(!1),children:f.jsx(eO,{"data-state":EN(h.open),role:"dialog",id:h.contentId,...m,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),CN="PopoverClose",fX=x.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,s=fl(CN,r);return f.jsx(i_.button,{type:"button",...n,ref:e,onClick:Lo(t.onClick,()=>s.onOpenChange(!1))})});fX.displayName=CN;var pX="PopoverArrow",AN=x.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,s=wh(r);return f.jsx(Z2,{...s,...n,ref:e})});AN.displayName=pX;function EN(t){return t?"open":"closed"}var kN=gN,mX=vN,PN=_N,TN=xN,RN=wN,IN=AN;const gX=({children:t,trigger:e,side:r,align:n})=>f.jsxs(kN,{children:[f.jsx(PN,{asChild:!0,children:e}),f.jsx(mX,{}),f.jsx(TN,{children:f.jsxs(RN,{sideOffset:10,side:r,align:n,className:"bg-bolt-elements-background-depth-2 text-bolt-elements-item-contentAccent p-2 rounded-md shadow-xl z-workbench",children:[t,f.jsx(IN,{className:"bg-bolt-elements-item-background-depth-2"})]})})]}),bX={langs:["json"],themes:["light-plus","dark-plus"]},vX=await Bm(bX);function Fy({className:t,code:e,theme:r}){let n=e;try{if(typeof n=="object")n=JSON.stringify(n,null,2);else if(typeof n=="string")try{const s=JSON.parse(n);n=JSON.stringify(s,null,2)}catch{}}catch(s){yD.error("Failed to parse JSON",{error:s})}return f.jsx("div",{className:ue("text-xs rounded-md overflow-hidden mcp-tool-invocation-code",t),dangerouslySetInnerHTML:{__html:vX.codeToHtml(n,{lang:"json",theme:r==="dark"?"dark-plus":"light-plus"})},style:{padding:"0",margin:"0"}})}const yX=x.memo(({toolInvocations:t,toolCallAnnotations:e,addToolResult:r})=>{const n=We(Ed),[s,i]=x.useState(!1),a=()=>{i(d=>!d)},o=x.useMemo(()=>t.filter(d=>d.toolInvocation.state==="call"),[t]),l=x.useMemo(()=>t.filter(d=>d.toolInvocation.state==="result"),[t]),c=o.length>0,u=l.length>0;return!c&&!u?null:f.jsxs("div",{className:"tool-invocation border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150",children:[f.jsxs("div",{className:"flex",children:[f.jsxs("button",{className:"flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden",onClick:a,"aria-label":s?"Collapse details":"Expand details",children:[f.jsx("div",{className:"p-2.5",children:f.jsx("div",{className:"i-ph:wrench text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"})}),f.jsx("div",{className:"border-l border-bolt-elements-borderColor p-2.5 w-full text-left",children:f.jsxs("div",{className:"w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm",children:["MCP Tool Invocations"," ",u&&f.jsxs("span",{className:"w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5",children:["(",l.length," tool",u?"s":""," used)"]})]})})]}),f.jsx(Si,{children:u&&f.jsx(ar.button,{initial:{width:0},animate:{width:"auto"},exit:{width:0},transition:{duration:.15,ease:Ds},className:"bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover",onClick:a,children:f.jsx("div",{className:"p-2",children:f.jsx("div",{className:`${s?"i-ph:caret-up-bold":"i-ph:caret-down-bold"} text-xl text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors`})})})})]}),f.jsxs(Si,{children:[c&&f.jsxs(ar.div,{className:"details",initial:{height:0},animate:{height:"auto"},exit:{height:"0px"},transition:{duration:.15},children:[f.jsx("div",{className:"bg-bolt-elements-artifacts-borderColor h-[1px]"}),f.jsx("div",{className:"px-3 py-3 text-left bg-bolt-elements-actions-background",children:f.jsx(xX,{toolInvocations:o,toolCallAnnotations:e,addToolResult:r,theme:n})})]}),u&&s&&f.jsxs(ar.div,{className:"details",initial:{height:0},animate:{height:"auto"},exit:{height:"0px"},transition:{duration:.15},children:[f.jsx("div",{className:"bg-bolt-elements-artifacts-borderColor h-[1px]"}),f.jsx("div",{className:"p-5 text-left bg-bolt-elements-actions-background",children:f.jsx(_X,{toolInvocations:l,toolCallAnnotations:e,theme:n})})]})]})]})}),NN={hidden:{opacity:0,y:20},visible:{opacity:1,y:0}},_X=x.memo(({toolInvocations:t,toolCallAnnotations:e,theme:r})=>f.jsx(ar.div,{initial:{opacity:0}
573,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:f.jsx("ul",{className:"list-none space-y-4",children:t.map((n,s)=>{if(n.toolInvocation.state!=="result")return null;const{toolName:a,toolCallId:o}=n.toolInvocation,l=e.find(u=>u.toolCallId===o),c=[dD,hD,fD].includes(n.toolInvocation.result);return f.jsxs(ar.li,{variants:NN,initial:"hidden",animate:"visible",transition:{duration:.2,ease:Ds},children:[f.jsxs("div",{className:"flex items-center gap-1.5 text-xs mb-1",children:[c?f.jsx("div",{className:"text-lg text-bolt-elements-icon-error",children:f.jsx("div",{className:"i-ph:x"})}):f.jsx("div",{className:"text-lg text-bolt-elements-icon-success",children:f.jsx("div",{className:"i-ph:check"})}),f.jsx("div",{className:"text-bolt-elements-textSecondary text-xs",children:"Server:"}),f.jsx("div",{className:"text-bolt-elements-textPrimary font-semibold",children:l?.serverName})]}),f.jsxs("div",{className:"ml-6 mb-2",children:[f.jsxs("div",{className:"text-bolt-elements-textSecondary text-xs mb-1",children:["Tool: ",f.jsx("span",{className:"text-bolt-elements-textPrimary font-semibold",children:a})]}),f.jsxs("div",{className:"text-bolt-elements-textSecondary text-xs mb-1",children:["Description:"," ",f.jsx("span",{className:"text-bolt-elements-textPrimary font-semibold",children:l?.toolDescription})]}),f.jsx("div",{className:"text-bolt-elements-textSecondary text-xs mb-1",children:"Parameters:"}),f.jsx("div",{className:"bg-[#FAFAFA] dark:bg-[#0A0A0A] p-3 rounded-md",children:f.jsx(Fy,{className:"mb-0",code:JSON.stringify(n.toolInvocation.args),theme:r})}),f.jsx("div",{className:"text-bolt-elements-textSecondary text-xs mt-3 mb-1",children:"Result:"}),f.jsx("div",{className:"bg-[#FAFAFA] dark:bg-[#0A0A0A] p-3 rounded-md",children:f.jsx(Fy,{className:"mb-0",code:JSON.stringify(n.toolInvocation.result),theme:r})})]})]},s)})})})),xX=x.memo(({toolInvocations:t,toolCallAnnotations:e,addToolResult:r,theme:n})=>{const[s,i]=x.useState({}),a=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),o=l=>{i(c=>({...c,[l]:!c[l]}))};return x.useEffect(()=>{const l={};t.forEach(c=>{c.toolInvocation.state==="call"&&(l[c.toolInvocation.toolCallId]=!0)}),i(c=>{const u=Object.keys(c),d=Object.keys(l);return u.length===d.length&&d.every(h=>c[h]===l[h])?c:l})},[t]),x.useEffect(()=>{const l=c=>{const u=document.activeElement;if(u&&(u.tagName==="INPUT"||u.tagName==="TEXTAREA"||u.isContentEditable)||Object.keys(s).length===0)return;const d=Object.keys(s).find(h=>s[h]);d&&((a?c.metaKey:c.ctrlKey)&&c.key==="Backspace"&&(c.preventDefault(),r({toolCallId:d,result:jh.REJECT})),(a?c.metaKey:c.ctrlKey)&&(c.key==="Enter"||c.key==="Return")&&(c.preventDefault(),r({toolCallId:d,result:jh.APPROVE})))};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[s,r,a]),f.jsx(ar.div,{initial:{opacity:0}
573,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:f.jsx("ul",{className:"list-none space-y-4",children:t.map((l,c)=>{if(l.toolInvocation.state!=="call")return null;const{toolName:d,toolCallId:h}=l.toolInvocation,m=e.find(b=>b.toolCallId===h);return f.jsx(ar.li,{variants:NN,initial:"hidden",animate:"visible",transition:{duration:.2,ease:Ds},children:f.jsx("div",{className:"",children:f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsxs("div",{className:"flex items-center text-bolt-elements-textSecondary font-semibold text-sm",children:[f.jsx("button",{onClick:()=>o(h),className:"mr-1 focus:outline-none bg-transparent","aria-label":s[h]?"Collapse":"Expand",tabIndex:0,type:"button",children:f.jsx("span",{className:`i-ph:caret-down-bold inline-block transition-transform duration-150 ${s[h]?"":"-rotate-90"}`})}),"Calling MCP tool"," ",f.jsx("span",{className:"ml-0.5 font-light font-mono text-bolt-elements-textPrimary bg-bolt-elements-background-depth-3 px-1.5 py-0.5 rounded-md",children:d})]}),s[h]&&f.jsxs("div",{className:"flex gap-3",children:[f.jsx("div",{className:"w-[0.1px] min-h-[40px] bg-bolt-elements-background-depth-3 ml-1.5"}),f.jsxs("div",{className:"flex flex-col gap-1 w-full",children:[f.jsxs("div",{className:"text-bolt-elements-textSecondary text-xs mb-1",children:["Description:"," ",f.jsx("span",{className:"text-bolt-elements-textPrimary font-semibold",children:m?.toolDescription})]}),f.jsx("div",{className:"flex w-full items-stretch space-x-2",children:f.jsx("div",{className:"w-full rounded-md bg-bolt-elements-background-depth-3 p-3 ml-0 border-l-2 border-bolt-elements-borderColor",children:f.jsx(Fy,{className:"mb-0",code:JSON.stringify(l.toolInvocation.args,null,2),theme:n})})})]})]}),f.jsxs("div",{className:"flex justify-end gap-2 pt-2.5",children:[f.jsxs("button",{className:ue("px-2.5 py-1.5 rounded-lg text-xs","bg-transparent","text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary","transition-all duration-200","flex items-center gap-2"),onClick:()=>r({toolCallId:h,result:jh.REJECT}),children:["Cancel ",f.jsx("span",{className:"opacity-70 text-xs ml-1",children:a?"ââ«":"Ctrl+Backspace"})]}),f.jsxs("button",{className:ue("inline-flex items-center gap-2 px-3.5 py-1.5 text-xs font-normal rounded-lg transition-colors","bg-accent-500 hover:bg-accent-600","text-black","disabled:opacity-50 disabled:cursor-not-allowed"),onClick:()=>r({toolCallId:h,result:jh.APPROVE}),children:["Run tool ",f.jsx("span",{className:"opacity-70 text-xs ml-1",children:a?"ââµ":"Ctrl+Enter"})]})]})]},h)})},c)})})})}),wX=/\s*\[CloudMySite [^\]]*note\][\s\S]*$/i,SX=/\s*<boltArtifact\b[\s\S]*?<\/boltArtifact>\s*/gi,CX=/\s*<div class=(['"])__boltSelectedElement__\1[^>]*>[\s\S]*?<\/div>\s*/gi,AX=/\s*<!--\s*system:[a-z-]+\s*-->[\s\S]*?<!--\s*\/system:[a-z-]+\s*-->\s*/gi,EX=/^\s*\[(?:Model|Provider):[^\]]+\]\s*$/gim,kX=/(?:^\s*|\s+)\[(?:Model|Provider):[^\]]+\](?=\s|$)/gim;function S0(t){return String(t||"").replace(EX,` 574`).replace(kX," ").replace(/\n{3,}/g,` 575 576`).replace(/[ \t]{2,}/g," ").trim()}function C0(t){return String(t||"").replace(SX,` 577`).replace(AX,` 578`).replace(CX,` 579`).replace(wX,"").trimEnd()}function PX(t){return t.level==="blocked"?{card:"border-rose-200 bg-rose-50/90 text-rose-950",progress:"bg-rose-500",badge:"bg-rose-100 text-rose-700",notice:"text-rose-700"}:t.level==="warning"?{card:"border-amber-200 bg-amber-50/90 text-amber-950",progress:"bg-amber-500",badge:"bg-amber-100 text-amber-700",notice:"text-amber-700"}:t.level==="notice"?{card:"border-sky-200 bg-sky-50/90 text-slate-900",progress:"bg-sky-500",badge:"bg-sky-100 text-sky-700",notice:"text-sky-700"}:{card:"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-bolt-elements-textPrimary",progress:"bg-emerald-500",badge:"bg-emerald-100 text-emerald-700",notice:"text-bolt-elements-textSecondary"}}function LN({annotation:t,className:e}){const{summary:r}=t,n=PX(r.threshold),s=[t.provider,t.model].filter(Boolean).join(" | "),i=s_(r);return f.jsxs("div",{className:ue("rounded-2xl border p-3 shadow-sm",n.card,e),children:[f.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] opacity-70",children:"AI Usage"}),f.jsx("div",{className:"mt-1 text-sm font-semibold",children:t.actionLabel}),s&&f.jsx("div",{className:"mt-1 text-xs opacity-70",children:s})]}),f.jsx("div",{className:ue("rounded-full px-2.5 py-1 text-[11px] font-semibold",n.badge),
579children:r.planName})]}),f.jsxs("div",{className:"mt-3 grid gap-3 text-sm sm:grid-cols-3",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] opacity-60",children:"This action"}),f.jsx("div",{className:"mt-1 font-semibold",children:Yl(t.tokensTotal)})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] opacity-60",children:"Monthly used"}),f.jsx("div",{className:"mt-1 font-semibold",children:Yl(i?.usedTokens||r.monthlyTokensUsed)})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] opacity-60",children:"Remaining"}),f.jsx("div",{className:"mt-1 font-semibold",children:Yl(i?.remainingTokens||r.monthlyTokensRemaining)})]})]}),f.jsx("div",{className:"mt-3 text-[11px] opacity-70",children:i?`Cycle started ${i.cycleStart} ⢠Resets ${i.cycleEnd}`:null}),f.jsxs("div",{className:"mt-3",children:[f.jsxs("div",{className:"flex items-center justify-between text-[11px] opacity-70",children:[f.jsx("span",{children:"Cycle usage"}),f.jsx("span",{children:n_(r.threshold.percent)})]}),f.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-black/10 dark:bg-white/10",children:f.jsx("div",{className:ue("h-full rounded-full transition-[width] duration-300",n.progress),style:{width:`${r.threshold.percent}%`}})})]}),r.threshold.level!=="healthy"&&f.jsx("div",{className:ue("mt-3 text-xs font-medium",n.notice),children:r.threshold.message})]})}function TX(t){t=DN(t),j.currentView.get()!=="code"&&j.currentView.set("code"),j.setSelectedFile(`${Za}/${t}`)}function DN(t){let e=t;return e.startsWith(Za)&&(e=t.replace(Za,"")),e.startsWith("/")&&(e=e.slice(1)),e}const RX=x.memo(({content:t,annotations:e,append:r,chatMode:n,setChatMode:s,model:i,provider:a,parts:o,addToolResult:l})=>{const c=x.useMemo(()=>e?.filter(p=>p&&typeof p=="object"&&Object.keys(p).includes("type"))||[],[e]);let u;c.find(p=>p.type==="chatSummary")&&(u=c.find(p=>p.type==="chatSummary")?.summary);let d;c.find(p=>p.type==="codeContext")&&(d=c.find(p=>p.type==="codeContext")?.files);const h=x.useMemo(()=>o?.filter(p=>p.type==="tool-invocation"),[o]),m=x.useMemo(()=>c.filter(p=>p.type==="toolCall"),[c]),b=x.useMemo(()=>[...c].reverse().find(p=>p.type==="usageSummary")||null,[c]),g=x.useMemo(()=>S0(t),[t]);return f.jsxs("div",{className:"overflow-hidden w-full",children:[f.jsx(f.Fragment,{children:f.jsx("div",{className:" flex gap-2 items-center text-sm text-bolt-elements-textSecondary mb-2",children:(d||u)&&f.jsxs(gX,{side:"right",align:"start",trigger:f.jsx("div",{className:"i-ph:info"}),children:[u&&f.jsxs("div",{className:"max-w-chat",children:[f.jsxs("div",{className:"summary max-h-96 flex flex-col",children:[f.jsx("h2",{className:"border border-bolt-elements-borderColor rounded-md p4",children:"Summary"}),f.jsx("div",{style:{zoom:.7},className:"overflow-y-auto m4",children:f.jsx(Jd,{children:u})})]}),d&&f.jsxs("div",{className:"code-context flex flex-col p4 border border-bolt-elements-borderColor rounded-md",children:[f.jsx("h2",{children:"Context"}),f.jsx("div",{className:"flex gap-4 mt-4 bolt",style:{zoom:.6},children:d.map(p=>{const y=DN(p);return f.jsx(x.Fragment,{children:f.jsx("code",{className:"bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md text-bolt-elements-item-contentAccent hover:underline cursor-pointer",onClick:v=>{v.preventDefault(),v.stopPropagation(),TX(y)},children:y})},y)})})]})]}),f.jsx("div",{className:"context"})]})})}),f.jsx(Jd,{append:r,chatMode:n,setChatMode:s,model:i,provider:a,html:!0,children:g}),b&&f.jsx(LN,{annotation:b,className:"mt-4"}),h&&h.length>0&&f.jsx(yX,{toolInvocations:h,toolCallAnnotations:m,addToolResult:l})]})});function IX({content:t,userVisibleContent:e,annotations:r,parts:n}){const s=We(Y1),i=typeof e=="string"&&e.trim().length>0,a=NX(LX(t,n,e)),o=x.useMemo(()=>gE({annotations:r}),[r]),l=x.useMemo(()=>o.filter(h=>h.mediaKind==="image"||String(h.mimeType||"").toLowerCase().startsWith("image/")),[o]),[c,u]=x.useState([]),d=x.useMemo(()=>DX(t,n,c),[c,t,n]);return x.useEffect(()=>{let h=!1;return l.length===0?(u([]),()=>{h=!0}):(Promise.all(l.map(async m=>{try{return{src:await YM(m),alt:m.filename||"Attached image"}}catch(b){return console.warn("[chat.user-message] Failed to load restored managed asset preview",{assetId:m.assetId,error:b}),null}})).then(m=>{h||u(m.filter(b=>b!==null))}),()=>{h=!0})},[l]),d.length>0?f.jsxs("div",{className:"overflow-hidden flex flex-col gap-3 items-center ",children:[f.jsx("div",{className:"flex flex-row items-start justify-center overflow-hidden shrink-0 self-start",children:s?.avatar||s?.username?f.jsxs("div",{className:"flex items-end gap-2",children:[f.jsx("img",{src:s.avatar,alt:s?.username||"User",className:"w-[25px] h-[25px] object-cover rounded-full",loading:"eager",decoding:"sync"}),f.jsx("span",{className:"text-bolt-elements-textPrimary text-sm",children:s?.username?s.username:""})]}):f.jsx("div",{className:"i-ph:user-fill text-accent-500 text-2xl"})}),f.jsxs("div",{className:"flex flex-col gap-4 bg-accent-500/10 backdrop-blur-sm p-3 py-3 w-auto rounded-lg mr-auto",children:[a&&f.jsx(Jd,{html:!0,children:a}),d.map((h,m)=>f.jsx("img",{src:h.src,alt:h.alt||`Image ${m+1}`,className:"max-w-full h-auto rounded-lg",style:{maxHeight:"512px",objectFit:"contain"}},`${h.src}-${m}`))]})]}):f.jsx("div",{className:`overflow-hidden pt-[4px] font-sans ${i?"max-w-[760px] pr-4 text-[15px] leading-8 tracking-[-0.01em]":""}`,children:f.jsx(Jd,{html:!0,children:a})})}function NX(t){const e=/<boltArtifact\s+[^>]*>[\s\S]*?<\/boltArtifact>/gm;return S0(C0(t).replace(e,""))}function LX(t,e,r){if(typeof r=="string"&&r.trim().length>0)return r;if(Array.isArray(t)){const n=t.find(s=>
579s.type==="text");if(typeof n?.text=="string"&&n.text.trim().length>0)return n.text}return typeof t=="string"?t:Array.isArray(e)?e.filter(n=>n?.type==="text"&&typeof n.text=="string").map(n=>n.text||"").join(" "):""}function DX(t,e,r){const n=[],s=new Set,i=(a,o)=>{typeof a!="string"||a.trim().length===0||s.has(a)||(s.add(a),n.push({src:a,alt:o}))};if(Array.isArray(t))for(const a of t)a?.type==="image"&&typeof a.image=="string"&&i(a.image,"Attached image");if(Array.isArray(e))for(const a of e){if(a?.type==="image"&&typeof a.image=="string"){i(a.image,"Attached image");continue}if(a?.type==="file"&&typeof a.data=="string"&&a.data.length>0){const o=typeof a.mimeType=="string"&&a.mimeType.length>0?a.mimeType:"image/png";i(`data:${o};base64,${a.data}`,"Attached image")}}if(n.length===0)for(const a of r)i(a.src,a.alt);return n}const Hb=x.forwardRef((t,e)=>{const{id:r,isStreaming:n=!1,messages:s=[]}=t;return f.jsxs("div",{id:r,className:t.className,ref:e,children:[s.length>0?s.map((i,a)=>{const{role:o,content:l,id:c,annotations:u,parts:d}=i,h=i.userVisibleContent,m=o==="user",b=a===0;return u?.includes("hidden")?f.jsx(x.Fragment,{},a):f.jsx("div",{className:ue("flex gap-4 py-3 w-full rounded-lg",{"mt-4":!b}),children:f.jsx("div",{className:"grid grid-col-1 w-full",children:m?f.jsx(IX,{content:l,userVisibleContent:typeof h=="string"?h:void 0,annotations:i.annotations,parts:d}):f.jsx(RX,{content:l,annotations:i.annotations,append:t.append,chatMode:t.chatMode,setChatMode:t.setChatMode,model:t.model,provider:t.provider,parts:d,addToolResult:t.addToolResult})})},a)}):null,n&&f.jsx("div",{className:"text-center w-full text-bolt-elements-item-contentAccent i-svg-spinners:3-dots-fade text-4xl mt-4"})]})}),MX="s",OX="t",jX="u",$X="v",Tf={BaseChat:MX,Chat:OX,WorkspaceTimelineScroller:jX,PromptQualificationActive:$X},BX="We couldn't open this starter template. Please try again or start from a custom prompt.",FX="Creating your app from template...",WX="Starter templates are unavailable right now. You can still start from a custom prompt.",HX=["modern-ecommerce","task-management-app","creative-portfolio","gdpr-compliant-cookie-consent","space-defender-game","tic-tac-toe-game","small-business-dashboard"],UX=[{label:"Build an e-commerce store using React and Tailwind",prompt:`Build a production-ready e-commerce web app using React, TypeScript, and Tailwind CSS. 580Requirements: 581- Use a clear folder structure with reusable components. 582- Add pages for home, product listing, product details, cart, checkout, and sign-in/sign-up UI. 583- Add filtering, sorting, search, pagination, and category chips on listing page. 584- Implement cart with quantity controls and persistence using localStorage. 585- Include responsive layout, loading/empty/error states, and accessible form controls. 586- Add a polished visual design and clear navigation header/footer. 587Deliverables: 588- Working app with mock product data, clean code, and setup instructions in README.`},{label:"Develop a task management app using React and Redux",prompt:`Create a task management app using React, TypeScript, Redux Toolkit, and Tailwind CSS. 589Requirements: 590- Support task CRUD, due dates, priority levels, tags, and completion toggle. 591- Provide filters for status, priority, and search text. 592- Add drag-and-drop reordering for tasks in each list. 593- Persist tasks in localStorage and restore state on reload. 594- Include responsive layout, keyboard-friendly interactions, and basic accessibility. 595Deliverables: 596- A clean dashboard-style UI with separate slices/selectors and maintainable code structure.`},{label:"Make a portfolio website with React and Framer Motion",prompt:`Build a modern personal portfolio site using React, TypeScript, Tailwind CSS, and Framer Motion. 597Requirements: 598- Sections: hero, about, skills, projects, testimonials, and contact. 599- Add smooth entrance animations, staggered card reveals, and section transitions. 600- Include project cards with tech stack, description, and live/demo links. 601- Add a functional contact form UI with validation and success/error feedback states. 602- Ensure fully responsive layout with strong typography and polished spacing. 603Deliverables: 604- A visually strong portfolio with reusable components and easy-to-edit content data.`},{label:"Create a cookie consent form using Material UI",prompt:`Create a GDPR-compliant cookie consent system using React, TypeScript, and Material UI. 605Requirements: 606- Show a consent banner on first visit with actions: Accept All, Reject Non-Essential, and Manage Preferences. 607- In preferences modal, include separate toggles for necessary (always on), analytics, marketing, and functional cookies. 608- Persist consent choices in localStorage and prevent banner from reappearing after consent. 609- Expose a settings button to reopen preferences and update consent later. 610- Include light/dark theme support, accessible labels, focus handling, and keyboard navigation. 611- Add clear copy explaining each cookie category and privacy intent. 612Deliverables: 613- Components, state management logic, and an example integration in app layout.`},{label:"Make a space invaders game",prompt:`Build a Space Invaders style browser game using HTML, CSS, and vanilla JavaScript. 614Requirements: 615- Use canvas rendering with smooth animation loop. 616- Implement player movement, shooting, enemy waves, collisions, scoring, and lives. 617- Add increasing difficulty by level (enemy speed, spawn density, projectile speed). 618- Add start, pause, game-over, and restart states. 619- Include keyboard controls, simple sound effects, and mobile-friendly fallback controls. 620Deliverables: 621- Cleanly structured game logic modules and a polished playable experience.`},{label:"Make a Tic Tac Toe game in html, css and js only",prompt:`Create a Tic Tac Toe game using only HTML, CSS, and vanilla JavaScript. 622Requirements: 623- Two-player mode with turn indicator and disabled filled cells. 624- Reliable win detection across rows, columns, and diagonals. 625- Draw detection with clear result messaging. 626- Restart button and score tracking for X and O across rounds. 627- Clean modern UI with responsive layout and keyboard-friendly actions. 628Deliverables: 629- Lightweight code without external libraries and clear separation of logic vs UI.`},{label:"Create a dashboard for small business owners.",prompt:`Build a responsive small-business dashboard using React, TypeScript, and Tailwind CSS. 630Requirements: 631- Top KPI cards for revenue, orders, conversion rate, and active customers. 632- Sales trend chart, traffic/source chart, and recent activity feed.
633- Date range filter and category/channel filters that update visible metrics. 634- Include loading, empty, and error states with realistic mock data. 635- Use consistent design tokens, clear hierarchy, and accessible color contrast. 636Deliverables: 637- Modular dashboard components with reusable chart wrappers and clean layout architecture.`}],zX=[{label:"Create a cake shop website",prompt:`Create a cake shop website with Eleventy and modern CSS. 638Include: 639- Home hero with featured cakes and CTA. 640- Product gallery with categories and pricing cards. 641- About section, opening hours, location map embed, and contact form UI. 642- Testimonials and FAQ section. 643- Fully responsive, mobile-first, and fast-loading static pages.`},{label:"Design a local cafe site",prompt:`Design a local cafe website with Eleventy. 644Include: 645- Homepage with warm visual style and featured menu items. 646- Dedicated menu page with categories and prices. 647- Location section with map, opening hours, and contact details. 648- Photo gallery and customer reviews section. 649- Responsive, accessible, and performance-focused static layout.`},{label:"Make a personal portfolio website",prompt:`Build a personal portfolio website using Eleventy. 650Include: 651- About, skills, project showcase, and blog listing pages. 652- Project detail page template with tech stack and outcomes. 653- Contact section and social links. 654- Clean modern typography and responsive layout. 655- Reusable templates and content collections for easy updates.`},{label:"Create an online store",prompt:`Create a static online store front-end with Eleventy. 656Include: 657- Product listing and category pages with filters and search UI. 658- Product detail pages with images, descriptions, and CTA buttons. 659- Cart and checkout interface (UI only, no backend checkout). 660- Responsive layout with conversion-focused product cards. 661- Reusable components and maintainable template structure.`},{label:"Create a dental website",prompt:`Create a professional dental clinic website in Eleventy. 662Include: 663- Services pages, doctor profiles, and patient testimonials. 664- Appointment request form UI and emergency contact block. 665- Clinic location with map, hours, and insurance/payment info. 666- Trust-focused design with clear CTAs and readable hierarchy. 667- Mobile-first and accessible static pages.`},{label:"Make a blog for travel and lifestyle",prompt:`Build a travel and lifestyle blog using Eleventy. 668Include: 669- Featured posts section and category/tag pages. 670- Article template with reading time, author bio, and share links. 671- Newsletter sign-up form UI and related posts section. 672- Image-forward but performant layout with lazy-loading strategy. 673- Clean typography optimized for long-form reading.`},{label:"Design a non-profit organization website",prompt:`Design a non-profit organization website with Eleventy. 674Include: 675- Mission, vision, and impact stories pages. 676- Programs/initiatives listing with detail templates. 677- Donation section (UI only) and volunteer sign-up form UI. 678- Team section, events/news area, and contact details. 679- Trustworthy, accessible, and responsive design system.`}];function Jf(t){return String(t||"").trim()}function VX(t){const e=Jf(t.slug),r=Jf(t.name);return!e||!r?null:{slug:e,name:r,category:Jf(t.category)||null}}function GX(t){const e=new Map;for(const r of t){const n=VX(r);n&&e.set(n.slug,n)}return HX.map(r=>e.get(r)).filter(r=>!!r)}function uA(t){if(typeof window>"u")return;const e=RO(t);sv(e),window.location.assign(`/login?returnTo=${encodeURIComponent(e)}`)}function qX(t){typeof window>"u"||window.location.assign(t)}function KX({onPromptSelect:t,isEleventy:e}){const[r,n]=x.useState(null),[s,i]=x.useState(null),[a,o]=x.useState([]),[l,c]=x.useState(!1),[u,d]=x.useState(null),h=e?zX:UX,m=!e;x.useEffect(()=>{if(!m)return;let g=!1;return(async()=>{c(!0),d(null);try{const y=await fetch("/api/templates",{cache:"no-store"}),v=await y.json().catch(()=>({}));if(!y.ok)throw new Error(v.error||v.details||"Unable to load starter templates.");g||o(GX(Array.isArray(v.templates)?v.templates:[]))}catch(y){console.warn("[chat.starterTemplates] Failed to load template catalog.",y),g||(o([]),d(WX))}finally{g||c(!1)}})(),()=>{g=!0}},[m]);const b=x.useCallback(async g=>{if(!r){n(g.slug),i(null);try{const p=await yO("/api/apps/from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:g.slug})},{retryOnUnauthorized:!0}),v=(p.headers.get("Content-Type")||"").includes("application/json")?await p.json().catch(()=>({})):{error:await p.text().catch(()=>"")};if(!p.ok){if(p.status===401){uA(g.slug);return}throw new Error(v.error||v.details||"Unable to create an app from that template.")}const _=Jf(v.redirectUrl||v.route);if(!_)throw new Error("Template was created, but the builder route was missing.");qX(_)}catch(p){if(console.error("[chat.starterTemplates] Failed to use starter template.",p),p instanceof Error&&/\b(log in|session expired|authenticated)\b/i.test(p.message)){uA(g.slug);return}i(BX)}finally{n(null)}}},[r]);return m?f.jsxs("div",{id:"examples",className:"relative mx-auto mb-10 mt-6 flex w-full max-w-4xl flex-col gap-4 px-3",children:[f.jsxs("div",{className:"text-center",children:[f.jsx("h3",{className:"text-base font-semibold text-bolt-elements-textPrimary",children:"Start instantly with a ready-made app"}),f.jsx("p",{className:"mt-1 text-sm text-bolt-elements-textSecondary",children:"Choose a starter template, customize it with AI, and launch faster."})]}),r?f.jsx("p",{className:"text-center text-xs font-medium text-bolt-elements-textSecondary","aria-live":"polite",children:FX}
679):null,s?f.jsx("p",{className:"mx-auto max-w-2xl rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-center text-xs font-medium text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-200",role:"alert",children:s}):null,l?f.jsx("p",{className:"text-center text-xs font-medium text-bolt-elements-textSecondary","aria-live":"polite",children:"Loading starter templates..."}):null,u?f.jsx("p",{className:"mx-auto max-w-2xl rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-center text-xs font-medium text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200",role:"status",children:u}):null,f.jsx("div",{className:"mx-auto grid w-full max-w-3xl grid-cols-1 gap-2 sm:grid-cols-2",style:{animation:".25s ease-out 0s 1 _fade-and-move-in_g2ptj_1 forwards"},children:a.map(g=>{const p=r===g.slug;return f.jsxs("button",{type:"button",onClick:()=>{b(g)},disabled:p,"aria-busy":p,className:ue("group flex w-full min-w-0 items-center gap-2 rounded-full border border-bolt-elements-borderColor bg-white/85 px-3 py-1.5 text-xs font-medium text-bolt-elements-textSecondary shadow-sm shadow-slate-200/50 transition-theme hover:border-[#0b67b2]/45 hover:bg-white hover:text-bolt-elements-textPrimary dark:bg-gray-950/80 dark:shadow-none dark:hover:bg-gray-900",p?"cursor-wait opacity-75":"cursor-pointer"),children:[f.jsx("span",{className:"shrink-0 rounded-full bg-[#e8f2ff] px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-[#075fae] dark:bg-[#0b3159] dark:text-[#9fd0ff]",children:"Instant"}),f.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:g.name}),f.jsx("span",{className:"hidden rounded-full border border-[#d5e3f3] bg-[#f7fbff] px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-[#386180] dark:border-white/10 dark:bg-white/5 dark:text-slate-300 sm:inline",children:"Template"}),p?f.jsx("span",{className:"shrink-0 text-[11px] text-[#075fae] dark:text-[#9fd0ff]",children:"Creating..."}):null]},g.slug)})})]}):f.jsxs("div",{id:"examples",className:"relative flex flex-col gap-9 w-full max-w-3xl mx-auto flex justify-center mt-6",children:[f.jsx("p",{className:"text-center text-sm text-gray-500 dark:text-gray-400",children:"Try these prompts to quickly start building or exploring ideas:"}),f.jsx("div",{className:"flex flex-wrap justify-center gap-2",style:{animation:".25s ease-out 0s 1 _fade-and-move-in_g2ptj_1 forwards"},children:h.map((g,p)=>f.jsx("button",{onClick:()=>{t?.(g.prompt)},className:"border border-bolt-elements-borderColor rounded-full bg-gray-50 hover:bg-gray-100 dark:bg-gray-950 dark:hover:bg-gray-900 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary px-3 py-1 text-xs transition-theme",children:g.label},p))})]})}function YX({alert:t,clearAlert:e,postMessage:r}){const{type:n,title:s,description:i,content:a,url:o,stage:l,buildStatus:c,deployStatus:u}=t,d=l&&(c||u);return f.jsx(Si,{children:f.jsx(ar.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3},className:"rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 mb-2",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx(ar.div,{className:"flex-shrink-0",initial:{scale:0},animate:{scale:1},transition:{delay:.2},children:f.jsx("div",{className:ue("text-xl",n==="success"?"i-ph:check-circle-duotone text-bolt-elements-icon-success":n==="error"?"i-ph:warning-duotone text-bolt-elements-button-danger-text":"i-ph:info-duotone text-bolt-elements-loader-progress")})}),f.jsxs("div",{className:"ml-3 flex-1",children:[f.jsx(ar.h3,{initial:{opacity:0}
679,animate:{opacity:1},transition:{delay:.1},className:"text-sm font-medium text-bolt-elements-textPrimary",children:s}),f.jsxs(ar.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"mt-2 text-sm text-bolt-elements-textSecondary",children:[f.jsx("p",{children:i}),d&&f.jsx("div",{className:"mt-4 mb-2",children:f.jsxs("div",{className:"flex items-center space-x-2 mb-3",children:[f.jsxs("div",{className:"flex items-center",children:[f.jsx("div",{className:ue("w-6 h-6 rounded-full flex items-center justify-center",c==="running"?"bg-bolt-elements-loader-progress":c==="complete"?"bg-bolt-elements-icon-success":c==="failed"?"bg-bolt-elements-button-danger-background":"bg-bolt-elements-textTertiary"),children:c==="running"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg text-white text-xs"}):c==="complete"?f.jsx("div",{className:"i-ph:check text-white text-xs"}):c==="failed"?f.jsx("div",{className:"i-ph:x text-white text-xs"}):f.jsx("span",{className:"text-white text-xs",children:"1"})}),f.jsx("span",{className:"ml-2",children:"Build"})]}),f.jsx("div",{className:ue("h-0.5 w-8",c==="complete"?"bg-bolt-elements-icon-success":"bg-bolt-elements-textTertiary")}),f.jsxs("div",{className:"flex items-center",children:[f.jsx("div",{className:ue("w-6 h-6 rounded-full flex items-center justify-center",u==="running"?"bg-bolt-elements-loader-progress":u==="complete"?"bg-bolt-elements-icon-success":u==="failed"?"bg-bolt-elements-button-danger-background":"bg-bolt-elements-textTertiary"),children:u==="running"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg text-white text-xs"}):u==="complete"?f.jsx("div",{className:"i-ph:check text-white text-xs"}):u==="failed"?f.jsx("div",{className:"i-ph:x text-white text-xs"}):f.jsx("span",{className:"text-white text-xs",children:"2"})}),f.jsx("span",{className:"ml-2",children:"Deploy"})]})]})}),a&&f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary p-2 bg-bolt-elements-background-depth-3 rounded mt-4 mb-4",children:a}),o&&n==="success"&&f.jsx("div",{className:"mt-2",children:f.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"text-bolt-elements-item-contentAccent hover:underline flex items-center",children:[f.jsx("span",{className:"mr-1",children:"View deployed site"}),f.jsx("div",{className:"i-ph:arrow-square-out"})]})})]}),f.jsx(ar.div,{className:"mt-4",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},children:f.jsxs("div",{className:ue("flex gap-2"),children:[n==="error"&&f.jsxs("button",{onClick:()=>r(`*Fix this deployment error* 680\`\`\` 681${a||i} 682\`\`\` 683`),className:ue("px-2 py-1.5 rounded-md text-sm font-medium","bg-bolt-elements-button-primary-background","hover:bg-bolt-elements-button-primary-backgroundHover","focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-danger-background","text-bolt-elements-button-primary-text","flex items-center gap-1.5"),children:[f.jsx("div",{className:"i-ph:chat-circle-duotone"}),"Ask Bolt"]}),f.jsx("button",{onClick:e,className:ue("px-2 py-1.5 rounded-md text-sm font-medium","bg-bolt-elements-button-secondary-background","hover:bg-bolt-elements-button-secondary-backgroundHover","focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-secondary-background","text-bolt-elements-button-secondary-text"),children:"Dismiss"})]})})]})]})})})}function XX(t){return`*Auto-repair this project error now.* 684You are repairing the generated project from the full diagnostics. You may rewrite generated app files completely when that is the fastest reliable fix. 685Fix the generated project so it compiles, starts, and preview loads. Stream complete corrected file contents for every affected file. 686Do not replace real persistence with mock data, no-op CRUD, or local-only sample data. Preserve published data storage behavior; if preview needs a fallback, keep the same API contract. 687For repeated content collections such as menus, products, services, locations, galleries, FAQs, destinations, or similar item lists, fix the persisted source of truth and its sync logic, not just the page copy. 688\`\`\`text 689${String(t.content||t.description||t.title||"Unknown project error").trim().slice(0,12e3)} 690\`\`\``}function JX({alert:t,clearAlert:e,postMessage:r}){const{description:n,content:s,source:i,autoAskGeniePrompt:a}=t,o=i==="preview",l=i==="responsive",c=!!a,u=l?t.title:c?o?"Escalating preview repair to Genie":"Escalating run repair to Genie":o?"We are fixing your preview":"We are fixing your project run",d=l?n:c?o?"A temporary preview issue was detected. Genie is fixing it automatically now.":"A temporary run issue was detected. Genie is fixing it automatically now.":o?"Your site hit a temporary issue. Genie is applying fixes and will refresh the preview automatically.":"Your project hit a temporary run issue. Genie is applying fixes and will retry automatically.";return f.jsx(Si,{children:f.jsx(ar.div,{initial:{opacity:0,y:-20}
690,animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3},className:"rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 mb-2",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx(ar.div,{className:"flex-shrink-0",initial:{scale:0},animate:{scale:1},transition:{delay:.2},children:f.jsx("div",{className:"i-ph:warning-duotone text-xl text-bolt-elements-button-danger-text"})}),f.jsxs("div",{className:"ml-3 flex-1",children:[f.jsx(ar.h3,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.1},className:"text-sm font-medium text-bolt-elements-textPrimary",children:u}),f.jsxs(ar.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"mt-2 text-sm text-bolt-elements-textSecondary",children:[f.jsx("p",{children:d}),(l||!c)&&(n||s)&&f.jsxs("details",{className:"mt-4 mb-4 text-xs text-bolt-elements-textSecondary rounded bg-bolt-elements-background-depth-3 p-2",children:[f.jsx("summary",{className:"cursor-pointer select-none",children:l?"Responsive check details":"Technical details"}),n&&!l&&f.jsxs("div",{className:"mt-2",children:["Error: ",n]}),s&&f.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-words",children:s})]})]}),f.jsx(ar.div,{className:"mt-4",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},children:f.jsxs("div",{className:ue(" flex gap-2"),children:[(!c||l)&&f.jsxs("button",{onClick:()=>{l&&e(),r(a||XX(t))},className:ue("px-2 py-1.5 rounded-md text-sm font-medium","bg-bolt-elements-button-primary-background","hover:bg-bolt-elements-button-primary-backgroundHover","focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-danger-background","text-bolt-elements-button-primary-text","flex items-center gap-1.5"),children:[f.jsx("div",{className:l?"i-ph:arrows-clockwise-duotone":"i-ph:chat-circle-duotone"}),l?"Fix responsive layout":"Ask Genie"]}),f.jsx("button",{onClick:e,className:ue("px-2 py-1.5 rounded-md text-sm font-medium","bg-bolt-elements-button-secondary-background","hover:bg-bolt-elements-button-secondary-backgroundHover","focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-secondary-background","text-bolt-elements-button-secondary-text"),children:"Dismiss"}),f.jsx(h_,{params:{error_code:t.type||i||"project_run_error"},className:ue("px-2 py-1.5 rounded-md text-sm font-medium no-underline hover:no-underline","bg-bolt-elements-button-secondary-background","hover:bg-bolt-elements-button-secondary-backgroundHover","text-bolt-elements-button-secondary-text")})]})})]})]})})})}function QX({onDismiss:t,onSelectIntent:e}){return f.jsx(Si,{children:f.jsx(ar.div,{initial:{opacity:0,y:-16},animate:{opacity:1,y:0},exit:{opacity:0,y:-16},transition:{duration:.25},className:"mb-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("div",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-emerald-500/12 text-emerald-500",children:f.jsx("div",{className:"i-ph:credit-card text-lg"})}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("h3",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Stripe setup recommended"}),f.jsx("p",{className:"mt-1 text-sm text-bolt-elements-textSecondary",children:"To accept payments, connect your Stripe account."}),f.jsx("p",{className:"mt-2 text-xs text-bolt-elements-textTertiary",children:"We will still generate the payment flow now, but it will stay marked as setup required until Stripe is configured."}),f.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[f.jsxs("button",{type:"button",onClick:()=>e("connect"),className:ue("flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium","bg-bolt-elements-button-primary-background text-bolt-elements-button-primary-text","hover:bg-bolt-elements-button-primary-backgroundHover"),children:[f.jsx("div",{className:"i-ph:plugs-connected"}),"Connect Stripe"]}),f.jsxs("button",{type:"button",onClick:()=>e("manual"),className:ue("flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium","bg-bolt-elements-button-secondary-background text-bolt-elements-button-secondary-text","hover:bg-bolt-elements-button-secondary-backgroundHover"),children:[f.jsx("div",{className:"i-ph:key"}),"Add Stripe API keys manually"]}),f.jsx("button",{type:"button",onClick:t,className:ue("rounded-md px-3 py-1.5 text-sm font-medium","bg-transparent text-bolt-elements-textSecondary hover:bg-bolt-elements-item-backgroundActive hover:text-bolt-elements-textPrimary"),children:"Dismiss"})]})]})]})})})}function ZX(t){const e=t.understood.topics.join(", "),r=t.understood.requested_pages.join(", ");return[t.understood.company_name?`Company or business: ${t.understood.company_name}`:null,t.understood.location?`Location: ${t.understood.location}`:null,t.understood.business_type?`Business focus: ${t.understood.business_type}`:e?`Business focus: ${e}`:null,t.generation_brief.site_goal?`Likely goal: ${t.generation_brief.site_goal}`:t.understood.website_type?`Likely goal: ${t.understood.website_type}`:null,r?`Requested pages or sections: ${r}`:null].filter(n=>!!n)}function eJ(t){const e=t.default_plan.pages.join(", "),r=t.default_plan.features.join(", ");return[e?`Assumed pages: ${e}`:null,t.default_plan.theme?`Style direction: ${t.default_plan.theme}`:null,t.default_plan.tone?`Tone: ${t.default_plan.tone}`:null,r?`Features: ${r}`:null].filter(n=>!!n)}function tJ(t){return t.replace(/\((?:e\.g\.|for example)[^)]+\)/gi,"").replace(/\s+/g," ").trim()}function rJ(t){return t.replace(/^(?:e\.g\.|for example)\s*/i,"").replace(/[()]/g,"").replace(/\s+/g," ").trim().replace(/[.,;:]$/,"")}function nJ(t){const r=t.match(/\(([^)]+)\)/)?.[1]||"";return r?Array.from(new Set(r.split(/,|\/|\bor\b/gi).map(rJ).filter(n=>n.length>=3))).slice(0,4):[]}function sJ(t){const e=ZX(t.qualification),r=eJ(t.qualification),n=t.qualification.questions.slice(0,3).map(a=>({original:a,text:tJ(a),options:nJ(a)}));if(!(t.qualification.classification==="NEEDS_CLARIFICATION"))return null;const i="min-w-0 flex-1 break-words leading-6 [overflow-wrap:anywhere]";return f.jsxs("div",{className:"mx-auto flex min-h-0 flex-1 w-full min-w-0 max-w-chat flex-col overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-3 py-3 sm:max-h-[min(64dvh,40rem)] sm:px-4 sm:py-4 lg:max-h-[min(70dvh,44rem)] xl:max-h-[min(74dvh,48rem)]",children:[f.jsx("div",{className:"min-w-0",children:f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-bolt-elements-textTertiary sm:text-[11px] sm:tracking-[0.16em]",children:"Prompt Qualification"}),f.jsx("div",{className:"mt-1 text-sm font-semibold leading-snug text-bolt-elements-textPrimary sm:text-base",children:"A few quick details will help me generate this correctly"})]})}),f.jsxs("div",{className:"mt-4 min-h-0 flex-1 space-y-4 overflow-y-auto pr-1 text-[13px] sm:pr-2 sm:text-sm",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-[13px] font-semibold leading-6 text-bolt-elements-textPrimary sm:text-sm",children:"A) Here's what I understood"}),f.jsx("ul",{className:"mt-2 space-y-1.5 text-bolt-elements-textSecondary",children:e.length>0?e.map(a=>f.jsxs("li",{className:"flex items-start gap-2",children:[f.jsx("span",{"aria-hidden":"true",className:"pt-0.5 text-bolt-elements-textTertiary",children:"-"}),f.jsx("span",{className:i,children:a})]},a)):f.jsxs("li",{className:"flex items-start gap-2",children:[f.jsx("span",{"aria-hidden":"true",className:"pt-0.5 text-bolt-elements-textTertiary",children:"-"}),f.jsx("span",{className:i,children:"I have the general direction, but I need a few details before generating it well."})]})})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[13px] font-semibold leading-6 text-bolt-elements-textPrimary sm:text-sm",children:"B) Quick details to get it right"}),f.jsx("div",{className:"mt-2 space-y-3 text-bolt-elements-textSecondary",children:n.length>0?n.map((a,o)=>f.jsxs("div",{className:"min-w-0",children:[f.jsxs("div",{className:"break-words leading-6 [overflow-wrap:anywhere]",children:[o+1,". ",a.text]}),t.onApplySuggestion&&a.options.length>0?f.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:a.options.map(l=>f.jsx("button",{type:"button",className:"rounded-full border border-bolt-elements-borderColor bg-bolt-elements-background-depth-3 px-3 py-1 text-[11px] text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-4 sm:text-xs",onClick:()=>t.onApplySuggestion?.(l),children:l},`${a.original}-${l}`))}):null]},a.original)):f.jsx("div",{className:"break-words leading-6 [overflow-wrap:anywhere]",children:"Tell me the use case and what people should be able to do."})}),f.jsx("div",{className:"mt-2 text-[11px] leading-5 text-bolt-elements-textTertiary sm:text-xs",children:"Tap a suggestion or type a short reply in chat, and I'll turn it into a final build brief."})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[13px] font-semibold leading-6 text-bolt-elements-textPrimary sm:text-sm",children:"C) Or I can use smart defaults"}),f.jsx("ul",{className:"mt-2 space-y-1.5 text-bolt-elements-textSecondary",children:r.length>0?r.map(a=>f.jsxs("li",{className:"flex items-start gap-2",children:[f.jsx("span",{"aria-hidden":"true",className:"pt-0.5 text-bolt-elements-textTertiary",children:"-"}),f.jsx("span",{className:i,children:a})]},a)):f.jsxs("li",{className:"flex items-start gap-2",children:[f.jsx("span",{"aria-hidden":"true",className:"pt-0.5 text-bolt-elements-textTertiary",children:"-"}),f.jsx("span",{className:i,children:"I'll use a clean modern structure, a professional tone, and sensible default sections."})]})})]}),t.error?f.jsxs("div",{className:"break-words rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[13px] leading-6 text-amber-700 [overflow-wrap:anywhere] dark:text-amber-300 sm:text-sm",children:[t.error,f.jsx("div",{className:"mt-2",children:f.jsx(h_,{params:{error_code:"prompt_qualification_error"},className:"text-[13px] text-amber-700 hover:text-amber-800 dark:text-amber-300 dark:hover:text-amber-200"})})]}):null]}),f.jsx("div",{className:"mt-4 flex w-full flex-wrap items-center gap-2",children:f.jsx(En,{type:"button",onClick:t.onUseSmartDefaults,disabled:t.busy,className:"h-auto w-full px-4 py-2 text-center sm:w-auto",style:{whiteSpace:"normal"}
690,children:t.busy?"Building brief...":"Use smart defaults and build now"})})]})}function iJ({data:t}){const[e,r]=x.useState(!1),n=x.useMemo(()=>{if(!t||t.length===0)return[];const s=new Map;t.forEach(a=>{const o=s.get(a.label);o&&o.status==="complete"||s.set(a.label,a)});const i=Array.from(s.values());return i.sort((a,o)=>a.order-o.order),i},[t]);return n.length===0?f.jsx(f.Fragment,{}):f.jsx(Si,{children:f.jsx("div",{className:ue("bg-bolt-elements-background-depth-2","border border-bolt-elements-borderColor","shadow-lg rounded-lg relative w-full max-w-chat mx-auto z-prompt","p-1"),children:f.jsxs("div",{className:ue("bg-bolt-elements-item-backgroundAccent","p-1 rounded-lg text-bolt-elements-item-contentAccent","flex "),children:[f.jsx("div",{className:"flex-1",children:f.jsx(Si,{children:e?f.jsx(ar.div,{className:"actions",initial:{height:0},animate:{height:"auto"},exit:{height:"0px"},transition:{duration:.15},children:n.map((s,i)=>f.jsx(dA,{progress:s},`${s.label}:${s.order}:${i}`))}):f.jsx(dA,{progress:n.slice(-1)[0]})})}),f.jsx(ar.button,{initial:{width:0},animate:{width:"auto"},exit:{width:0},transition:{duration:.15,ease:Ds},className:" p-1 rounded-lg bg-bolt-elements-item-backgroundAccent hover:bg-bolt-elements-artifacts-backgroundHover",onClick:()=>r(s=>!s),children:f.jsx("div",{className:e?"i-ph:caret-up-bold":"i-ph:caret-down-bold"})})]})})})}const dA=({progress:t})=>f.jsxs(ar.div,{className:ue("flex text-sm gap-3"),initial:{opacity:0}
690,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},children:[f.jsx("div",{className:"flex items-center gap-1.5 ",children:f.jsx("div",{children:t.status==="in-progress"?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg"}):t.status==="complete"?f.jsx("div",{className:"i-ph:check"}):null})}),t.message]});function MN(t,e){return`${t.type} ${t.name} ${e}`.trim().toLowerCase()}function oJ(t,e){const r=MN(t,e);return r.includes("video/")||r.includes("data:video/")||/\.(mp4|m4v|mov|webm|mpeg|mpg|avi)(?:[?#]|$)/i.test(r)}function aJ(t,e){const r=MN(t,e);return r.includes("audio/")||r.includes("data:audio/")||/\.(aac|flac|m4a|mp3|ogg|opus|wav|webm)(?:[?#]|$)/i.test(r)}function lJ(t){if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.includes("#t="))return t;try{const e=new URL(t,window.location.origin);return e.hash=e.hash||"t=0.1",e.href}catch{return t}}const cJ=({previewItems:t,onRemove:e})=>{if(t.length===0)return null;const r=(n,s)=>{if(n.type.toLowerCase().startsWith("image/"))return f.jsx("img",{src:s,alt:n.name,className:"h-16 w-auto max-w-[9rem] rounded-lg object-cover"});if(oJ(n,s))return f.jsxs("div",{className:"relative h-16 w-28 overflow-hidden rounded-lg bg-black",children:[f.jsx("video",{src:lJ(s),"aria-label":n.name,className:"h-full w-full object-cover",muted:!0,playsInline:!0,preload:"metadata",crossOrigin:"anonymous",onLoadedMetadata:o=>{const l=o.currentTarget;try{Number.isFinite(l.duration)&&l.duration>0&&(l.currentTime=Math.min(.2,Math.max(0,l.duration/12)))}catch{}}}),f.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-black/10",children:f.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full bg-black/65 text-white",children:f.jsx("div",{className:"i-ph:play-fill h-3.5 w-3.5"})})})]});const a=aJ(n,s)?"i-ph:speaker-high":"i-ph:file";return f.jsx("div",{className:"flex h-16 w-28 items-center justify-center rounded-lg bg-bolt-elements-background-depth-2",children:f.jsx("div",{className:`${a} h-7 w-7 text-bolt-elements-textSecondary`})})};return f.jsx("div",{className:"mx-2 -mt-1 mb-2 flex max-h-24 flex-row items-center gap-2 overflow-x-auto rounded-lg rounded-b-none border border-b-none border-bolt-elements-borderColor bg-bolt-elements-background-depth-3 px-2 py-2",children:t.map(({file:n,index:s,imageData:i})=>f.jsx("div",{className:"relative",children:f.jsxs("div",{className:"relative",children:[r(n,i),f.jsx("button",{onClick:()=>e(s),className:"absolute -top-1 -right-1 z-10 bg-black rounded-full w-5 h-5 shadow-md hover:bg-gray-900 transition-colors flex items-center justify-center",children:f.jsx("div",{className:"i-ph:x w-3 h-3 text-gray-200"})}),f.jsx("div",{className:"absolute bottom-0 w-full h-5 flex items-center px-2 rounded-b-lg text-bolt-elements-textTertiary font-thin text-xs bg-bolt-elements-background-depth-2",children:f.jsx("span",{className:"truncate",children:n.name})})]})},`${n.name}-${n.size}-${s}`))})},uJ=({handleImageFilesSelected:t,uploadedFiles:e,imageDataList:r})=>(x.useEffect(()=>(t&&(window.__BOLT_ATTACH_IMAGE_FILES__=t,window.__BOLT_UPLOADED_FILES__=e,window.__BOLT_IMAGE_DATA_LIST__=r),()=>{delete window.__BOLT_ATTACH_IMAGE_FILES__,delete window.__BOLT_UPLOADED_FILES__,delete window.__BOLT_IMAGE_DATA_LIST__}),[t,e,r]),null),dJ=_2(.4,0,.2,1);function hJ(){return f.jsxs("svg",{"aria-hidden":"true",className:"h-4 w-4",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[f.jsx("path",{d:"M2.2 8H11.5",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"}),f.jsx("path",{d:"M8.8 4.7L12.1 8L8.8 11.3",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}function fJ(){return f.jsxs("svg",{"aria-hidden":"true",className:"h-4 w-4",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[f.jsx("circle",{cx:"8",cy:"8",r:"5.3",stroke:"currentColor",strokeWidth:"1.8"}),f.jsx("rect",{x:"5.6",y:"5.6",width:"4.8",height:"4.8",rx:"0.8",fill:"
690currentColor"})]})}const pJ=({show:t,isStreaming:e,disabled:r,onClick:n})=>{const s=e?"Stop generation":"Send message";return f.jsx(Si,{children:t?f.jsx(ar.button,{"aria-label":s,title:s,className:"absolute right-4 top-4 z-20 flex h-[34px] w-[34px] items-center justify-center rounded-md bg-accent-500 p-1 text-white shadow-sm transition-theme hover:brightness-94 disabled:cursor-not-allowed disabled:opacity-50",transition:{ease:dJ,duration:.17},initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},disabled:r,onClick:i=>{i.preventDefault(),r||n?.(i)},children:e?f.jsx(fJ,{}):f.jsx(hJ,{})}):null})};var A0={},tm={exports:{}};tm.exports;(function(t,e){var r=200,n="__lodash_hash_undefined__",s=1,i=2,a=9007199254740991,o="[object Arguments]",l="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",d="[object Date]",h="[object Error]",m="[object Function]",b="[object GeneratorFunction]",g="[object Map]",p="[object Number]",y="[object Null]",v="[object Object]",_="[object Promise]",w="[object Proxy]",C="[object RegExp]",A="[object Set]",E="[object String]",S="[object Symbol]",k="[object Undefined]",O="[object WeakMap]",T="[object ArrayBuffer]",R="[object DataView]",N="[object Float32Array]",M="[object Float64Array]",B="[object Int8Array]",U="[object Int16Array]",X="[object Int32Array]",oe="[object Uint8Array]",L="[object Uint8ClampedArray]",F="[object Uint16Array]",V="[object Uint32Array]",Z=/[\\^$.*+?()[\]{}|]/g,K=/^\[object .+?Constructor\]$/,ie=/^(?:0|[1-9]\d*)$/,se={};se[N]=se[M]=se[B]=se[U]=se[X]=se[oe]=se[L]=se[F]=se[V]=!0,se[o]=se[l]=se[T]=se[u]=se[R]=se[d]=se[h]=se[m]=se[g]=se[p]=se[v]=se[C]=se[A]=se[E]=se[O]=!1;var fe=typeof Ka=="object"&&Ka&&Ka.Object===Object&&Ka,Y=typeof self=="object"&&self&&self.Object===Object&&self,I=fe||Y||Function("return this")(),z=e&&!e.nodeType&&e,q=z&&!0&&t&&!t.nodeType&&t,ae=q&&q.exports===z,ee=ae&&fe.process,le=function(){try{return ee&&ee.binding&&ee.binding("util")}catch{}}(),ve=le&&le.isTypedArray;function ye(G,ce){for(var xe=-1,Je=G==null?0:G.length,It=0,wt=[];++xe<Je;){var Gt=G[xe];ce(Gt,xe,G)&&(wt[It++]=Gt)}return wt}function Ae(G,ce){for(var xe=-1,Je=ce.length,It=G.length;++xe<Je;)G[It+xe]=ce[xe];return G}function we(G,ce){for(var xe=-1,Je=G==null?0:G.length;++xe<Je;)if(ce(G[xe],xe,G))return!0;return!1}function pe(G,ce){for(var xe=-1,Je=Array(G);++xe<G;)Je[xe]=ce(xe);return Je}function Ye(G){return function(ce){return G(ce)}}function ft(G,ce){return G.has(ce)}function pt(G,ce){return G?.[ce]}function Lt(G){var ce=-1,xe=Array(G.size);return G.forEach(function(Je,It){xe[++ce]=[It,Je]}),xe}function nt(G,ce){return function(xe){return G(ce(xe))}}function xt(G){var ce=-1,xe=Array(G.size);return G.forEach(function(Je){xe[++ce]=Je}),xe}var ct=Array.prototype,_r=Function.prototype,ht=Object.prototype,Pe=I["__core-js_shared__"],be=_r.toString,Te=ht.hasOwnProperty,Ne=function(){var G=/[^.]+$/.exec(Pe&&Pe.keys&&Pe.keys.IE_PROTO||"");return G?"Symbol(src)_1."+G:""}(),Fe=ht.toString,Fr=RegExp("^"+be.call(Te).replace(Z,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Jr=ae?I.Buffer:void 0,Dt=I.Symbol,Yt=I.Uint8Array,Os=ht.propertyIsEnumerable,ci=ct.splice,Yn=Dt?Dt.toStringTag:void 0,$n=Object.getOwnPropertySymbols,lt=Jr?Jr.isBuffer:void 0,bs=nt(Object.keys,Object),wn=Nr(I,"DataView"),Bn=Nr(I,"Map"),an=Nr(I,"Promise"),vs=Nr(I,"Set"),ys=Nr(I,"WeakMap"),Fn=Nr(Object,"create"),Ir=Bt(wn),Wn=Bt(Bn),Hn=Bt(an),is=Bt(vs),rn=Bt(ys),Jt=Dt?Dt.prototype:void 0,xr=Jt?Jt.valueOf:void 0;function Mt(G){var ce=-1,xe=G==null?0:G.length;for(this.clear();++ce<xe;){var Je=G[ce];this.set(Je[0],Je[1])}}function Gs(){this.__data__=Fn?Fn(null):{},this.size=0}function ir(G){var ce=this.has(G)&&delete this.__data__[G];return this.size-=ce?1:0,ce}function Ai(G){var ce=this.__data__;if(Fn){var xe=ce[G];return xe===n?void 0:xe}return Te.call(ce,G)?ce[G]:void 0}function Xn(G){var ce=this.__data__;return Fn?ce[G]!==void 0:Te.call(ce,G)}function os(G,ce){var xe=this.__data__;return this.size+=this.has(G)?0:1,xe[G]=Fn&&ce===void 0?n:ce,this}Mt.prototype.clear=Gs,Mt.prototype.delete=ir,Mt.prototype.get=Ai,Mt.prototype.has=Xn,Mt.prototype.set=os;function Ur(G){var ce=-1,xe=G==null?0:G.length;for(this.clear();++ce<xe;){var Je=G[ce];this.set(Je[0],Je[1])}}function ui(){this.__data__=[],this.size=0}function nn(G){var ce=this.__data__,xe=ur(ce,G);if(xe<0)return!1;var Je=ce.length-1;return xe==Je?ce.pop():ci.call(ce,xe,1),--this.size,!0}function St(G){var ce=this.__data__,xe=ur(ce,G);return xe<0?void 0:ce[xe][1]}function Ei(G){return ur(this.__data__,G)>-1}
vendor: 2,673 bytes, line 690
690function Tn(G,ce){var xe=this.__data__,Je=ur(xe,G);return Je<0?(++this.size,xe.push([G,ce])):xe[Je][1]=ce,this}Ur.prototype.clear=ui,Ur.prototype.delete=nn,Ur.prototype.get=St,Ur.prototype.has=Ei,Ur.prototype.set=Tn;function fr(G){var ce=-1,xe=G==null?0:G.length;for(this.clear();++ce<xe;){var Je=G[ce];this.set(Je[0],Je[1])}}function Sn(){this.size=0,this.__data__={hash:new Mt,map:new(Bn||Ur),string:new Mt}}function kr(G){var ce=xs(this,G).delete(G);return this.size-=ce?1:0,ce}function Ot(G){return xs(this,G).get(G)}function Or(G){return xs(this,G).has(G)}function zr(G,ce){var xe=xs(this,G),Je=xe.size;return xe.set(G,ce),this.size+=xe.size==Je?0:1,this}fr.prototype.clear=Sn,fr.prototype.delete=kr,fr.prototype.get=Ot,fr.prototype.has=Or,fr.prototype.set=zr;function Pr(G){var ce=-1,xe=G==null?0:G.length;for(this.__data__=new fr;++ce<xe;)this.add(G[ce])}function as(G){return this.__data__.set(G,n),this}function $i(G){return this.__data__.has(G)}Pr.prototype.add=Pr.prototype.push=as,Pr.prototype.has=$i;function jt(G){var ce=this.__data__=new Ur(G);this.size=ce.size}function _s(){this.__data__=new Ur,this.size=0}function Rn(G){var ce=this.__data__,xe=ce.delete(G);return this.size=ce.size,xe}function jr(G){return this.__data__.get(G)}function wr(G){return this.__data__.has(G)}function In(G,ce){var xe=this.__data__;if(xe instanceof Ur){var Je=xe.__data__;if(!Bn||Je.length<r-1)return Je.push([G,ce]),this.size=++xe.size,this;xe=this.__data__=new fr(Je)}return xe.set(G,ce),this.size=xe.size,this}jt.prototype.clear=_s,jt.prototype.delete=Rn,jt.prototype.get=jr,jt.prototype.has=wr,jt.prototype.set=In;function Xt(G,ce){var xe=Ln(G),Je=!xe&&Nn(G),It=!xe&&!Je&&Sr(G),wt=!xe&&!Je&&!It&&ki(G),Gt=xe||Je||It||wt,Qt=Gt?pe(G.length,String):[],Nt=Qt.length;for(var pr in G)Te.call(G,pr)&&!(Gt&&(pr=="length"||It&&(pr=="offset"||pr=="parent")||wt&&(pr=="buffer"||pr=="byteLength"||pr=="byteOffset")||De(pr,Nt)))&&Qt.push(pr);return Qt}function ur(G,ce){for(var xe=G.length;xe--;)if(Lr(G[xe][0],ce))return xe;return-1}function di(G,ce,xe){var Je=ce(G);return Ln(G)?Je:Ae(Je,xe(G))}function ls(G){return G==null?G===void 0?k:y:Yn&&Yn in Object(G)?js(G):qe(G)}function ln(G){return Xs(G)&&ls(G)==o}function Gr(G,ce,xe,Je,It){return G===ce?!0:G==null||ce==null||!Xs(G)&&!Xs(ce)?G!==G&&ce!==ce:Bi(G,ce,xe,Je,Gr,It)}function Bi(G,ce,xe,Je,It,wt){var Gt=Ln(G),Qt=Ln(ce),Nt=Gt?l:te(G),pr=Qt?l:te(ce);Nt=Nt==o?v:Nt,pr=pr==o?v:pr;var Ft=Nt==v,ot=pr==v,qt=Nt==pr;if(qt&&Sr(G)){if(!Sr(ce))return!1;Gt=!0,Ft=!1}if(qt&&!Ft)return wt||(wt=new jt),Gt||ki(G)?Qr(G,ce,xe,Je,It,wt):Ar(G,ce,Nt,xe,Je,It,wt);if(!(xe&s)){var Zt=Ft&&Te.call(G,"__wrapped__"),mn=ot&&Te.call(ce,"__wrapped__");
690if(Zt||mn){var cn=Zt?G.value():G,Ss=mn?ce.value():ce;return wt||(wt=new jt),It(cn,Ss,xe,Je,wt)}}return qt?(wt||(wt=new jt),cs(G,ce,xe,Je,It,wt)):!1}function br(G){if(!Vr(G)||Ge(G))return!1;var ce=Ks(G)?Fr:K;return ce.test(Bt(G))}function Tr(G){return Xs(G)&&Ys(G.length)&&!!se[ls(G)]}function Vt(G){if(!$t(G))return bs(G);var ce=[];for(var xe in Object(G))Te.call(G,xe)&&xe!="constructor"&&ce.push(xe);return ce}function Qr(G,ce,xe,Je,It,wt){var Gt=xe&s,Qt=G.length,Nt=ce.length;if(Qt!=Nt&&!(Gt&&Nt>Qt))return!1;var pr=wt.get(G);if(pr&&wt.get(ce))return pr==ce;var Ft=-1,ot=!0,qt=xe&i?new Pr:void 0;for(wt.set(G,ce),wt.set(ce,G);++Ft<Qt;){var Zt=G[Ft],mn=ce[Ft];if(Je)var cn=Gt?Je(mn,Zt,Ft,ce,G,wt):Je(Zt,mn,Ft,G,ce,wt);if(cn!==void 0){if(cn)continue;ot=!1;break}if(qt){if(!we(ce,function(Ss,Js){if(!ft(qt,Js)&&(Zt===Ss||It(Zt,Ss,xe,Je,wt)))return qt.push(Js)})){ot=!1;break}}else if(!(Zt===mn||It(Zt,mn,xe,Je,wt))){ot=!1;break}}return wt.delete(G),wt.delete(ce),ot}function Ar(G,ce,xe,Je,It,wt,Gt){switch(xe){case R:if(G.byteLength!=ce.byteLength||G.byteOffset!=ce.byteOffset)return!1;G=G.buffer,ce=ce.buffer;case T:return!(G.byteLength!=ce.byteLength||!wt(new Yt(G),new Yt(ce)));case u:case d:case p:return Lr(+G,+ce);case h:return G.name==ce.name&&G.message==ce.message;case C:case E:return G==ce+"";case g:var Qt=Lt;case A:var Nt=Je&s;if(Qt||(Qt=xt),G.size!=ce.size&&!Nt)return!1;var pr=Gt.get(G);if(pr)return pr==ce;Je|=i,Gt.set(G,ce);var Ft=Qr(Qt(G),Qt(ce),Je,It,wt,Gt);return Gt.delete(G),Ft;case S:if(xr)return xr.call(G)==xr.call(ce)}return!1}function cs(G,ce,xe,Je,It,wt){var Gt=xe&s,Qt=Ut(G),Nt=Qt.length,pr=Ut(ce),Ft=pr.length;if(Nt!=Ft&&!Gt)return!1;for(var ot=Nt;ot--;){var qt=Qt[ot];if(!(Gt?qt in ce:Te.call(ce,qt)))return!1}var Zt=wt.get(G);if(Zt&&wt.get(ce))return Zt==ce;var mn=!0;wt.set(G,ce),wt.set(ce,G);for(var cn=Gt;++ot<Nt;){qt=Qt[ot];var Ss=G[qt],Js=ce[qt];if(Je)var ro=Gt?Je(Js,Ss,qt,ce,G,wt):Je(Ss,Js,qt,G,ce,wt);if(!(ro===void 0?Ss===Js||It(Ss,Js,xe,Je,wt):ro)){mn=!1;break}cn||(cn=qt=="constructor")}if(mn&&!cn){var Wi=G.constructor,rr=ce.constructor;Wi!=rr&&"constructor"in G&&"constructor"in ce&&!(typeof Wi=="function"&&Wi instanceof Wi&&typeof rr=="function"&&rr instanceof rr)&&(mn=!1)}return wt.delete(G),wt.delete(ce),mn}function Ut(G){return di(G,ws,pn)}function xs(G,ce){var xe=G.__data__;return je(ce)?xe[typeof ce=="string"?"string":"hash"]:xe.map}function Nr(G,ce){var xe=pt(G,ce);return br(xe)?xe:void 0}function js(G){var ce=Te.call(G,Yn),xe=G[Yn];try{G[Yn]=void 0;var Je=!0}catch{}var It=Fe.call(G);return Je&&(ce?G[Yn]=xe:delete G[Yn]),It}var pn=$n?function(G){return G==null?[]:(G=Object(G),ye($n(G),function(ce){return Os.call(G,ce)}))}:Dn,te=ls;(wn&&te(new wn(new ArrayBuffer(1)))!=R||Bn&&te(new Bn)!=g||an&&te(an.resolve())!=_||vs&&te(new vs)!=A||ys&&te(new ys)!=O)&&(te=function(G){var ce=ls(G),xe=ce==v?G.constructor:void 0,Je=xe?Bt(xe):"";if(Je)switch(Je){case Ir:return R;case Wn:return g;case Hn:return _;case is:return A;case rn:return O}return ce});function De(G,ce){return ce=ce??a,!!ce&&(typeof G=="number"||ie.test(G))&&G>-1&&G%1==0&&G<ce}function je(G){var ce=typeof G;return ce=="string"||ce=="number"||ce=="symbol"||ce=="boolean"?G!=="__proto__":G===null}function Ge(G){return!!Ne&&Ne in G}function $t(G){var ce=G&&G.constructor,xe=typeof ce=="function"&&ce.prototype||ht;return G===xe}function qe(G){return Fe.call(G)}function Bt(G){if(G!=null){try{return be.call(G)}catch{}try{return G+""}catch{}}return""}function Lr(G,ce){return G===ce||G!==G&&ce!==ce}var Nn=ln(function(){return arguments}())?ln:function(G){return Xs(G)&&Te.call(G,"callee")&&!Os.call(G,"callee")},Ln=Array.isArray;function qs(G){return G!=null&&Ys(G.length)&&!Ks(G)}var Sr=lt||Fi;function or(G,ce){return Gr(G,ce)}function Ks(G){if(!Vr(G))return!1;var ce=ls(G);return ce==m||ce==b||ce==c||ce==w}function Ys(G){return typeof G=="number"&&G>-1&&G%1==0&&G<=a}function Vr(G){var ce=typeof G;return G!=null&&(ce=="object"||ce=="function")}function Xs(G){return G!=null&&typeof G=="object"}var ki=ve?Ye(ve):Tr;function ws(G){return qs(G)?Xt(G):Vt(G)}function Dn(){return[]}function Fi(){return!1}t.exports=or})(tm,tm.exports);var mJ=tm.exports,ON={exports:{}};(function(t,e){var r=function(){var n=function(C,A){var E=236,S=17,k=C,O=i[A],T=null,R=0,N=null,M=[],B={},U=function(I,z){R=k*4+17,T=function(q){for(var ae=new Array(q),ee=0;ee<q;ee+=1){ae[ee]=new Array(q);for(var le=0;le<q;le+=1)ae[ee][le]=null}return ae}(R),X(0,0),X(R-7,0),X(0,R-7),F(),L(),Z(I,z),k>=7&&V(I),N==null&&(N=se(k,O,M)),K(N,z)},X=function(I,z){for(var q=-1;q<=7;q+=1)if(!(I+q<=-1||R<=I+q))for(var ae=-1;ae<=7;ae+=1)z+ae<=-1||R<=z+ae||(0<=q&&q<=6&&(ae==0||ae==6)||0<=ae&&ae<=6&&(q==0||q==6)||2<=q&&q<=4&&2<=ae&&ae<=4?T[I+q][z+ae]=!0:T[I+q][z+ae]=!1)},oe=function(){for(var I=0,z=0,q=0;q<8;q+=1){U(!0,q);var ae=o.getLostPoint(B);(q==0||I>ae)&&(I=ae,z=q)}return z},L=function(){for(var I=8;I<R-8;I+=1)T[I][6]==null&&(T[I][6]=I%2==0);for(var z=8;z<R-8;z+=1)T[6][z]==null&&(T[6][z]=z%2==0)},F=function(){for(var I=o.getPatternPosition(k),z=0;z<I.length;z+=1)for(var q=0;q<I.length;q+=1){var ae=I[z],ee=I[q];
690if(T[ae][ee]==null)for(var le=-2;le<=2;le+=1)for(var ve=-2;ve<=2;ve+=1)le==-2||le==2||ve==-2||ve==2||le==0&&ve==0?T[ae+le][ee+ve]=!0:T[ae+le][ee+ve]=!1}},V=function(I){for(var z=o.getBCHTypeNumber(k),q=0;q<18;q+=1){var ae=!I&&(z>>q&1)==1;T[Math.floor(q/3)][q%3+R-8-3]=ae}for(var q=0;q<18;q+=1){var ae=!I&&(z>>q&1)==1;T[q%3+R-8-3][Math.floor(q/3)]=ae}},Z=function(I,z){for(var q=O<<3|z,ae=o.getBCHTypeInfo(q),ee=0;ee<15;ee+=1){var le=!I&&(ae>>ee&1)==1;ee<6?T[ee][8]=le:ee<8?T[ee+1][8]=le:T[R-15+ee][8]=le}for(var ee=0;ee<15;ee+=1){var le=!I&&(ae>>ee&1)==1;ee<8?T[8][R-ee-1]=le:ee<9?T[8][15-ee-1+1]=le:T[8][15-ee-1]=le}T[R-8][8]=!I},K=function(I,z){for(var q=-1,ae=R-1,ee=7,le=0,ve=o.getMaskFunction(z),ye=R-1;ye>0;ye-=2)for(ye==6&&(ye-=1);;){for(var Ae=0;Ae<2;Ae+=1)if(T[ae][ye-Ae]==null){var we=!1;le<I.length&&(we=(I[le]>>>ee&1)==1);var pe=ve(ae,ye-Ae);pe&&(we=!we),T[ae][ye-Ae]=we,ee-=1,ee==-1&&(le+=1,ee=7)}if(ae+=q,ae<0||R<=ae){ae-=q,q=-q;break}}},ie=function(I,z){for(var q=0,ae=0,ee=0,le=new Array(z.length),ve=new Array(z.length),ye=0;ye<z.length;ye+=1){var Ae=z[ye].dataCount,we=z[ye].totalCount-Ae;ae=Math.max(ae,Ae),ee=Math.max(ee,we),le[ye]=new Array(Ae);for(var pe=0;pe<le[ye].length;pe+=1)le[ye][pe]=255&I.getBuffer()[pe+q];q+=Ae;var Ye=o.getErrorCorrectPolynomial(we),ft=c(le[ye],Ye.getLength()-1),pt=ft.mod(Ye);ve[ye]=new Array(Ye.getLength()-1);for(var pe=0;pe<ve[ye].length;pe+=1){var Lt=pe+pt.getLength()-ve[ye].length;ve[ye][pe]=Lt>=0?pt.getAt(Lt):0}}for(var nt=0,pe=0;pe<z.length;pe+=1)nt+=z[pe].totalCount;for(var xt=new Array(nt),ct=0,pe=0;pe<ae;pe+=1)for(var ye=0;ye<z.length;ye+=1)pe<le[ye].length&&(xt[ct]=le[ye][pe],ct+=1);for(var pe=0;pe<ee;pe+=1)for(var ye=0;ye<z.length;ye+=1)pe<ve[ye].length&&(xt[ct]=ve[ye][pe],ct+=1);return xt},se=function(I,z,q){for(var ae=u.getRSBlocks(I,z),ee=d(),le=0;le<q.length;le+=1){var ve=q[le];ee.put(ve.getMode(),4),ee.put(ve.getLength(),o.getLengthInBits(ve.getMode(),I)),ve.write(ee)}for(var ye=0,le=0;le<ae.length;le+=1)ye+=ae[le].dataCount;if(ee.getLengthInBits()>ye*8)throw"code length overflow. ("+ee.getLengthInBits()+">"+ye*8+")";for(ee.getLengthInBits()+4<=ye*8&&ee.put(0,4);ee.getLengthInBits()%8!=0;)ee.putBit(!1);for(;!(ee.getLengthInBits()>=ye*8||(ee.put(E,8),ee.getLengthInBits()>=ye*8));)ee.put(S,8);return ie(ee,ae)};B.addData=function(I,z){z=z||"Byte";var q=null;switch(z){case"Numeric":q=h(I);break;case"Alphanumeric":q=m(I);break;case"Byte":q=b(I);break;case"Kanji":q=g(I);break;default:throw"mode:"+z}M.push(q),N=null},B.isDark=function(I,z){if(I<0||R<=I||z<0||R<=z)throw I+","+z;return T[I][z]},B.getModuleCount=function(){return R},B.make=function(){if(k<1){for(var I=1;I<40;I++){for(var z=u.getRSBlocks(I,O),q=d(),ae=0;ae<M.length;ae++){var ee=M[ae];q.put(ee.getMode(),4),q.put(ee.getLength(),o.getLengthInBits(ee.getMode(),I)),ee.write(q)}for(var le=0,ae=0;ae<z.length;ae++)le+=z[ae].dataCount;if(q.getLengthInBits()<=le*8)break}k=I}U(!1,oe())},B.createTableTag=function(I,z){I=I||2,z=typeof z>"u"?I*4:z;var q="";q+='<table style="',q+=" border-width: 0px; border-style: none;",q+=" border-collapse: collapse;",q+=" padding: 0px; margin: "+z+"px;",q+='">',q+="<tbody>";for(var ae=0;ae<B.getModuleCount();ae+=1){q+="<tr>";for(var ee=0;ee<B.getModuleCount();ee+=1)q+='<td style="',q+=" border-width: 0px; border-style: none;",q+=" border-collapse: collapse;",q+=" padding: 0px; margin: 0px;",q+=" width: "+I+"px;",q+=" height: "+I+"px;",q+=" background-color: ",q+=B.isDark(ae,ee)?"#000000":"#ffffff",q+=";",q+='"/>';q+="</tr>"}return q+="</tbody>",q+="</table>",q},B.createSvgTag=function(I,z,q,ae){var ee={};typeof arguments[0]=="object"&&(ee=arguments[0],I=ee.cellSize,z=ee.margin,q=ee.alt,ae=ee.title),I=I||2,z=typeof z>"u"?I*4:z,q=typeof q=="string"?{text:q}:q||{},q.text=q.text||null,q.id=q.text?q.id||"qrcode-description":null,ae=typeof ae=="string"?{text:ae}:ae||{},ae.text=ae.text||null,ae.id=ae.text?ae.id||"qrcode-title":null;var le=B.getModuleCount()*I+z*2,ve,ye,Ae,we,pe="",Ye;for(Ye="l"+I+",0 0,"+I+" -"+I+",0 0,-"+I+"z ",pe+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',pe+=ee.scalable?"":' width="'+le+'px" height="'+le+'px"',pe+=' viewB
690ox="0 0 '+le+" "+le+'" ',pe+=' preserveAspectRatio="xMinYMin meet"',pe+=ae.text||q.text?' role="img" aria-labelledby="'+fe([ae.id,q.id].join(" ").trim())+'"':"",pe+=">",pe+=ae.text?'<title id="'+fe(ae.id)+'">'+fe(ae.text)+"</title>":"",pe+=q.text?'<description id="'+fe(q.id)+'">'+fe(q.text)+"</description>":"",pe+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',pe+='<path d="',Ae=0;Ae<B.getModuleCount();Ae+=1)for(we=Ae*I+z,ve=0;ve<B.getModuleCount();ve+=1)B.isDark(Ae,ve)&&(ye=ve*I+z,pe+="M"+ye+","+we+Ye);return pe+='" stroke="transparent" fill="black"/>',pe+="</svg>",pe},B.createDataURL=function(I,z){I=I||2,z=typeof z>"u"?I*4:z;var q=B.getModuleCount()*I+z*2,ae=z,ee=q-z;return w(q,q,function(le,ve){if(ae<=le&&le<ee&&ae<=ve&&ve<ee){var ye=Math.floor((le-ae)/I),Ae=Math.floor((ve-ae)/I);return B.isDark(Ae,ye)?0:1}else return 1})},B.createImgTag=function(I,z,q){I=I||2,z=typeof z>"u"?I*4:z;var ae=B.getModuleCount()*I+z*2,ee="";return ee+="<img",ee+=' src="',ee+=B.createDataURL(I,z),ee+='"',ee+=' width="',ee+=ae,ee+='"',ee+=' height="',ee+=ae,ee+='"',q&&(ee+=' alt="',ee+=fe(q),ee+='"'),ee+="/>",ee};var fe=function(I){for(var z="",q=0;q<I.length;q+=1){var ae=I.charAt(q);switch(ae){case"<":z+="<";break;case">":z+=">";break;case"&":z+="&";break;case'"':z+=""";break;default:z+=ae;break}}return z},Y=function(I){var z=1;I=typeof I>"u"?z*2:I;var q=B.getModuleCount()*z+I*2,ae=I,ee=q-I,le,ve,ye,Ae,we,pe={"ââ":"â","â ":"â"," â":"â"," ":" "},Ye={"ââ":"â","â ":"â"," â":" "," ":" "},ft="";for(le=0;le<q;le+=2){for(ye=Math.floor((le-ae)/z),Ae=Math.floor((le+1-ae)/z),ve=0;ve<q;ve+=1)we="â",ae<=ve&&ve<ee&&ae<=le&&le<ee&&B.isDark(ye,Math.floor((ve-ae)/z))&&(we=" "),ae<=ve&&ve<ee&&ae<=le+1&&le+1<ee&&B.isDark(Ae,Math.floor((ve-ae)/z))?we+=" ":we+="â",ft+=I<1&&le+1>=ee?Ye[we]:pe[we];ft+=` 691`}return q%2&&I>0?ft.substring(0,ft.length-q-1)+Array(q+1).join("â"):ft.substring(0,ft.length-1)};return B.createASCII=function(I,z){if(I=I||1,I<2)return Y(z);I-=1,z=typeof z>"u"?I*2:z;var q=B.getModuleCount()*I+z*2,ae=z,ee=q-z,le,ve,ye,Ae,we=Array(I+1).join("ââ"),pe=Array(I+1).join(" "),Ye="",ft="";for(le=0;le<q;le+=1){for(ye=Math.floor((le-ae)/I),ft="",ve=0;ve<q;ve+=1)Ae=1,ae<=ve&&ve<ee&&ae<=le&&le<ee&&B.isDark(ye,Math.floor((ve-ae)/I))&&(Ae=0),ft+=Ae?we:pe;for(ye=0;ye<I;ye+=1)Ye+=ft+` 692`}return Ye.substring(0,Ye.length-1)},B.renderTo2dContext=function(I,z){z=z||2;for(var q=B.getModuleCount(),ae=0;ae<q;ae++)for(var ee=0;ee<q;ee++)I.fillStyle=B.isDark(ae,ee)?"black":"white",I.fillRect(ae*z,ee*z,z,z)},B};n.stringToBytesFuncs={default:function(C){for(var A=[],E=0;E<C.length;E+=1){var S=C.charCodeAt(E);A.push(S&255)}return A}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(C,A){var E=function(){for(var k=v(C),O=function(){var L=k.read();if(L==-1)throw"eof";return L},T=0,R={};;){var N=k.read();if(N==-1)break;var M=O(),B=O(),U=O(),X=String.fromCharCode(N<<8|M),oe=B<<8|U;R[X]=oe,T+=1}if(T!=A)throw T+" != "+A;return R}(),S=63;return function(k){for(var O=[],T=0;T<k.length;T+=1){var R=k.charCodeAt(T);if(R<128)O.push(R);else{var N=E[k.charAt(T)];typeof N=="number"?(N&255)==N?O.push(N):(O.push(N>>>8),O.push(N&255)):O.push(S)}}return O}};var s={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},i={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=function(){var C=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,E=7973,S=21522,k={},O=function(T){for(var R=0;T!=0;)R+=1,T>>>=1;return R};return k.getBCHTypeInfo=function(T){for(var R=T<<10;O(R)-O(A)>=0;)R^=A<<O(R)-O(A);return(T<<10|R)^S},k.getBCHTypeNumber=function(T){for(var R=T<<12;O(R)-O(E)>=0;)R^=E<<O(R)-O(E);return T<<12|R},k.getPatternPosition=function(T){return C[T-1]},k.getMaskFunction=function(T){switch(T){case a.PATTERN000:return function(R,N){return(R+N)%2==0};case a.PATTERN001:return function(R,N){return R%2==0};case a.PATTERN010:return function(R,N){return N%3==0};case a.PATTERN011:return function(R,N){return(R+N)%3==0};case a.PATTERN100:return function(R,N){return(Math.floor(R/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(R,N){return R*N%2+R*N%3==0};case a.PATTERN110:return function(R,N){return(R*N%2+R*N%3)%2==0};case a.PATTERN111:return function(R,N){return(R*N%3+(R+N)%2)%2==0};default:throw"bad maskPattern:"+T}},k.getErrorCorrectPolynomial=function(T){for(var R=c([1],0),N=0;N<T;N+=1)R=R.multiply(c([1,l.gexp(N)],0));return R},k.getLengthInBits=function(T,R){if(1<=R&&R<10)switch(T){case s.MODE_NUMBER:return 10;case s.MODE_ALPHA_NUM:return 9;
692case s.MODE_8BIT_BYTE:return 8;case s.MODE_KANJI:return 8;default:throw"mode:"+T}else if(R<27)switch(T){case s.MODE_NUMBER:return 12;case s.MODE_ALPHA_NUM:return 11;case s.MODE_8BIT_BYTE:return 16;case s.MODE_KANJI:return 10;default:throw"mode:"+T}else if(R<41)switch(T){case s.MODE_NUMBER:return 14;case s.MODE_ALPHA_NUM:return 13;case s.MODE_8BIT_BYTE:return 16;case s.MODE_KANJI:return 12;default:throw"mode:"+T}else throw"type:"+R},k.getLostPoint=function(T){for(var R=T.getModuleCount(),N=0,M=0;M<R;M+=1)for(var B=0;B<R;B+=1){for(var U=0,X=T.isDark(M,B),oe=-1;oe<=1;oe+=1)if(!(M+oe<0||R<=M+oe))for(var L=-1;L<=1;L+=1)B+L<0||R<=B+L||oe==0&&L==0||X==T.isDark(M+oe,B+L)&&(U+=1);U>5&&(N+=3+U-5)}for(var M=0;M<R-1;M+=1)for(var B=0;B<R-1;B+=1){var F=0;T.isDark(M,B)&&(F+=1),T.isDark(M+1,B)&&(F+=1),T.isDark(M,B+1)&&(F+=1),T.isDark(M+1,B+1)&&(F+=1),(F==0||F==4)&&(N+=3)}for(var M=0;M<R;M+=1)for(var B=0;B<R-6;B+=1)T.isDark(M,B)&&!T.isDark(M,B+1)&&T.isDark(M,B+2)&&T.isDark(M,B+3)&&T.isDark(M,B+4)&&!T.isDark(M,B+5)&&T.isDark(M,B+6)&&(N+=40);for(var B=0;B<R;B+=1)for(var M=0;M<R-6;M+=1)T.isDark(M,B)&&!T.isDark(M+1,B)&&T.isDark(M+2,B)&&T.isDark(M+3,B)&&T.isDark(M+4,B)&&!T.isDark(M+5,B)&&T.isDark(M+6,B)&&(N+=40);for(var V=0,B=0;B<R;B+=1)for(var M=0;M<R;M+=1)T.isDark(M,B)&&(V+=1);var Z=Math.abs(100*V/R/R-50)/5;return N+=Z*10,N},k}(),l=function(){for(var C=new Array(256),A=new Array(256),E=0;E<8;E+=1)C[E]=1<<E;for(var E=8;E<256;E+=1)C[E]=C[E-4]^C[E-5]^C[E-6]^C[E-8];for(var E=0;E<255;E+=1)A[C[E]]=E;var S={};return S.glog=function(k){if(k<1)throw"glog("+k+")";return A[k]},S.gexp=function(k){for(;k<0;)k+=255;for(;k>=256;)k-=255;return C[k]},S}();function c(C,A){if(typeof C.length>"u")throw C.length+"/"+A;var E=function(){for(var k=0;k<C.length&&C[k]==0;)k+=1;for(var O=new Array(C.length-k+A),T=0;T<C.length-k;T+=1)O[T]=C[T+k];return O}(),S={};return S.getAt=function(k){return E[k]},S.getLength=function(){return E.length},S.multiply=function(k){for(var O=new Array(S.getLength()+k.getLength()-1),T=0;T<S.getLength();T+=1)for(var R=0;R<k.getLength();R+=1)O[T+R]^=l.gexp(l.glog(S.getAt(T))+l.glog(k.getAt(R)));return c(O,0)},S.mod=function(k){if(S.getLength()-k.getLength()<0)return S;for(var O=l.glog(S.getAt(0))-l.glog(k.getAt(0)),T=new Array(S.getLength()),R=0;R<S.getLength();R+=1)T[R]=S.getAt(R);for(var R=0;R<k.getLength();R+=1)T[R]^=l.gexp(l.glog(k.getAt(R))+O);return c(T,0).mod(k)},S}var u=function(){var C=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],A=function(k,O){var T={};return T.totalCount=k,T.dataCount=O,T},E={},S=function(k,O){switch(O){case i.L:return C[(k-1)*4+0];case i.M:return C[(k-1)*4+1];case i.Q:return C[(k-1)*4+2];case i.H:return C[(k-1)*4+3];default:return}};return E.getRSBlocks=function(k,O){var T=S(k,O);if(typeof T>"u")throw"bad rs block @ typeNumber:"+k+"/errorCorrectionLevel:"+O;for(var R=T.length/3,N=[],M=0;M<R;M+=1)for(var B=T[M*3+0],U=T[M*3+1],X=T[M*3+2],oe=0;oe<B;oe+=1)N.push(A(U,X));return N},E}(),d=function(){var C=[],A=0,E={};return E.getBuffer=function(){return C},E.getAt=function(S){var k=Math.floor(S/8);return(C[k]>>>7-S%8&1)==1},E.put=function(S,k){for(var O=0;O<k;O+=1)E.putBit((S>>>k-O-1&1)==1)},E.getLengthInBits=function(){return A},E.putBit=function(S){var k=Math.floor(A/8);C.length<=k&&C.push(0),S&&(C[k]|=128>>>A%8),A+=1},E},h=function(C){var A=s.MODE_NUMBER,E=C,S={};S.getMode=function(){return A},S.getLength=function(T){return E.length},S.write=function(T){for(var R=E,N=0;N+2<R.length;)T.put(k(R.substring(N,N+3)),10),N+=3;N<R.length&&(R.length-N==1?T.put(k(R.substring(N,N+1)),4):R.length-N==2&&T.put(k(R.substring(N,N+2)),7))};var k=function(T){for(var R=0,N=0;N<T.length;N+=1)R=R*10+O(T.charAt(N));return R},O=function(T){if("0"<=T&&T<="9")return T.charCodeAt(0)-48;throw"illegal char :"+T};return S},m=function(C){var A=s.MODE_ALPHA_NUM,E=C,S={};S.getMode=function(){return A},S.getLength=function(O){return E.length},S.write=function(O){for(var T=E,R=0;R+1<T.length;)O.put(k(T.charAt(R))*45+k(T.charAt(R+1)),11),R+=2;R<T.length&&O.put(k(T.charAt(R)),6)};var k=function(O){if("0"<=O&&O<="9")return O.charCodeAt(0)-48;if("A"<=O&&O<="Z")return O.charCodeAt(0)-65+10;switch(O){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+O}};return S},b=function(C){var A=s.MODE_8BIT_BYTE,E=n.stringToBytes(C),S={};return S.getMode=function(){return A},S.getLength=function(k){return E.length},S.write=function(k){for(var O=0;O<E.length;O+=1)k.put(E[O],8)},S},g=function(C){var A=s.MODE_KANJI,E=n.stringToBytesFuncs.SJIS;if(!E)throw"sjis not supported.";(function(O,T){var R=E(O);if(R.length!=2||(R[0]<<8|R[1])!=T)throw"sjis not supported."})("å",38726);var S=E(C),k={};return k.getMode=function(){return A},k.getLength=function(O){return~~(S.length/2)},k.write=function(O){for(var T=S,R=0;R+1<T.length;){var N=(255&T[R])<<8|255&T[R+1];if(33088<=N&&N<=40956)N-=33088;else if(57408<=N&&N<=60351)N-=49472;else throw"illegal char at "+(R+1)+"/"+N;N=(N>
692>>8&255)*192+(N&255),O.put(N,13),R+=2}if(R<T.length)throw"illegal char at "+(R+1)},k},p=function(){var C=[],A={};return A.writeByte=function(E){C.push(E&255)},A.writeShort=function(E){A.writeByte(E),A.writeByte(E>>>8)},A.writeBytes=function(E,S,k){S=S||0,k=k||E.length;for(var O=0;O<k;O+=1)A.writeByte(E[O+S])},A.writeString=function(E){for(var S=0;S<E.length;S+=1)A.writeByte(E.charCodeAt(S))},A.toByteArray=function(){return C},A.toString=function(){var E="";E+="[";for(var S=0;S<C.length;S+=1)S>0&&(E+=","),E+=C[S];return E+="]",E},A},y=function(){var C=0,A=0,E=0,S="",k={},O=function(R){S+=String.fromCharCode(T(R&63))},T=function(R){if(!(R<0)){if(R<26)return 65+R;if(R<52)return 97+(R-26);if(R<62)return 48+(R-52);if(R==62)return 43;if(R==63)return 47}throw"n:"+R};return k.writeByte=function(R){for(C=C<<8|R&255,A+=8,E+=1;A>=6;)O(C>>>A-6),A-=6},k.flush=function(){if(A>0&&(O(C<<6-A),C=0,A=0),E%3!=0)for(var R=3-E%3,N=0;N<R;N+=1)S+="="},k.toString=function(){return S},k},v=function(C){var A=C,E=0,S=0,k=0,O={};O.read=function(){for(;k<8;){if(E>=A.length){if(k==0)return-1;throw"unexpected end of file./"+k}var R=A.charAt(E);if(E+=1,R=="=")return k=0,-1;if(R.match(/^\s$/))continue;S=S<<6|T(R.charCodeAt(0)),k+=6}var N=S>>>k-8&255;return k-=8,N};var T=function(R){if(65<=R&&R<=90)return R-65;if(97<=R&&R<=122)return R-97+26;if(48<=R&&R<=57)return R-48+52;if(R==43)return 62;if(R==47)return 63;throw"c:"+R};return O},_=function(C,A){var E=C,S=A,k=new Array(C*A),O={};O.setPixel=function(M,B,U){k[B*E+M]=U},O.write=function(M){M.writeString("GIF87a"),M.writeShort(E),M.writeShort(S),M.writeByte(128),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(255),M.writeByte(255),M.writeByte(255),M.writeString(","),M.writeShort(0),M.writeShort(0),M.writeShort(E),M.writeShort(S),M.writeByte(0);var B=2,U=R(B);M.writeByte(B);for(var X=0;U.length-X>255;)M.writeByte(255),M.writeBytes(U,X,255),X+=255;M.writeByte(U.length-X),M.writeBytes(U,X,U.length-X),M.writeByte(0),M.writeString(";")};var T=function(M){var B=M,U=0,X=0,oe={};return oe.write=function(L,F){if(L>>>F)throw"length over";for(;U+F>=8;)B.writeByte(255&(L<<U|X)),F-=8-U,L>>>=8-U,X=0,U=0;X=L<<U|X,U=U+F},oe.flush=function(){U>0&&B.writeByte(X)},oe},R=function(M){for(var B=1<<M,U=(1<<M)+1,X=M+1,oe=N(),L=0;L<B;L+=1)oe.add(String.fromCharCode(L));oe.add(String.fromCharCode(B)),oe.add(String.fromCharCode(U));var F=p(),V=T(F);V.write(B,X);var Z=0,K=String.fromCharCode(k[Z]);for(Z+=1;Z<k.length;){var ie=String.fromCharCode(k[Z]);Z+=1,oe.contains(K+ie)?K=K+ie:(V.write(oe.indexOf(K),X),oe.size()<4095&&(oe.size()==1<<X&&(X+=1),oe.add(K+ie)),K=ie)}return V.write(oe.indexOf(K),X),V.write(U,X),V.flush(),F.toByteArray()},N=function(){var M={},B=0,U={};return U.add=function(X){if(U.contains(X))throw"dup key:"+X;M[X]=B,B+=1},U.size=function(){return B},U.indexOf=function(X){return M[X]},U.contains=function(X){return typeof M[X]<"u"},U};return O},w=function(C,A,E){for(var S=_(C,A),k=0;k<A;k+=1)for(var O=0;O<C;O+=1)S.setPixel(O,k,E(O,k));var T=p();S.write(T);for(var R=y(),N=T.toByteArray(),M=0;M<N.length;M+=1)R.writeByte(N[M]);return R.flush(),"data:image/gif;base64,"+R};return n}();(function(){r.stringToBytesFuncs["UTF-8"]=function(n){function s(i){for(var a=[],o=0;o<i.length;o++){var l=i.charCodeAt(o);l<128?a.push(l):l<2048?a.push(192|l>>6,128|l&63):l<55296||l>=57344?a.push(224|l>>12,128|l>>6&63,128|l&63):(o++,l=65536+((l&1023)<<10|i.charCodeAt(o)&1023),a.push(240|l>>18,128|l>>12&63,128|l>>6&63,128|l&63))}return a}return s(n)}})(),function(n){t.exports=n()}(function(){return r})})(ON);var gJ=ON.exports,bJ=Ka&&Ka.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(n[i]=s[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Wy=Ka&&Ka.__assign||function(){return Wy=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=e[s])}return t},Wy.apply(this,arguments)};Object.defineProperty(A0,"__esModule",{value:!0});var jN=A0.QRCode=void 0,vJ=mJ,yJ=gJ,Ub=x,_J=function(t){bJ(e,t);function e(r){var n=t.call(this,r)||this;return n.canvasRef=Ub.createRef(),n}return e.prototype.download=function(r,n){if(this.canvasRef.current){var s=void 0;switch(r){case"jpg":s="image/jpeg";break;case"webp":s="image/webp";break;case"png":default:s="image/png";break}var i=this.canvasRef.current.toDataURL(s,1),a=document.createElement("a");a.download=n??"react-qrcode-logo",a.href=i,a.click()}},e.prototype.utf16to8=function(r){var n="",s,i,a=r.length;for(s=0;s<a;s++)i=r.charCodeAt(s),i>=1&&i<=127?n+=r.charAt(s):i>2047?(n+=String.fromCharCode(224|i>>12&15),n+=String.fromCharCode(128|i>>6&63),n+=String.fromCharCode(128|i>>0&63)):(n+=String.fromCharCode(192|i>>6&31),n+=String.fromCharCode(128|i>>0&63));return n},e.prototype.drawRoundedSquare=function(r,n,s,i,a,o,l,c){c.lineWidth=r,c.fillStyle=a,c.strokeStyle=a,s+=r/2,n+=r/2,i-=r,Array.isArray(o)||(o=[o,o,o,o]),o=o.map(function(b){return b=Math.min(b,i/2),b<0?0:b});var u=o[0]||0,d=o[1]||0,h=o[2]||0,m=o[3]||0;c.beginPath(),c.moveTo(n+u,s),c.lineTo(n+i-d,s),d&&c.quadraticCurveTo(n+i,s,n+i,s+d),c.lineTo(n+i,s+i-h),h&&c.quadraticCurveTo(n+i,s+i,n+i-h,s+i),c.lineTo(n+m,s+i),m&&c.quadraticCurveTo(n,s+i,n,s+i-m),c.lineTo(n,s+u),u&&c.quadraticCurveTo(n,s,n+u,s),c.closePath(),c.stroke(),l&&c.fill()},e.prototype.drawPositioningPattern=function(r,n,s,i,a,o,l){l===void 0&&(l=[0,0,0,0]);var c=Math.ceil(n),u,d;typeof l!="number"&&!Array.isArray(l)?(u=l.outer||0,d=l.inner||0):(u=l,d=u);var h,m;typeof o!="string"?(h=o.outer,m=o.inner):(h=o,m=o);var b=i*n+s,g=a*n+s,p=n*7;this.drawRoundedSquare(c,g,b,p,h,u,!1,r),p=n*3,b+=n*2,g+=n*2,this.drawRoundedSquare(c,g,b,p,m,d,!0,r)},e.prototype.isInPositioninZone=function(r,n,s){return s.some(function(i){return n>=i.row&&n<=i.row+7&&r>=i.col&&r<=i.col+7})},e.prototype.transformPixelLengthIntoNumberOfCells=function(r,n){return r/n},e.prototype.isCoordinateInImage=function(r,n,s,i,a,o,l,c){if(c){var u=2,d=this.transformPixelLengthIntoNumberOfCells(a,l),h=this.transformPixelLengthIntoNumberOfCells(o,l),m=this.transformPixelLengthIntoNumberOfCells(s,l)-1,b=this.transformPixelLengthIntoNumberOfCells(i,l)-1;return n>=d-u&&n<=d+m+u&&r>=h-u&&r<=h+b+u}else return!1},e.prototype.shouldComponentUpdate=function(r){return!vJ(this.props,r)},e.prototype.componentDidMount=function(){this.update()},e.prototype.componentDidUpdate=function(){this.update()},e.prototype.update=function(){var r,n=this.props,s=n.value,i=n.ecLevel,a=n.enableCORS,o=n.bgColor,l=n.fgColor,c=n.logoImage,u=n.logoOpacity,d=n.logoOnLoad,h=n.removeQrC
692odeBehindLogo,m=n.qrStyle,b=n.eyeRadius,g=n.eyeColor,p=n.logoPaddingStyle,y=+this.props.size,v=+this.props.quietZone,_=this.props.logoWidth?+this.props.logoWidth:0,w=this.props.logoHeight?+this.props.logoHeight:0,C=this.props.logoPadding?+this.props.logoPadding:0,A=yJ(0,i);A.addData(this.utf16to8(s)),A.make();var E=(r=this.canvasRef)===null||r===void 0?void 0:r.current,S=E.getContext("2d"),k=y+2*v,O=A.getModuleCount(),T=y/O,R=window.devicePixelRatio||1;E.height=E.width=k*R,S.scale(R,R),S.fillStyle=o,S.fillRect(0,0,k,k);var N=v,M=[{row:0,col:0},{row:0,col:O-7},{row:O-7,col:0}];if(S.strokeStyle=l,m==="dots"){S.fillStyle=l;for(var B=T/2,U=0;U<O;U++)for(var X=0;X<O;X++)A.isDark(U,X)&&!this.isInPositioninZone(U,X,M)&&(S.beginPath(),S.arc(Math.round(X*T)+B+N,Math.round(U*T)+B+N,B/100*75,0,2*Math.PI,!1),S.closePath(),S.fill())}else if(m==="fluid"){for(var B=Math.ceil(T/2),U=0;U<O;U++)for(var X=0;X<O;X++)if(A.isDark(U,X)&&!this.isInPositioninZone(U,X,M)){var oe=[!1,!1,!1,!1];U>0&&!A.isDark(U-1,X)&&X>0&&!A.isDark(U,X-1)&&(oe[0]=!0),U>0&&!A.isDark(U-1,X)&&X<O-1&&!A.isDark(U,X+1)&&(oe[1]=!0),U<O-1&&!A.isDark(U+1,X)&&X<O-1&&!A.isDark(U,X+1)&&(oe[2]=!0),U<O-1&&!A.isDark(U+1,X)&&X>0&&!A.isDark(U,X-1)&&(oe[3]=!0);var L=Math.ceil((X+1)*T)-Math.floor(X*T),F=Math.ceil((U+1)*T)-Math.floor(U*T);S.fillStyle=l,S.beginPath(),S.arc(Math.round(X*T)+B+N,Math.round(U*T)+B+N,B,0,2*Math.PI,!1),S.closePath(),S.fill(),oe[0]||S.fillRect(Math.round(X*T)+N,Math.round(U*T)+N,L/2,F/2),oe[1]||S.fillRect(Math.round(X*T)+N+Math.floor(L/2),Math.round(U*T)+N,L/2,F/2),oe[2]||S.fillRect(Math.round(X*T)+N+Math.floor(L/2),Math.round(U*T)+N+Math.floor(F/2),L/2,F/2),oe[3]||S.fillRect(Math.round(X*T)+N,Math.round(U*T)+N+Math.floor(F/2),L/2,F/2)}}else for(var U=0;U<O;U++)for(var X=0;X<O;X++)if(A.isDark(U,X)&&!this.isInPositioninZone(U,X,M)){S.fillStyle=l;var L=Math.ceil((X+1)*T)-Math.floor(X*T),F=Math.ceil((U+1)*T)-Math.floor(U*T);S.fillRect(Math.round(X*T)+N,Math.round(U*T)+N,L,F)}for(var V=0;V<3;V++){var Z=M[V],U=Z.row,X=Z.col,K=b,ie=void 0;Array.isArray(K)&&(K=K[V]),typeof K=="number"&&(K=[K,K,K,K]),g?Array.isArray(g)?ie=g[V]:ie=g:ie=l,this.drawPositioningPattern(S,T,N,U,X,ie,K)}if(c){var se=new Image;a&&(se.crossOrigin="Anonymous"),se.onload=function(fe){S.save();var Y=_||y*.2,I=w||Y,z=(y-Y)/2,q=(y-I)/2;if(h||C){S.beginPath(),S.strokeStyle=o,S.fillStyle=o;var ae=Y+2*C,ee=I+2*C,le=z+N-C,ve=q+N-C;if(p==="circle"){var ye=le+ae/2,Ae=ve+ee/2;S.ellipse(ye,Ae,ae/2,ee/2,0,0,2*Math.PI),S.stroke(),S.fill()}else S.fillRect(le,ve,ae,ee)}S.globalAlpha=u,S.drawImage(se,z+N,q+N,Y,I),S.restore(),d&&d(fe)},se.src=c}},e.prototype.render=function(){var r,n=+this.props.size+2*+this.props.quietZone;return Ub.createElement("canvas",{id:(r=this.props.id)!==null&&r!==void 0?r:"react-qrcode-logo",height:n,width:n,style:Wy({height:n+"px",width:n+"px"},this.props.style),ref:this.canvasRef})},e.defaultProps={value:"https://reactjs.org/",ecLevel:"M",enableCORS:!1,size:150,quietZone:10,bgColor:"#FFFFFF",fgColor:"#000000",logoOpacity:1,qrStyle:"squares",eyeRadius:[0,0,0],logoPaddingStyle:"square"},e}(Ub.Component);jN=A0.QRCode=_J;const xJ=({open:t,onClose:e})=>{const r=We(U1);return f.jsx(Bl,{open:t,onOpenChange:n=>!n&&e(),children:f.jsx(Lc,{className:"text-center !flex-col !mx-auto !text-center !max-w-md",showCloseButton:!0,onClose:e,children:f.jsxs("div",{className:"border !border-bolt-elements-borderColor flex flex-col gap-5 justify-center items-center p-6 bg-bolt-elements-background-depth-2 rounded-md",children:[f.jsx("div",{className:"i-bolt:expo-brand h-10 w-full invert dark:invert-none"}),f.jsx(Dc,{className:"text-bolt-elements-textTertiary text-lg font-semibold leading-6",children:"Preview on your own mobile device"}),f.jsx(Cd,{className:"bg-bolt-elements-background-depth-3 max-w-sm rounded-md p-1 border border-bolt-elements-borderColor",children:"Scan this QR code with the Expo Go app on your mobile device to open your project."}),f.jsx("div",{className:"my-6 flex flex-col items-center",children:r?f.jsx(jN,{logoImage:"/logomain.png",removeQrCodeBehindLogo:!0,logoPadding:3,logoHeight:50,logoWidth:50,logoPaddingStyle:"square",style:{borderRadius:16,padding:2,backgroundColor:"#8a5fff"},value:r,size:200}):f.jsx("div",{className:"text-gray-500 text-center",children:"No Expo URL detected."})})]})})})},wJ=({isListening:t,onStart:e,onStop:r,disabled:n,unsupported:s=!1,showLabel:i=!1})=>{const a=s?"Voice input is not supported in this browser. Try Chrome or Edge.":t?"Stop listening":"Start speech recognition";return f.jsx(tu,{title:a,"aria-label":s?"Voice input unsupported":t?"Stop speech recognition":"Start speech recognition",disabled:n,className:ue("transition-all",i?"gap-2 rounded-full border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-3 py-1.5 text-xs font-medium text-bolt-elements-textSecondary enabled:hover:bg-bolt-elements-background-depth-3 enabled:hover:text-bolt-elements-textPrimary":"",{"text-bolt-elements-item-contentAccent":t}),onClick:()=>
692{if(s){Se.info("Voice input is not supported in this browser. Try Chrome or Edge for speech to text.");return}t?r():e()},children:f.jsxs(f.Fragment,{children:[t?f.jsx("div",{className:"i-ph:microphone-slash text-xl"}):f.jsx("div",{className:"i-ph:microphone text-xl"}),i?f.jsx("span",{children:t?"Stop listening":"Speech to text"}):null]})})},SJ=_t.lazy(()=>H(()=>import("./VideoStudio-_hTpIzKt.js").then(t=>t.a),__vite__mapDeps([213,5,6,22,23,110,109,111,47,46,54,112,113,62,41,63,36,37,33,3,43,40,64,68,39,20,14,51,16,17,11,18,15,214,27,215,30,31,216,217,218,219,61,220,52,221])).then(t=>({default:t.VideoStudioPage}))),CJ=_t.lazy(()=>H(()=>import("./AudioStudio-Cco9byUX.js").then(t=>t.a),__vite__mapDeps([222,5,6,22,23,223,14,3,16,17,11,41,46,216,62,224,51,18,15,214,27,30,31,32,33,112,55,217,218,61,220,47,52])).then(t=>({default:t.AudioStudioPage}))),hA=["Describe the idea you want Genie building","Explain what you want Genie to create","Start typing your prompt for Genie here","Tell Genie what you'd like made today","Share your project details for Genie now","Write what you want Genie to generate"],AJ=new Set(["apng","avif","bmp","gif","ico","jpeg","jpg","png","svg","webp"]),EJ=new Set(["avi","m4v","mov","mp4","mpeg","mpg","webm"]),kJ=new Set(["aac","flac","m4a","mp3","ogg","opus","wav","webm"]),PJ=24,TJ=12,RJ=12;function El(t,e){typeof window>"u"||window.dispatchEvent(new CustomEvent("cloudmysite:media-library-metric",{detail:{name:t,...e}}))}function fA(t){const e=Date.parse(t.updatedAt||t.createdAt||"");return Number.isFinite(e)?e:0}function rm(t){const r=String(t.filename||"").trim().toLowerCase().match(/\.([a-z0-9]+)$/i);if(r?.[1])return r[1].toLowerCase();const n=String(t.mimeType||"").trim().toLowerCase();return n.startsWith("image/")||n.startsWith("video/")||n.startsWith("audio/")?n.slice(6):"file"}function pA(t){return rm(t).toUpperCase()}function Wm(t){if(t.assetType==="image"||t.assetType==="video"||t.assetType==="audio"||t.assetType==="file")return t.assetType;const e=String(t.mimeType||"").trim().toLowerCase();if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video";if(e.startsWith("audio/"))return"audio";const r=rm(t);return AJ.has(r)?"image":EJ.has(r)?"video":kJ.has(r)?"audio":"file"}function Qf(t){return Wm(t)==="image"}function mA(t,e){return e?/^data:image\//i.test(e)?!0:Qf(t):!1}function IJ(t){switch(Wm(t)){case"video":return"i-ph:film-strip";case"audio":return"i-ph:speaker-high";case"image":return"i-ph:image";case"file":default:return"i-ph:file"}}function NJ(t){switch(Wm(t)){case"video":return"Video";
692case"audio":return"Audio";case"image":return"Image";case"file":default:return"File"}}function gA(t){return t.trim().length>0?t.toUpperCase():"FILE"}function LJ(t,e){return e==="all"?!0:e==="generated"?t.category==="generated":t.category!=="generated"}function DJ(t){const e=new Date(t.createdAt||t.updatedAt||"");return Number.isNaN(e.getTime())?"Unknown date":e.toLocaleDateString()}function MJ(t){return!t||t<=0?"":t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function OJ(t){return t.category==="generated"||t.source==="generated"?"Generated":t.category==="branding"?"Branding":t.category==="temp"?"Temporary":"Upload"}function jJ(t){const e=Q1(t);return e?`${e.aspectRatioLabel} - ${e.size}`:t}function $J(t){const e=Date.parse(String(t||""));return Number.isFinite(e)?Math.max(0,Math.floor((Date.now()-e)/J1)):0}function BJ(t,e){const r=$J(e);switch(t){case"PENDING":return Math.min(25,15+r*5);case"RUNNING":return Math.min(84,25+r*12);case"STORING":return 92;case"SUCCEEDED":return 100;case"FAILED":case"CANCELED":case"UNKNOWN":return 100;default:return 0}}function FJ(t){return String(t||"").trim()}const WJ=t=>{const e=t.isStreaming||!!t.readOnlyReason,r=x.useMemo(()=>jD(t.input),[t.input]),[n,s]=x.useState(""),[i,a]=x.useState(0),[o,l]=x.useState(0),[c,u]=x.useState(!1),[d,h]=x.useState("connect"),[m,b]=x.useState(null),[g,p]=x.useState([]),[y,v]=x.useState(""),[_,w]=x.useState(!1),[C,A]=x.useState(null),[E,S]=x.useState(!1),[k,O]=x.useState(null),[T,R]=x.useState(!1),N=l_(),[M,B]=x.useState(""),[U,X]=x.useState(""),[oe,L]=x.useState([]),[F,V]=x.useState({}),[Z,K]=x.useState({}),[ie,se]=x.useState([]),[fe,Y]=x.useState("all"),[I,z]=x.useState("newest"),[q,ae]=x.useState("all"),[ee,le]=x.useState(!1),[ve,ye]=x.useState(!1),[Ae,we]=x.useState(!1),[pe,Ye]=x.useState(!1),[ft,pt]=x.useState(null),[Lt,nt]=x.useState(null),[xt,ct]=x.useState(!1),[_r,ht]=x.useState(!1),[Pe,be]=x.useState(0),[Te,Ne]=x.useState(!1),[Fe,Fr]=x.useState(!1),[Jr,Dt]=x.useState(0),[Yt,Os]=x.useState(!1),[ci,Yn]=x.useState(0),[$n,lt]=x.useState(""),[bs,wn]=x.useState(""),[Bn,an]=x.useState($h[0]?.id||"1:1"),[vs,ys]=x.useState(hg),[Fn,Ir]=x.useState(rM),[Wn,Hn]=x.useState(!0),[is,rn]=x.useState(""),[Jt,xr]=x.useState(null),[Mt,Gs]=x.useState(!1),[ir,Ai]=x.useState(null),[Xn,os]=x.useState([]),[Ur,ui]=x.useState(!1),nn=x.useRef(null),St=x.useRef(0),Ei=x.useRef(!1),Tn=!!String(t.assetLibraryWorkspaceId||"").trim(),fr=t.assetWorkspaceId||t.assetLibraryWorkspaceId||null,Sn=N.constrained?TJ:PJ,kr=async te=>{const De=te.filter(je=>je.type.startsWith("image/")||je.type.startsWith("video/")||je.type.startsWith("audio/"));De.length!==0&&await t.handleImageFilesSelected?.(De)},Ot=x.useMemo(()=>{const te=M.trim().toLowerCase(),De=oe.filter(je=>{const Ge=`${je.filename||""} ${je.id} ${je.category} ${pA(je)}`.toLowerCase(),$t=!te||Ge.includes(te),qe=LJ(je,fe),Bt=q==="all"||rm(je)===q;return $t&&qe&&Bt});return De.sort((je,Ge)=>{if(I==="name")return String(je.filename||je.id).localeCompare(String(Ge.filename||Ge.id),void 0,{sensitivity:"base"});const $t=fA(Ge)-fA(je);return I==="oldest"?-$t:$t}),De},[fe,M,I,q,oe]),Or=x.useMemo(()=>Array.from(new Set(oe.map(te=>rm(te)))).filter(te=>te!=="file").sort((te,De)=>te.localeCompare(De)),[oe]),zr=x.useMemo(()=>Ot.filter(te=>ie.includes(te.id)).length,[Ot,ie]),Pr=Ot.length>0&&zr===Ot.length,as=x.useMemo(()=>t.uploadedFiles.map((te,De)=>({file:te,index:De,imageData:t.imageDataList[De]})).filter(te=>typeof te.imageData=="string"&&te.imageData.trim().length>0),[t.uploadedFiles,t.imageDataList]);x.useMemo(()=>{const te=y.trim().toLowerCase();return te?g.filter(De=>`${De.name} ${De.mimeType}`.toLowerCase().includes(te)):g},[g,y]),x.useMemo(()=>g.find(te=>te.id===k)||null,[g,k]);const $i=x.useMemo(()=>$h.find(te=>te.id===Bn)||null,[Bn]),jt=Bn==="custom"?vs.trim():$i?.size||hg,_s=x.useMemo(()=>nM({workspaceId:t.assetWorkspaceId||"",rawPrompt:$n,prompt:$n,negativePrompt:bs,size:jt,n:Fn,seed:is.trim().length>0?Number(is):null,promptExtend:Wn}),[t.assetWorkspaceId,Fn,bs,$n,Wn,jt,is]),Rn=ir?.assets||[],jr=x.useMemo(()=>Rn.filter(te=>Xn.includes(te.asset.id)),[Rn,Xn]),wr=as.length>0,In=A$({prompt:t.input,chatStarted:t.chatStarted,chatMode:t.chatMode,isNewsletterMode:t.isNewsletterMode}),ur=!wr&&!t.selectedElement&&!t.compactEmptyComposer,di=t.TEXTAREA_MIN_HEIGHT+88+(In?68:0),ls=(t.input.trim().length>0||t.uploadedFiles.length>0)&&!In;x.useEffect(()=>()=>{},[]),x.useEffect(()=>()=>{},[c]),x.useEffect(()=>()=>{},[m,c,d]),x.useEffect(()=>{},[m,c]),x.useEffect(()=>{wr||t.input.length>0||t.uploadedFiles.length===0&&t.imageDataList.length===0||t.clearImageAttachments?.()},[t.clearImageAttachments,wr,t.imageDataList.length,t.input.length,t.uploadedFiles.length]),x.useEffect(()=>{if(!t.assetWorkspaceId||!t.handleExistingAssetSelected)return;const te=b2();!te||te.workspaceId!==t.assetWorkspaceId||XM(te.assetId).then(De=>t.handleExistingAssetSelected?.(De)).then(()=>{Se.success("Generated image added to your current prompt.")}).catch(De=>{console.error("Failed to restore Image Studio asset into the prompt",De),Se.error(De instanceof Error?De.message:"Unable to use the generated image in this project.")})},[t.assetWorkspaceId,t.handleExistingAssetSelected]),x.useEffect(()=>{if(!T)return;const te=window.setTimeout(()=>{X(M.trim())},350);return()=>window.clearTimeout(te)},[M,T]),x.useEffect(()=>{if(!T)return;const te=St.current+1;St.current=te;const De=typeof performance<"u"?performance.now():Date.now(),je=fe==="generated"?"generated":fe==="uploads"?"upload":"all";let Ge=!1;const $t=window.setTimeout(()=>{!Ge&&St.current===te&&ht(!0)},5e3);return we(!0),pt(null),nt(null),ct(!1),ht(!1),L([]),V({}),K({}),Ei.current=!1,Sx({workspaceId:t.assetLibraryWorkspaceId,limit:Sn,sort:I,type:q,source:je,query:U}).then(qe=>{if(Ge||St.current!==te)return;L(qe.assets),V(Object.fromEntries(qe.assets.filter(Lr=>Qf(Lr)&&typeof Lr.thumbnailUrl=="string"&&Lr.thumbnailUrl).map(Lr=>
692[Lr.id,Lr.thumbnailUrl]))),nt(qe.nextCursor),ct(qe.hasMore);const Bt=typeof performance<"u"?performance.now():Date.now();El("metadata-response",{durationMs:qe.durationMs,elapsedSinceOpenMs:Math.max(0,Bt-De),responseBytes:qe.responseBytes,requestedAssets:qe.limit,returnedAssets:qe.assets.length,effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained}),qe.assets.length>0&&El("first-card",{elapsedSinceOpenMs:Math.max(0,Bt-De),returnedAssets:qe.assets.length,constrained:N.constrained})}).catch(qe=>{Ge||St.current!==te||(console.error("Failed to load managed assets",qe),pt(qe instanceof Error?qe.message:"Failed to load assets"),El("pagination-failure",{phase:"first-page",effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained}))}).finally(()=>{window.clearTimeout($t),!Ge&&St.current===te&&we(!1)}),()=>{Ge=!0,window.clearTimeout($t)}},[fe,Sn,Pe,I,q,T,U,N.constrained,N.effectiveType,N.saveData,t.assetLibraryWorkspaceId]),x.useEffect(()=>{!T||oe.length===0||V(te=>{let De=!1;const je={...te};for(const Ge of oe)je[Ge.id]||!Qf(Ge)||!Ge.thumbnailUrl||(je[Ge.id]=Ge.thumbnailUrl,De=!0);return De?je:te})},[T,oe]),x.useEffect(()=>{se(te=>te.filter(De=>oe.some(je=>je.id===De)))},[oe]),x.useEffect(()=>{q!=="all"&&(Or.includes(q)||ae("all"))},[q,Or]),x.useEffect(()=>{if(!Te||!ir?.id||_c(ir.status))return;let te=!1;const De=async()=>{try{const Ge=await sM(ir.id);if(te)return;Ai(Ge.task),Ge.task.assets&&Ge.task.assets.length>0&&os($t=>$t.length>0?$t:Ge.task.assets.map(qe=>qe.asset.id)),(Ge.task.status==="FAILED"||Ge.task.status==="CANCELED"||Ge.task.status==="UNKNOWN")&&xr(Ge.task.errorMessage||"Image generation failed.")}catch(Ge){if(te)return;console.error("Failed to poll Wan image task",Ge),xr(Ge instanceof Error?Ge.message:"Failed to check image generation status.")}},je=window.setTimeout(()=>{De()},J1);return()=>{te=!0,window.clearTimeout(je)}},[Te,ir]);const ln=te=>{const De=typeof te=="string"&&te.trim().length>0?te:t.input,je=Q1(jt);Ne(!0),xr(null),Ai(null),os([]),Gs(!1),ui(!1),lt(De||$n),an(je?.id||$h[0]?.id||"1:1"),ys(jt||hg)},Gr=()=>{Dt(te=>te+1),Fr(!0)},Bi=()=>{Yn(te=>te+1),Os(!0)},br=()=>{xr(null),Gs(!1),ui(!1),Ai(null),os([])},Tr=async()=>{if(!_s.valid||!_s.normalized){xr(Object.values(_s.errors)[0]||"Fix the image settings and try again.");return}Gs(!0),xr(null);try{const te=await iM(_s.normalized);Ai(te.task),os([])}catch(te){console.error("Failed to start Wan image generation",te),xr(te instanceof Error?te.message:"Unable to start image generation.")}finally{Gs(!1)}},Vt=te=>{os(De=>De.includes(te)?De.filter(je=>je!==te):[...De,te])},Qr=async()=>{if(!(jr.length===0||Ur)){ui(!0);try{for(const te of jr)await t.handleExistingAssetSelected?.(te.asset);Se.success(`${jr.length} generated image${jr.length===1?"":"s"} attached to this prompt.`),Ne(!1),br()}catch(te){console.error("Failed to attach generated Wan asset",te),Se.error("Failed to attach generated images.")}finally{ui(!1)}}};x.useEffect(()=>{if(t.chatStarted||t.input.length>0)return;const te=hA[i];if(o<te.length){const De=setTimeout(()=>{s(je=>je+te[o]),l(o+1)},70);return()=>clearTimeout(De)}else{const De=setTimeout(()=>{s(""),l(0),a(je=>(je+1)%hA.length)},1800);return()=>clearTimeout(De)}},[o,i,t.input,t.chatStarted]);const Ar=async te=>{try{await t.handleExistingAssetSelected?.(te),R(!1),se([]),Se.success(`Attached ${te.filename||te.id}`)}catch(De){console.error("Failed to attach managed asset",De),Se.error("Failed to attach asset")}},cs=te=>{se(De=>De.includes(te)?De.filter(je=>je!==te):[...De,te])},Ut=()=>{if(Ot.length!==0){if(Pr){const te=new Set(Ot.map(De=>De.id));se(De=>De.filter(je=>!te.has(je)));return}se(te=>[...new Set([...te,...Ot.map(De=>De.id)])])}},xs=async()=>{if(!T||!Lt||pe)return;const te=fe==="generated"?"generated":fe==="uploads"?"upload":"all",De=St.current;Ye(!0),pt(null);try{const je=await Sx({workspaceId:t.assetLibraryWorkspaceId,limit:Sn,cursor:Lt,sort:I,type:q,source:te,query:U});if(St.current!==De)return;L(Ge=>{const $t=new Map(Ge.map(qe=>[qe.id,qe]));for(const qe of je.assets)$t.set(qe.id,qe);return[...$t.values()]}),V(Ge=>{const $t={...Ge};for(const qe of je.assets)Qf(qe)&&qe.thumbnailUrl&&($t[qe.id]=qe.thumbnailUrl);return $t}
692),nt(je.nextCursor),ct(je.hasMore),El("metadata-response",{phase:"next-page",durationMs:je.durationMs,responseBytes:je.responseBytes,requestedAssets:je.limit,returnedAssets:je.assets.length,effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained})}catch(je){console.error("Failed to load more managed assets",je),pt(je instanceof Error?je.message:"Failed to load more assets"),El("pagination-failure",{phase:"next-page",effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained})}finally{St.current===De&&Ye(!1)}},Nr=async()=>{if(ie.length===0||ee)return;const te=oe.filter(Ge=>ie.includes(Ge.id)),De=Math.max(0,ld-t.uploadedFiles.length),je=te.slice(0,De);if(te.length!==0){if(De<=0){Se.info(`You can attach up to ${ld} assets to a prompt right now.`);return}te.length>je.length&&Se.info(`Only the first ${ld} assets will be attached.`),le(!0);try{for(const Ge of je)await t.handleExistingAssetSelected?.(Ge);R(!1),se([]),Se.success(je.length===1?`Attached ${je[0].filename||je[0].id}`:`Attached ${je.length} assets`)}catch(Ge){console.error("Failed to attach selected managed assets",Ge),Se.error("Failed to attach selected assets")}finally{le(!1)}}},js=()=>{if(!t.assetWorkspaceId){Se.error("Open a workspace before uploading assets.");return}nn.current?.click()},pn=async te=>{const De=te.filter(je=>je.type.startsWith("image/")||je.type.startsWith("video/")||je.type.startsWith("audio/"));if(De.length===0){Se.error("Select image, video, or audio files to upload.");return}if(!t.assetWorkspaceId){Se.error("Workspace media library is not ready yet.");return}ye(!0);try{const je=await Promise.all(De.map($t=>nv($t,{workspaceId:t.assetWorkspaceId,category:"uploads",source:"upload"}))),Ge=je.map(({asset:$t,previewUrl:qe})=>({...$t,previewDataUrl:qe}));L($t=>{const qe=new Map($t.map(Bt=>[Bt.id,Bt]));for(const Bt of Ge)qe.set(Bt.id,Bt);return[...qe.values()]}),V($t=>{const qe={...$t};for(const Bt of je)mA(Bt.asset,Bt.previewUrl)&&(qe[Bt.asset.id]=Bt.previewUrl);return qe}),K($t=>{const qe={...$t};for(const Bt of je)delete qe[Bt.asset.id];return qe}),se($t=>[...new Set([...$t,...Ge.map(qe=>qe.id)])]),B(""),Y("all"),ae("all"),pt(null),Se.success(Ge.length===1?`Uploaded ${Ge[0].filename||Ge[0].id}`:`Uploaded ${Ge.length} files`)}catch(je){console.error("Failed to upload managed assets from the library dialog",je),Se.error("Failed to upload those files.")}finally{ye(!1)}};return f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:ue("relative z-prompt mx-auto w-full max-w-full shrink-0 overflow-hidden rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 backdrop-blur",t.compactEmptyComposer?"p-2.5":"p-3"),style:{height:ur?di:void 0,minHeight:ur?di:void 0,maxHeight:ur?di:void 0},children:[f.jsx(cJ,{previewItems:as,onRemove:te=>{t.removeImageAttachment?.(te)}}),f.jsx(Ml,{children:()=>f.jsx(uJ,{handleImageFilesSelected:t.handleImageFilesSelected,uploadedFiles:t.uploadedFiles,imageDataList:t.imageDataList})}),t.selectedElement&&f.jsxs("div",{className:"flex mx-1.5 gap-2 items-center justify-between rounded-lg rounded-b-none border border-b-none border-bolt-elements-borderColor text-bolt-elements-textPrimary flex py-1 px-2.5 font-medium text-xs",children:[f.jsxs("div",{className:"flex gap-2 items-center lowercase",children:[f.jsx("code",{className:"bg-accent-500 rounded-4px px-1.5 py-1 mr-0.5 text-white",children:t?.selectedElement?.tagName}),"selected for inspection"]}),f.jsx("button",{className:"bg-transparent text-accent-500 pointer-auto",onClick:()=>t.setSelectedElement?.(null),children:"Clear"})]}),f.jsxs("div",{className:ue("relative overflow-hidden rounded-lg border border-bolt-elements-borderColor shadow-xs backdrop-blur"),children:[f.jsx("textarea",{ref:t.textareaRef,rows:1,className:ue("block w-full resize-none bg-transparent px-4 text-sm leading-5 text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary outline-none sm:pr-20 md:pr-24",t.compactEmptyComposer?"pb-2.5 pt-2.5 pr-16":"pb-4 pt-4 pr-16",e?"cursor-not-allowed opacity-80":"","transition-all duration-200","hover:border-bolt-elements-focus"),disabled:e,readOnly:e,"aria-busy":e,"aria-disabled":e,onDragEnter:te=>{if(e){te.preventDefault();return}
692te.preventDefault(),te.currentTarget.style.border="2px solid #1488fc"},onDragOver:te=>{if(e){te.preventDefault();return}te.preventDefault(),te.currentTarget.style.border="2px solid #1488fc"},onDragLeave:te=>{if(e){te.preventDefault();return}te.preventDefault(),te.currentTarget.style.border="1px solid var(--bolt-elements-borderColor)"},onDrop:te=>{if(e){te.preventDefault();return}te.preventDefault(),te.currentTarget.style.border="1px solid var(--bolt-elements-borderColor)";const De=Array.from(te.dataTransfer.files);kr(De).catch(je=>{console.error("Failed to attach dropped image",je),Se.error("Failed to attach dropped image")})},onKeyDown:te=>{if(e){te.preventDefault();return}if(te.key==="Enter"){if(te.shiftKey)return;if(te.preventDefault(),t.isStreaming){t.handleStop?.();return}if(te.nativeEvent.isComposing||!ls)return;t.handleSendMessage?.(te)}},value:t.input,onChange:te=>{e||t.handleInputChange?.(te)},onPaste:te=>{if(e){te.preventDefault();return}t.handlePaste(te)},style:{boxSizing:"border-box",height:t.TEXTAREA_MIN_HEIGHT,minHeight:t.TEXTAREA_MIN_HEIGHT,maxHeight:t.TEXTAREA_MIN_HEIGHT,overflowY:t.input.length===0?"hidden":"auto",scrollbarGutter:"stable"},translate:"no"}),t.input.length===0&&!t.chatStarted&&f.jsx("p",{className:ue("pointer-events-none absolute left-5 right-16 text-sm font-medium leading-5 text-bolt-elements-textSecondary sm:right-20 md:right-24",t.compactEmptyComposer?"top-3":"top-4"),children:n}),t.input.length===0&&t.chatStarted&&f.jsx("p",{className:ue("pointer-events-none absolute left-5 right-16 text-sm font-medium leading-5 text-bolt-elements-textSecondary sm:right-20 md:right-24",t.compactEmptyComposer?"top-3":"top-4"),children:t.readOnlyReason||(t.isStreaming?"Genie is processing your latest request...":"Ask Genie your message...")}),f.jsx(Ml,{children:()=>f.jsx(pJ,{show:!0,isStreaming:!1,disabled:e||!ls,onClick:te=>{!e&&ls&&t.handleSendMessage?.(te)}})}),In?f.jsx("div",{role:"alert",className:"mx-4 mt-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-300",children:Ha}):null,f.jsxs("div",{className:ue("flex flex-wrap items-center justify-between gap-x-3 gap-y-2 text-sm",t.compactEmptyComposer?"px-4 pb-2.5 pt-1":"p-4 pt-2"),children:[f.jsx("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:f.jsxs(f.Fragment,{children:[f.jsxs(bg,{align:"start",sideOffset:8,trigger:f.jsx(tu,{title:"Add media",className:"transition-all",disabled:e,children:f.jsx("div",{className:"i-ph:plus text-xl"})}),children:[f.jsxs(oo,{onSelect:()=>{t.handleFileUpload()},children:[f.jsx("div",{className:"i-ph:upload-simple text-base"}),f.jsx("span",{children:"Upload from computer"})]}),f.jsxs(oo,{onSelect:()=>{ln(t.input)},children:[f.jsx("div",{className:"i-ph:magic-wand text-base"}),f.jsx("span",{children:"Generate Image"})]}),f.jsxs(oo,{onSelect:()=>{Gr()},children:[f.jsx("div",{className:"i-ph:film-strip text-base"}),f.jsx("span",{children:"Generate Video"})]}),f.jsxs(oo,{onSelect:()=>{Bi()},children:[f.jsx("div",{className:"i-ph:speaker-high text-base"}),f.jsx("span",{children:"Generate Audio"})]}),null,f.jsxs(oo,{onSelect:()=>{R(!0)},children:[f.jsx("div",{className:"i-ph:folder-open text-base"}),f.jsx("span",{children:"Choose from assets"})]}),f.jsx(tO,{}),f.jsxs(oo,{className:ue({"pointer-events-none opacity-50":t.uploadedFiles.length===0}),onSelect:()=>{t.uploadedFiles.length!==0&&t.clearImageAttachments?.()},children:[f.jsx("div",{className:"i-ph:x-circle text-base"}),f.jsx("span",{children:"Clear attachments"})]})]}),f.jsx(wJ,{isListening:t.isListening,onStart:t.startListening,onStop:t.stopListening,disabled:e,unsupported:!t.speechRecognitionSupported}),f.jsx(tu,{title:r?"Prompt is already detailed":"Enhance prompt",disabled:e||t.input.length===0||t.enhancingPrompt||r||!t.enhancePrompt,className:ue("transition-all",t.enhancingPrompt?"opacity-100":""),onClick:()=>t.enhancePrompt?.(),children:t.enhancingPrompt?f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"}):f.jsx("div",{className:"i-bolt:stars text-xl"})})]})}),t.input.length>3?f.jsxs("div",{className:"w-full text-[11px] leading-5 text-bolt-elements-textTertiary sm:ml-auto sm:w-auto
692sm:text-right sm:text-xs",children:["Use ",f.jsx("kbd",{className:"kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2",children:"Shift"})," +"," ",f.jsx("kbd",{className:"kdb px-1.5 py-0.5 rounded bg-bolt-elements-background-depth-2",children:"Enter"})," for new line"]}):null,f.jsx(xJ,{open:t.qrModalOpen,onClose:()=>t.setQrModalOpen(!1)})]})]})]}),f.jsx(Bl,{open:Te,onOpenChange:te=>{Ne(te),te||br()},children:f.jsx(Lc,{className:"h-[94vh] w-[min(96vw,78rem)] max-h-[94vh] overflow-y-auto border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 md:h-[min(94vh,52rem)]",children:f.jsxs("div",{className:"flex min-h-full flex-col",children:[f.jsx("div",{className:"border-b border-bolt-elements-borderColor px-6 pb-5 pt-6",children:f.jsx("div",{className:"flex flex-wrap items-start justify-between gap-4",children:f.jsxs("div",{children:[f.jsxs(Dc,{className:"text-2xl font-semibold text-bolt-elements-textPrimary",children:[f.jsx("div",{className:"i-ph:magic-wand text-2xl"}),f.jsx("span",{children:"Generate image"})]}),f.jsx(Cd,{className:"text-bolt-elements-textSecondary",children:"Generate hero images, logo concepts, icons, illustrations, mockups, and marketing visuals. Final images are saved to CloudMySite storage and added to your media library."})]})})}),f.jsxs("div",{className:"grid gap-0 overflow-visible xl:grid-cols-[minmax(0,1.05fr)_minmax(20rem,0.95fr)]",children:[f.jsx("div",{className:"border-b border-bolt-elements-borderColor px-6 py-5 xl:border-b-0 xl:border-r",children:f.jsxs("div",{className:"space-y-5",children:[f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Prompt"}),f.jsx("textarea",{value:$n,onChange:te=>{lt(te.target.value),xr(null)},placeholder:"Describe the image you want, for example: A premium hero image for a sustainable skincare brand with soft studio lighting and botanical textures.",className:"cms-light-form-control min-h-[8.5rem] w-full rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background px-4 py-3 text-sm text-bolt-elements-textPrimary placeholder:text-bolt-elements-textSecondary focus:outline-none focus:ring-2 focus:ring-bolt-elements-item-backgroundAccent/35"}),f.jsx("div",{className:"flex flex-wrap gap-2",children:["Hero image","Logo concept","Icon","Illustration","Product image","Social graphic","Background"].map(te=>f.jsx("button",{type:"button",className:"rounded-full border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-3 py-1.5 text-xs font-medium text-bolt-elements-textSecondary hover:bg-bolt-elements-background-depth-3 hover:text-bolt-elements-textPrimary",onClick:()=>{lt(De=>De.trim().length>0?`${De.trim()} ${te.toLowerCase()}`:`Create a ${te.toLowerCase()} for `)},children:te},te))}),f.jsxs("div",{className:"text-xs text-bolt-elements-textTertiary",children:[$n.length,"/",2100," characters."]})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Negative prompt"}),f.jsx("textarea",{value:bs,onChange:te=>{wn(te.target.value),xr(null)},placeholder:"Optional: describe what to avoid, such as blurry text, low quality, extra fingers, watermark, distorted anatomy.",className:"cms-light-form-control min-h-[6.5rem] w-full rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background px-4 py-3 text-sm text-bolt-elements-textPrimary placeholder:text-bolt-elements-textSecondary focus:outline-none focus:ring-2 focus:ring-bolt-elements-item-backgroundAccent/35"}),f.jsxs("div",{className:"text-xs text-bolt-elements-textTertiary",children:[bs.length,"/",500," characters."]})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Aspect ratio and size"}),f.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[$h.map(te=>{const De=Bn===te.id;return f.jsxs("button",{type:"button",className:ue("rounded-2xl border px-4 py-3 text-left transition-all",De?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent/10 ring-2 ring-bolt-elements-item-backgroundAccent/25":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 hover:border-bolt-elements-borderColorActive hover:bg-bolt-elements-background-depth-3"),onClick:()=>{an(te.id),ys(te.size),xr(null)},children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:te.label}),f.jsxs("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:[te.aspectRatioLabel," - ",te.size]}),f.jsx("div",{className:"mt-2 text-xs text-bolt-elements-textTertiary",children:te.description})]},te.id)}),f.jsxs("button",{type:"button",className:ue("rounded-2xl border px-4 py-3 text-left transition-all",Bn==="custom"?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent/10 ring-2 ring-bolt-elements-item-backgroundAccent/25":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 hover:border-bolt-elements-borderColorActive hover:bg-bolt-elements-background-depth-3"),onClick:()=>{an("custom"),xr(null)},children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Custom"}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:"Enter width*height"}),f.jsx("div",{className:"mt-2 text-xs text-bolt-elements-textTertiary",children:"Validation runs before generation starts."})]})]}),Bn==="custom"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx(xg,{value:vs,onChange:te=>{ys(te.target.value),xr(null)},placeholder:"1280*1280"}),f.jsx("div",{className:"text-xs text-bolt-elements-textTertiary",children:"Use the format width*height. Aspect ratio must stay between 1:4 and 4:1."})]})]}),f.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Number of images"}),f.jsx("div",{className:"grid grid-cols-4 gap-2",children:[1,2,3,4].map(te=>f.jsx("button",{type:"button",className:ue("rounded-xl border px-3 py-2 text-sm font-medium transition-colors",Fn===te?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-background-depth-3 hover:text-bolt-elements-textPrimary"),onClick:()=>
692{Ir(te),xr(null)},children:te},te))}),f.jsx("div",{className:"text-xs text-bolt-elements-textTertiary",children:Fn>1?"Generating more than one image increases cost.":"1 image keeps costs lower and is the default."})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Optional seed"}),f.jsx(xg,{value:is,onChange:te=>{rn(te.target.value.replace(/[^\d]/g,"")),xr(null)},placeholder:"Random seed"}),f.jsx("div",{className:"text-xs text-bolt-elements-textTertiary",children:"Reuse a seed to keep results relatively stable."})]})]}),f.jsx("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-4 py-3",children:f.jsxs("label",{className:"flex items-start gap-3",children:[f.jsx(op,{checked:Wn,onCheckedChange:te=>{Hn(!!te)},className:"mt-1"}),f.jsxs("div",{children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Prompt extend"}),f.jsx("div",{className:"mt-1 text-sm text-bolt-elements-textSecondary",children:"Let the generator refine shorter prompts for better results. This usually improves quality but adds latency."})]})]})}),Jt?f.jsx("div",{className:"rounded-2xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-sm text-red-700 dark:text-red-300",children:Jt}):null]})}),f.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden bg-bolt-elements-background-depth-2",children:[f.jsxs("div",{className:"border-b border-bolt-elements-borderColor px-6 py-5",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:"Generation status"}),f.jsx("div",{className:"mt-2 text-sm text-bolt-elements-textSecondary",children:ir?cx(ir.status):"Ready to generate"}),f.jsx("div",{className:"mt-4 h-2 overflow-hidden rounded-full bg-bolt-elements-background-depth-3",children:f.jsx("div",{className:ue("h-full rounded-full transition-all duration-500",ir?.status==="FAILED"||ir?.status==="CANCELED"||ir?.status==="UNKNOWN"?"bg-red-500":"bg-bolt-elements-item-backgroundAccent"),style:{width:`${BJ(ir?.status,ir?.createdAt)}%`}})}),f.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-xs text-bolt-elements-textSecondary",children:[f.jsx("span",{children:jJ(jt)}),f.jsxs("span",{children:[Fn," image",Fn===1?"":"s"]}),f.jsx("span",{children:"Watermark disabled"})]})]}),f.jsx("div",{className:"px-6 py-5",children:ir?ir.status==="FAILED"||ir.status==="CANCELED"||ir.status==="UNKNOWN"?f.jsx("div",{className:"rounded-2xl border border-red-500/25 bg-red-500/10 p-5 text-sm text-red-700 dark:text-red-300",children:ir.errorMessage||"Image generation failed."}
692):_c(ir.status)?Rn.length>0?f.jsx("div",{className:"space-y-4",children:f.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:Rn.map(te=>{const De=Xn.includes(te.asset.id),je=FJ(te.storedUrl);return f.jsxs("button",{type:"button",className:ue("overflow-hidden rounded-2xl border bg-bolt-elements-background text-left transition-all",De?"border-bolt-elements-item-backgroundAccent ring-2 ring-bolt-elements-item-backgroundAccent/25":"border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive"),onClick:()=>{Vt(te.asset.id)},children:[f.jsx("img",{src:te.asset.thumbnailUrl||te.asset.optimizedUrl||te.asset.url,alt:te.asset.filename||te.asset.id,className:"aspect-square w-full bg-bolt-elements-background-depth-3 object-cover"}),f.jsxs("div",{className:"space-y-2 p-3",children:[f.jsxs("div",{className:"flex items-start justify-between gap-2",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"truncate text-sm font-medium text-bolt-elements-textPrimary",children:te.asset.filename||te.asset.id}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:te.asset.width&&te.asset.height?`${te.asset.width}x${te.asset.height}`:te.asset.mimeType||"Generated image"})]}),f.jsx("div",{className:ue("flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-sm transition-colors",De?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-bolt-elements-textPrimary"),children:f.jsx("div",{className:De?"i-ph:check text-base":"i-ph:plus text-base"})})]}),f.jsx("div",{className:"text-xs text-bolt-elements-textSecondary",children:"Stored URL"}),f.jsx("div",{className:"break-all text-xs text-bolt-elements-textTertiary",children:je})]})]},te.asset.id)})})}):f.jsx("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background p-5 text-sm text-bolt-elements-textSecondary",children:"Image generation finished but CloudMySite did not receive any stored images from the task."}):f.jsx("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background p-5",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg animate-spin text-2xl text-bolt-elements-item-backgroundAccent"}),f.jsxs("div",{children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:cx(ir.status)}),f.jsx("div",{className:"mt-1 text-sm text-bolt-elements-textSecondary",children:"Your images are being created and CloudMySite will save the results to permanent storage as soon as they are ready."})]})]})}):f.jsx("div",{className:"rounded-2xl border border-dashed border-bolt-elements-borderColor p-5 text-sm text-bolt-elements-textSecondary",children:"Generated images will appear here after the task finishes. They are immediately copied into CloudMySite's permanent media storage so you can reuse them in the builder."})}),f.jsx("div",{className:"hidden shrink-0 border-t border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-6 py-4",children:f.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textSecondary",children:Rn.length>0?`${jr.length} of ${Rn.length} generated image${Rn.length===1?"":"s"} selected`:"Generated assets will also appear in the workspace media library under Generated Images."}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(En,{type:"button",variant:"outline",onClick:()=>Ne(!1),children:"Close"}),f.jsx(En,{type:"button",variant:"outline",onClick:()=>{Tr()},disabled:!$n.trim()||Mt||!_c(ir?.status)&&!!ir,children:Mt?"Starting...":!_c(ir?.status)&&ir?"Generating...":"Generate"}),f.jsx(En,{type:"button",disabled:jr.length===0||Ur,onClick:()=>{Qr()},className:"bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent hover:bg-bolt-elements-button-primary-backgroundHover",children:Ur?"Attaching...":"Add to prompt"})]})]})})]})]}),f.jsx("div",{className:"shrink-0 border-t border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-4 py-4 sm:px-6",children:f.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textSecondary",children:Rn.length>0?`${jr.length} of ${Rn.length} generated image${Rn.length===1?"":"s"} selected`:"Generated assets will also appear in the workspace media library under Generated Images."}),f.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[f.jsx(En,{type:"button",variant:"outline",onClick:()=>Ne(!1),className:"w-full sm:w-auto",children:"Close"}),f.jsx(En,{type:"button",variant:"outline",onClick:()=>{Tr()},disabled:!$n.trim()||Mt||!_c(ir?.status)&&!!ir,className:"w-full sm:w-auto",children:Mt?"Starting...":!_c(ir?.status)&&ir?"Generating...":"Generate"}),f.jsx(En,{type:"button",disabled:jr.length===0||Ur,onClick:()=>{Qr()},className:"w-full bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent hover:bg-bolt-elements-button-primary-backgroundHover sm:w-auto",children:Ur?"Attaching...":"Add to prompt"})]})]})})]})})}),f.jsx(Bl,{open:Fe,onOpenChange:Fr,children:f.jsxs(Lc,{className:"h-[94vh] w-[min(96vw,84rem)] max-h-[94vh] overflow-y-auto border border-bolt-elements-borderColor bg-[#f5f9fc]",children:[f.jsx(Dc,{className:"sr-only",children:"Generate video"}),Fe?f.jsx(_t.Suspense,{fallback:f.jsx("div",{className:"flex h-full min-h-[28rem] items-center justify-center text-sm text-bolt-elements-textTertiary",children:"Loading Video Studio..."}),children:f.jsx(SJ,{embedded:!0,appId:fr,initialPrompt:t.input},Jr)}):null]})}),f.jsx(Bl,{open:Yt,onOpenChange:Os,children:f.jsxs(Lc,{className:"h-[94vh] w-[min(96vw,84rem)] max-h-[94vh] overflow-y-auto border border-bolt-elements-borderColor bg-[#f5f9fc]",children:[f.jsx(Dc,{className:"sr-only",children:"Generate audio"}),Yt?f.jsx(_t.Suspense,{fallback:f.jsx("div",{className:"flex h-full min-h-[28rem] items-center justify-center text-sm text-bolt-elements-textTertiary",children:"Loading Audio Studio..."}),children:f.jsx(CJ,{embedded:!0,workspaceId:fr,initialText:""},ci)}):null]})}),null,f.jsx(Bl,{open:T,onOpenChange:te=>{R(te),te||(B(""),X(""),se([]),Y("all"),z("newest"),ae("all"),nt(null),ct(!1),pt(null),ht(!1))},children:f.jsx(Lc,{className:"h-[min(88vh,56rem)] w-[min(96vw,74rem)] max-h-[88vh] overflow-hidden border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[f.jsx("input",{ref:nn,type:"file",accept:"image/*,video/*,audio/*",multiple:!0,className:"hidden",onChange:te=>{const De=Array.from(te.target.files||[]);te.target.value="",De.length>0&&pn(De)}}),f.jsxs("div",{className:"border-b border-bolt-elements-borderColor px-6 pb-5 pt-6",children:[f.jsx(Dc,{className:"text-2xl font-semibold text-bolt-elements-textPrimary",children:"Select files"}),f.jsx(Cd,{className:"text-bolt-elements-textSecondary",children:T
692n?"Choose reusable workspace assets to attach to your next prompt.":"Choose reusable assets from your library to attach to your next prompt."})]}),f.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-4 pt-4 sm:px-6 sm:pb-5 sm:pt-5",children:[f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:"pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-bolt-elements-textTertiary",children:f.jsx("div",{className:"i-ph:magnifying-glass text-xl"})}),f.jsx(xg,{autoFocus:!0,placeholder:"Search files by name...",value:M,onChange:te=>{B(te.target.value)},className:"h-12 rounded-2xl border-2 border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 pl-12 pr-4 text-base shadow-none focus-visible:ring-0"})]}),f.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[[["all","All"],["uploads","Uploads"],["generated","Generated"]].map(([te,De])=>{const je=fe===te;return f.jsx("button",{type:"button",className:ue("rounded-xl border px-4 py-2 text-sm font-medium transition-colors",je?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-background-depth-3 hover:text-bolt-elements-textPrimary"),onClick:()=>{Y(te)},children:De},te)}),f.jsxs(bg,{align:"start",trigger:f.jsxs(En,{type:"button",variant:"ghost",className:"h-10 gap-2 rounded-xl px-3 text-sm",children:[f.jsx("span",{children:I==="newest"?"Newest first":I==="oldest"?"Oldest first":"Name"}),f.jsx("div",{className:"i-ph:caret-down text-base"})]}),children:[f.jsx(oo,{onSelect:()=>z("newest"),children:f.jsx("span",{children:"Newest first"})}),f.jsx(oo,{onSelect:()=>z("oldest"),children:f.jsx("span",{children:"Oldest first"})}),f.jsx(oo,{onSelect:()=>z("name"),children:f.jsx("span",{children:"Name"})})]}),f.jsxs(bg,{align:"start",trigger:f.jsxs(En,{type:"button",variant:"ghost",className:"h-10 gap-2 rounded-xl px-3 text-sm",children:[f.jsx("span",{children:q==="all"?"All types":gA(q)}),f.jsx("div",{className:"i-ph:caret-down text-base"})]}),children:[f.jsx(oo,{onSelect:()=>ae("all"),children:f.jsx("span",{children:"All types"})}),Or.map(te=>f.jsx(oo,{onSelect:()=>ae(te),children:f.jsx("span",{children:gA(te)})},te))]}),f.jsx("button",{type:"button",className:ue("rounded-xl px-3 py-2 text-sm font-medium transition-colors",Ot.length===0?"cursor-not-allowed text-bolt-elements-textTertiary opacity-50":"text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-2"),disabled:Ot.length===0,onClick:Ut,children:Pr?"Clear selection":"Select all"})]}),f.jsxs(En,{type:"button",variant:"outline",className:"h-10 gap-2 rounded-xl px-4",disabled:ve||!t.assetWorkspaceId,onClick:()=>{js()},children:[f.jsx("div",{className:"i-ph:upload-simple text-lg"}),f.jsx("span",{children:ve?"Uploading...":"Upload"})]})]}),f.jsx("div",{className:"mt-5 min-h-[20rem] flex-1 overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2",children:Ot.length>0||Ae||ft?f.jsxs("div",{className:"h-full overflow-y-auto overscroll-contain p-4 [scrollbar-gutter:stable] sm:p-5",children:[f.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[Ot.map(te=>{const De=F[te.id],je=ie.includes(te.id),Ge=MJ(te.sizeBytes),$t=Wm(te),qe=mA(te,De);return f.jsxs("button",{type:"button",className:ue("group relative flex w-full flex-col overflow-hidden rounded-2xl border bg-bolt-elements-background-depth-1 text-left transition-all",je?"border-bolt-elements-item-backgroundAccent ring-2 ring-bolt-elements-item-backgroundAccent/30":"border-bolt-elements-borderColor hover:-translate-y-0.5 hover:border-bolt-elements-borderColorActive hover:shadow-lg"),onClick:()=>{cs(te.id)},onDoubleClick:()=>{Ar(te)},children:[qe?f.jsx("img",{src:De,alt:te.filename||te.id,width:320,height:240,loading:"lazy",decoding:"async",className:"aspect-[4/3] h-44 w-full object-cover",onLoad:()=>{Ei.current||(Ei.current=!0,El("first-thumbnail",{effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained}))},onError:()=>{K(Bt=>({...Bt,[te.id]:!0})),V(Bt=>{const Lr={...Bt};return delete Lr[te.id],Lr}),El("thumbnail-failure",{assetType:$t,effectiveType:N.effectiveType,saveData:N.saveData,constrained:N.constrained})}}):f.jsx("div",{className:"flex aspect-[4/3] h-44 w-full items-center justify-center bg-bolt-elements-background-depth-2 text-bolt-elements-textTertiary",children:f.jsx("span",{className:ue(IJ(te),"text-3xl")})}),f.jsxs("div",{className:"space-y-2 p-3",children:[f.jsxs("div",{className:"flex items-start justify-between gap-2",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"truncate text-sm font-medium text-bolt-elements-textPrimary",children:te.filename||te.id}),f.jsxs("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:[OJ(te)," ",NJ(te)]})]}),f.jsx("div",{className:ue("flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-sm transition-colors",je?"border-bolt-elements-item-backgroundAccent bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 text-bolt-elements-textPrimary"),children:f.jsx("div",{className:je?"i-ph:check text-base":"i-ph:plus text-base"})})]}),f.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-bolt-elements-textSecondary",children:[f.jsx("span",{children:pA(te)}),te.width&&te.height?f.jsxs("span",{children:[te.width,"x",te.height]}):null,Ge?f.jsx("span",{children:Ge}):null]}),f.jsx("div",{className:"text-xs text-bolt-elements-textTertiary",children:DJ(te)})]})]},te.id)}),Ae||pe?Array.from({length:Ot.length>0?Math.min(4,Sn):Math.min(RJ,Sn)}).map((te,De)=>f.jsxs("div",{className:"group relative flex w-full flex-col overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 text-left",children:[f.jsx("div",{className:"aspect-[4/3] h-44 w-full animate-pulse bg-bolt-elements-background-depth-3"}),f.jsxs("div",{className:"space-y-3 p-3",children:[f.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded-full bg-bolt-elements-background-depth-3"}),f.jsx("div",{className:"h-3 w-1/2 animate-pulse rounded-full bg-bolt-elements-background-depth-3"}),f.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded-full bg-bolt-elements-background-depth-3"})]})]},`asset-library-skeleton-${De}`)):null]}),_r?f.jsx("div",{className:"mt-4 rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-4 py-3 text-sm text-bolt-elements-textSecondary",children:"Your connection appears to be slow. Some files may take longer to appear."}):null,ft?f.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-4 py-3 text-sm text-bolt-elements-textSecondary",children:[f.jsx("span",{children:Ot.length>0?ft:"We couldn't load your media library. Check your connection and try again."}),f.jsx(En,{type:"button",variant:"outline",className:"h-9 rounded-xl px-3",onClick:()=>be(te=>te+1),children:"Retry"})]}):null,xt&&!Ae?f.jsx("div",{className:"mt-4 flex justify-center",children:f.jsx(En,{type:"button",variant:"outline",className:"h-10 rounded-xl px-4",disabled:pe,onClick:()=>{xs()},children:pe?"Loading...":"Load more"})}):null]}):f.jsxs("div",{className:"flex h-full min-h-[18rem] flex-col items-center justify-center px-6 text-center",children:[f.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-2xl bg-bolt-elements-background-depth-1 text-bolt-elements-textTertiary",children:f.jsx("div",{className:"i-ph:images text-2xl"})}),f.jsx("div",{className:"mt-4 text-base font-medium text-bolt-elements-textPrimary",children:oe.length>0?"No files match your filters":Tn?"No assets in this workspace yet":"No assets in your library yet"}),f.jsx("div",{className:"mt-2 max-w-md text-sm text-bolt-elements-textSecondary",children:oe.length>0?"Try a different search, category, or file type to find what you need.":Tn?"Upload images or generate media to start building your workspace media library.":"Upload images or generate media to start building your reusable asset library."}),oe.length===0?f.jsxs(En,{type:"button",variant:"outline",className:"mt-5 gap-2 rounded-xl",onClick:()=>{js()},disabled:ve||!t.assetWorkspaceId,children:[f.jsx("div",{className:"i-ph:upload-simple text-lg"}),f.jsx("span",{children:ve?"Uploading...":"Upload files"})]}):null]})}),f.jsx("div",{className:"mt-5 shrink-0 border-t border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 pt-4",children:f.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4",children:[f.jsx("div",{className:"text-sm text-bolt-elements-textSecondary",children:ie.length>0?`${ie.length} file${ie.length===1?"":"s"} selected`:Ae&&Ot.length===0?"Loading files...":Ae||pe?`${Ot.length} file${Ot.length===1?"":"s"} loaded`:`${Ot.length} file${Ot.length===1?"":"s"} shown`}),f.jsxs("div",{className:"flex w-full items-center gap-3 sm:w-auto
692sm:justify-end",children:[f.jsx(En,{type:"button",variant:"outline",onClick:()=>R(!1),className:"flex-1 sm:flex-none",children:"Cancel"}),f.jsx(En,{type:"button",disabled:ie.length===0||ee,onClick:()=>{Nr()},className:"flex-1 bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent hover:bg-bolt-elements-button-primary-backgroundHover sm:flex-none",children:ee?"Adding...":"Add"})]})]})})]})]})})})]})};function HJ({alert:t,clearAlert:e}){const{title:r,description:n,provider:s,errorType:i}=t,a=()=>{switch(i){case"authentication":return"i-ph:key-duotone";case"rate_limit":return"i-ph:clock-duotone";case"quota":return"i-ph:warning-circle-duotone";default:return"i-ph:warning-duotone"}},l=(()=>{if(t.type==="warning"&&!i&&n)return n;switch(i){case"authentication":return`Authentication failed with ${s}. Please check your API key.`;case"rate_limit":return`Rate limit exceeded for ${s}. Please wait before retrying.`;case"quota":return`Quota exceeded for ${s}. Please check your account limits.`;default:return"An error occurred while processing your request."}})();return f.jsx(Si,{children:f.jsx(ar.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3},className:"rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 mb-2",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx(ar.div,{className:"flex-shrink-0",initial:{scale:0},animate:{scale:1},transition:{delay:.2},children:f.jsx("div",{className:`${a()} text-xl text-bolt-elements-button-danger-text`})}),f.jsxs("div",{className:"ml-3 flex-1",children:[f.jsx(ar.h3,{initial:{opacity:0}
692,animate:{opacity:1},transition:{delay:.1},className:"text-sm font-medium text-bolt-elements-textPrimary",children:r}),f.jsxs(ar.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"mt-2 text-sm text-bolt-elements-textSecondary",children:[f.jsx("p",{children:l}),n&&n!==l&&f.jsxs("div",{className:"text-xs text-bolt-elements-textSecondary p-2 bg-bolt-elements-background-depth-3 rounded mt-4 mb-4",children:["Error Details: ",n]})]}),f.jsx(ar.div,{className:"mt-4",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.3},children:f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:e,className:ue("px-2 py-1.5 rounded-md text-sm font-medium","bg-bolt-elements-button-secondary-background","hover:bg-bolt-elements-button-secondary-backgroundHover","focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-bolt-elements-button-secondary-background","text-bolt-elements-button-secondary-text"),children:"Dismiss"}),f.jsx(h_,{params:{error_code:i||t.type},className:ue("px-2 py-1.5 rounded-md text-sm font-medium no-underline hover:no-underline","bg-bolt-elements-button-secondary-background","hover:bg-bolt-elements-button-secondary-backgroundHover","text-bolt-elements-button-secondary-text")})]})})]})]})})})}function UJ(t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>!n||typeof n!="object"||!("type"in n)?"":n.type==="text"&&"text"in n?String(n.text||""):"").join("");const r=t.parts;return Array.isArray(r)?r.map(n=>!n||typeof n!="object"||!("type"in n)?"":n.type==="text"&&"text"in n?String(n.text||""):"").join(""):""}function $N(t){return Array.isArray(t)&&t.includes("hidden")}function bA(t){return $N(t.annotations)?t:{...t,annotations:[...t.annotations||[],"hidden"]}}function E0(t){const e=t.trim().toLowerCase();return e?e.startsWith("*auto-repair this project error now.*")||e.startsWith("auto-repair this project error now.")||e.startsWith("auto-repair this project error now")||e.startsWith("*fix this preview error now.*")||e.startsWith("fix this preview error now.")||e.startsWith("*fix this terminal error now.*")||e.startsWith("fix this terminal error now.")||e.includes("you are repairing the current generated project in place.")||e.includes("you are repairing the generated project from the full diagnostics.")||e.includes("you are repairing the generated project from the full batched diagnostics."):!1}function xd(t){let e=!1;return t.map(r=>{const n=UJ(r);return r.role==="user"?(e=E0(n),e?bA(r):r):r.role==="assistant"&&e?bA(r):r})}function zJ(t,e){const r=xd(t);return e?.hideAssistantMessages?r.filter(n=>$N(n.annotations)?!1:n.role==="user"):r}function VJ(t){return t==="/"||t==="/app"||t==="/apps"||t.startsWith("/app/")||t.startsWith("/apps/")||t.startsWith("/builder")||t.startsWith("/builder-app")||t.startsWith("/chat/")||t.startsWith("/newsletter")}function vA(t){if(!(typeof window>"u")){if(VJ(window.location.pathname)){window.dispatchEvent(new Event(t));return}window.sessionStorage.setItem("cms:pending-menu-event",t),window.location.href="/builder-app"}}function GJ(t){return t?.cycleEndAt?new Intl.DateTimeFormat(void 0,{month:"numeric",day:"numeric",year:"2-digit"}).format(new Date(t.cycleEndAt)):"Billing cycle refresh pending"}function qJ(t){const e=t?.threshold.level;return e==="blocked"?{progress:"bg-rose-500",action:"text-rose-600 hover:text-rose-700"}:e==="warning"?{progress:"bg-amber-500",action:"text-amber-600 hover:text-amber-700"}:e==="notice"?{progress:"bg-sky-500",action:"text-sky-600 hover:text-sky-700"}:{progress:"bg-orange-500",action:"text-orange-600 hover:text-orange-700"}}function KJ(t){if(!t)return null;const e=t.plan;if(String(e?.status||"").trim().toLowerCase()==="active"&&(e.productType==="video_credits"||e.productType==="image_credits"||e.productType==="audio_credits"))return{name:e.name||e.code.replace(/_/g," "),productType:e.productType};const n=t.recentPayments.find(i=>String(i.transactionStatus||i.paymentStatus||"").trim().toLowerCase()==="completed");return!n||n.productType!=="video_credits"&&n.productType!=="image_credits"&&n.productType!=="audio_credits"?null:{name:XD(n.productC
692ode)?.name||n.productCode.replace(/_/g," "),productType:n.productType}}function YJ(t){const e=t.billingSummary?.plan,r=e?.status==="active"&&e.productType==="subscription",n=KJ(t.billingSummary),s=s_(t.summary);return{planName:n?.name||e?.name||s?.planName||t.summary?.planName||(t.loading?"Checking plan":"Basic"),helperLabel:n?`${n.productType==="video_credits"?"Video":n.productType==="audio_credits"?"Audio":"Image"} credits`:"CloudMySite plan"}}function XJ(){return f.jsxs("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4",children:[f.jsx("div",{className:"h-4 w-28 animate-pulse rounded bg-bolt-elements-background-depth-3"}),f.jsx("div",{className:"mt-4 h-2 w-full animate-pulse rounded-full bg-bolt-elements-background-depth-3"}),f.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3",children:[f.jsx("div",{className:"h-12 animate-pulse rounded-xl bg-bolt-elements-background-depth-3"}),f.jsx("div",{className:"h-12 animate-pulse rounded-xl bg-bolt-elements-background-depth-3"})]})]})}function qu(t){return f.jsxs("button",{type:"button",className:"flex w-full items-center gap-3 rounded-2xl bg-[#ececf1] px-4 py-3 text-left text-sm text-slate-900 transition-colors hover:bg-[#e3e4ea] dark:bg-[#2a2d33] dark:text-white dark:hover:bg-[#343841]",onClick:t.onClick,children:[f.jsx("span",{className:ue(t.icon,"text-base text-slate-500 dark:text-slate-300")}),f.jsx("span",{children:t.label})]})}function JJ({email:t,fallbackName:e}){const r=t||e||"Signed in";return f.jsx("div",{className:"mt-3 rounded-2xl border border-bolt-elements-borderColor bg-[#ffffff] px-4 py-3 dark:bg-[#171717]",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-[#ececf1] text-slate-500 dark:bg-[#2a2a2a] dark:text-slate-300",children:f.jsx("span",{className:"i-ph:user-circle text-lg"})}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-[11px] font-medium uppercase tracking-[0.12em] text-slate-500 dark:text-slate-300",children:"Signed in"}),f.jsx("div",{className:"truncate text-sm font-semibold text-slate-950 dark:text-white",title:r,children:r})]})]})})}function QJ({productType:t,workspaceName:e,workspaceSubtitle:r,trigger:n}){const[s,i]=x.useState(!1),a=We(On),{summary:o,loading:l,refresh:c}=lE(t,{details:!1,enabled:!0,sync:!0}),{summary:u,refresh:d}=IO({enabled:!!a?.email}),h=qJ(o),m=s_(o),b=m?.usagePercent??o?.threshold.percent??0,g=YJ({billingSummary:u,loading:l,summary:o});x.useEffect(()=>{s&&(c(t),d())},[s,t,c,d]);const p=A=>{i(!1),A()},y=()=>{p(()=>vA("cms:open-workspace-upgrade"))},v=()=>{p(()=>vA("cms:open-settings-panel"))},_=()=>{p(()=>{typeof window<"u"&&window.open(NO,"_blank","noopener,noreferrer")})},w=()=>{p(()=>{typeof window<"u"&&window.open(LO,"_blank","noopener,noreferrer")})},C=()=>{p(()=>{tE().then(()=>{typeof window<"u"&&(window.location.href="/login")})})};return f.jsxs(kN,{open:s,onOpenChange:i,children:[f.jsx(PN,{asChild:!0,children:n}),f.jsx(TN,{children:f.jsxs(RN,{side:"bottom",align:"start",sideOffset:10,className:"z-workbench w-[320px] rounded-2xl border border-bolt-elements-borderColor bg-[rgba(255,255,255,0.98)] p-3 text-slate-950 shadow-2xl backdrop-blur-xl dark:bg-[rgba(18,24,32,0.98)] dark:text-white",children:[f.jsxs("div",{className:"flex items-start justify-between gap-3 px-1 py-1",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"truncate text-sm font-semibold",children:e}),f.jsx("div",{className:"truncate text-xs text-slate-600 dark:text-slate-300",children:r})]}),f.jsx("button",{type:"button",className:"flex h-8 w-8 items-center justify-center rounded-xl bg-[#ececf1] text-slate-500 transition-colors hover:bg-[#e3e4ea] hover:text-slate-900 dark:bg-[#f3f4f7] dark:text-slate-500 dark:hover:bg-white dark:hover:text-slate-700","aria-label":"Close workspace menu",onClick:()=>i(!1),children:f.jsx("span",{className:"i-ph:x text-base"})})]}),f.jsx("div",{className:"mt-2",children:l&&!o?f.jsx(XJ,{}):o?f.jsxs("div",{className:"rounded-2xl border border-bolt-elements-borderColor bg-[#ffffff] p-4 dark:bg-[#171717]",children:[f.jsxs("div",{className:"flex items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-sm font-medium",children:g.planName}),f.jsx("div",{className:"text-xs text-slate-500 dark:text-slate-300",children:g.helperLabel})]}),f.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[f.jsx("span",{children:aE(m?.usedTokens||o.monthlyTokensUsed,m?.totalTokens||o.monthlyTokenLimit)}),f.jsx("span",{className:"text-xs font-medium text-slate-500 dark:text-slate-300",children:n_(b)})]})]}),u?f.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-3",children:[f.jsxs("div",{className:"rounded-xl bg-[#ececf1] px-3 py-2 dark:bg-[#2a2a2a]",children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-slate-500 dark:text-slate-300",children:"Images"}),f.jsx("div",{className:"mt-1 text-sm font-semibold",children:u.credits.imageCredits.toLocaleStr
692ing()})]}),f.jsxs("div",{className:"rounded-xl bg-[#ececf1] px-3 py-2 dark:bg-[#2a2a2a]",children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-slate-500 dark:text-slate-300",children:"Videos"}),f.jsx("div",{className:"mt-1 text-sm font-semibold",children:u.credits.videoCredits.toLocaleString()})]})]}):null,f.jsx("div",{className:"mt-3 h-2 overflow-hidden rounded-full bg-black/8 dark:bg-white/8",children:f.jsx("div",{className:ue("h-full rounded-full transition-[width] duration-300",h.progress),style:{width:`${b}%`}})}),f.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3",children:[f.jsxs("div",{className:"rounded-xl bg-[#ececf1] px-3 py-2 dark:bg-[#2a2a2a]",children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-slate-500 dark:text-slate-300",children:"Tokens used"}),f.jsx("div",{className:"mt-1 text-lg font-semibold",children:Yl(m?.usedTokens||o.monthlyTokensUsed)})]}),f.jsxs("div",{className:"rounded-xl bg-[#ececf1] px-3 py-2 dark:bg-[#2a2a2a]",children:[f.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-slate-500 dark:text-slate-300",children:"Balance"}),f.jsx("div",{className:"mt-1 text-lg font-semibold",children:Yl(m?.remainingTokens||o.monthlyTokensRemaining)})]})]}),f.jsxs("div",{className:"mt-4 text-xs text-slate-600 dark:text-slate-300",children:["Total ",Yl(m?.totalTokens||o.monthlyTokenLimit),f.jsx("span",{className:"mx-1.5 inline-block h-1 w-1 rounded-full bg-slate-400/80 align-middle dark:bg-slate-300/70"}),m?`Resets ${m.cycleEnd}`:`Resets ${GJ(o)}`]}),f.jsx("button",{type:"button",className:ue("mt-3 text-sm font-semibold transition-colors",h.action),onClick:y,children:"Upgrade your plan"})]}):f.jsx("div",{className:"rounded-2xl border border-dashed border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-4 py-5 text-sm text-bolt-elements-textSecondary",children:"Token usage will appear here once your plan data is available."})}),a&&f.jsx(JJ,{email:a.email,fallbackName:a.username}),f.jsxs("div",{className:"mt-3 space-y-1",children:[f.jsx(qu,{icon:"i-ph:gear",label:"Settings",onClick:v}),f.jsx(qu,{icon:"i-ph:credit-card",label:"Pricing plans",onClick:y}),f.jsx(qu,{icon:"i-ph:lifebuoy",label:"Help Center",onClick:_}),f.jsx(qu,{icon:"i-ph:envelope-simple",label:"Contact Support",onClick:w}),a&&f.jsx(qu,{icon:"i-ph:sign-out",label:"Logout",onClick:C})]}),f.jsx(IN,{className:"fill-[rgba(255,255,255,0.96)] dark:fill-[rgba(18,24,32,0.96)]"})]})})]})}const ZJ=_t.lazy(()=>H(()=>Promise.resolve().then(()=>oX),void 0).then(t=>({default:t.Markdown}))),eQ=96,Rf=_t.lazy(()=>H(()=>Promise.resolve().then(()=>vG),void 0).then(t=>({default:t.ProgressPanel}))),tQ=oh({}),rQ=["imported-files","starter-template-files"],nQ="home",sQ=["Planning the workspace","Writing app files","Checking the app structure","Preparing the live preview"],iQ=["Reviewing your update","Updating app files","Checking the changes","Preparing the live preview"],oQ=["Planning the campaign","Writing email-safe HTML","Checking newsletter content","Preparing the email preview"],aQ=["Reviewing your update","Updating the campaign draft","Checking newsletter content","Preparing the email preview"];function Ku(t){return t?t.type!=="runtime"&&!rQ.some(e=>String(t.id||"").toLowerCase().startsWith(e)):!1}function yA(t){const e=t?.runner?.actions?.get?.();return!e||typeof e!="object"?0:Object.keys(e).length}function lQ(t){return new URLSearchParams(t).get(nQ)==="1"}function cQ(t){const e=Array.isArray(t)?t:[];for(let r=e.length-1;r>=0;r--){const n=e[r]?.annotations,s=Array.isArray(n)?n:[];for(let i=s.length-1;i>=0;i--){const a=s[i];if(!(!a||typeof a!="object"||!("type"in a))&&a.type==="usageSummary")return a}}return null}const uQ=new Set(["my app","my website","my workspace","website","site","app","untitled","untitled app","untitled project","create initial files","imported files"]),dQ=[{matcher:/(game|arcade|quiz|play|vibe|puzzle|invader|fun)/i,theme:{icon:"i-ph:game-controller-duotone",iconClassName:"bg-violet-500/15 text-violet-400",subtitle:"Game Workspace"}},{matcher:/(shop|store|e-?commerce|cart|product|retail)/i,theme:{icon:"i-ph:shopping-bag-open-duotone",iconClassName:"bg-rose-500/15 text-rose-400",subtitle:"Commerce Workspace"}},{matcher:/(blog|article|content|news|writer|seo)/i,theme:{icon:"i-ph:note-pencil-duotone",iconClassName:"bg-amber-500/15 text-amber-400",subtitle:"Content Worksp
692ace"}},{matcher:/(finance|bank|stock|crypto|invest|accounting|tax)/i,theme:{icon:"i-ph:chart-line-up-duotone",iconClassName:"bg-emerald-500/15 text-emerald-400",subtitle:"Finance Workspace"}},{matcher:/(health|medical|clinic|doctor|fitness|wellness)/i,theme:{icon:"i-ph:heartbeat-duotone",iconClassName:"bg-red-500/15 text-red-400",subtitle:"Health Workspace"}},{matcher:/(school|education|course|learning|academy|student)/i,theme:{icon:"i-ph:graduation-cap-duotone",iconClassName:"bg-indigo-500/15 text-indigo-400",subtitle:"Education Workspace"}},{matcher:/(travel|tour|trip|hotel|flight|vacation)/i,theme:{icon:"i-ph:airplane-tilt-duotone",iconClassName:"bg-sky-500/15 text-sky-400",subtitle:"Travel Workspace"}},{matcher:/(music|audio|podcast|radio|dj|song)/i,theme:{icon:"i-ph:music-notes-duotone",iconClassName:"bg-pink-500/15 text-pink-400",subtitle:"Audio Workspace"}}],_A=[{icon:"i-ph:sparkle-duotone",iconClassName:"bg-fuchsia-500/15 text-fuchsia-400",subtitle:"Creative Workspace"},{icon:"i-ph:rocket-launch-duotone",iconClassName:"bg-blue-500/15 text-blue-400",subtitle:"Launch Workspace"},{icon:"i-ph:compass-duotone",iconClassName:"bg-teal-500/15 text-teal-400",subtitle:"Discovery Workspace"},{icon:"i-ph:planet-duotone",iconClassName:"bg-cyan-500/15 text-cyan-400",subtitle:"Explorer Workspace"},{icon:"i-ph:palette-duotone",iconClassName:"bg-orange-500/15 text-orange-400",subtitle:"Design Workspace"}];function hQ(t){return(t||"").trim().toLowerCase().replace(/\s+/g," ")}function xA(t){return uQ.has(hQ(t))}function fQ(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function wA(t){const e=lm(t||"");return C0(e||t||"").replace(/^\s*\[Model:[^\]]+\]\s*/i,"").replace(/^\s*\[Provider:[^\]]+\]\s*/i,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function BN(t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>!n||typeof n!="object"||!("type"in n)?"":n.type==="text"&&"text"in n?String(n.text||""):"").join(" ");const r=t.parts;return Array.isArray(r)?r.map(n=>!n||typeof n!="object"||!("type"in n)?"":n.type==="text"&&"text"in n?String(n.text||""):"").join(" "):""}function pQ(t){const e=t.userVisibleContent;return typeof e=="string"?e:BN(t)}function Hy(t){if(!t)return;const e=pQ(t),r=lm(e),n=S0(C0(r||e)).replace(/\n{3,}/g,` 693 694`).trim();if(n)return n}function mQ(t){if(!t||t.role!=="user"||t.annotations?.includes("hidden"))return!1;if(gE(t).length>0||Hy(t))return!0;const e=t.content;if(Array.isArray(e)&&e.some(s=>{if(!s||typeof s!="object"||!("type"in s))return!1;const i=s;return i.type==="image"&&!!i.image||i.type==="file"&&!!i.data}))return!0;const r=t.parts;return Array.isArray(r)?r.some(n=>{if(!n||typeof n!="object"||!("type"in n))return!1;const s=n;return s.type==="file"&&!!s.data}):!1}function gQ(t,e){const r=wA(t);let n=xA(r)?"":r;if(!n&&Array.isArray(e))for(const o of e){if(o.role!=="user")continue;const l=wA(typeof o.content=="string"?o.content:"");if(!(!l||xA(l))){n=l;break}}if(!n)return"My Workspace";const i=n.replace(/^\s*(create|build|design|make|generate|develop)\b[:\s-]*/i,"").replace(/\b(a|an|the)\b/gi," ").replace(/\s+/g," ").trim()||n,a=fQ(i.split(" ").slice(0,4).join(" ").trim());return a.length<=40?a:`${a.slice(0,37).trimEnd()}...`}function bQ(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return Math.abs(e)}function vQ(t){for(const r of dQ)if(r.matcher.test(t))return r.theme;const e=bQ(t||"workspace")%_A.length;return _A[e]}const yQ=_t.forwardRef(({textareaRef:t,showChat:e=!0,chatStarted:r=!1,isStreaming:n=!1,onStreamingChange:s,awaitingResponse:i=!1,awaitingResponseSeconds:a=0,awaitingResponseLabel:o="Genie is working on your request and preparing your website.",isFollowUpRequest:l=!1,showResumeGeneration:c=!1,onResumeGeneration:u,model:d,setModel:h,input:m="",enhancingPrompt:b,handleInputChange:g,activePlanId:p=null,dreamWeaverToken:y=null,enhancePrompt:v,sendMessage:_,handleStop:w,importChat:C,exportChat:A,uploadedFiles:E=[],imageDataList:S=[],handleImageFilesSelected:k,handleExistingAssetSelected:O,removeImageAttachment:T,clearImageAttachments:R,assetWorkspaceId:N,assetLibraryWorkspaceId:M,readOnlyReason:B,messages:U,description:X,actionAlert:oe,clearAlert:L,deployAlert:F,clearDeployAlert:V,llmErrorAlert:Z,clearLlmErrorAlert:K,promptQualification:ie,promptQualificationBusy:se=!1,promptQualificationError:fe,onUsePromptQualificationDefaults:Y,applyPromptQualificationSuggestion:I,str
694ipeSetupRequired:z=!1,openStripeSetup:q,dismissStripeSetup:ae,data:ee,chatMode:le,setChatMode:ve,append:ye,designScheme:Ae,setDesignScheme:we,selectedElement:pe,setSelectedElement:Ye,addToolResult:ft=()=>{throw new Error("addToolResult not implemented")},metadata:pt,updateChatMestaData:Lt,buildJob:nt,onCancelBuild:xt},ct)=>{const _r=nE(),ht=r?400:260,[Pe,be]=x.useState(!1),[Te,Ne]=x.useState(null),[Fe,Fr]=x.useState(""),Jr=We(U1),[Dt,Yt]=x.useState(!1),[Os,ci]=x.useState(0),[Yn,$n]=x.useState(!1),[lt,bs]=x.useState(null),wn=x.useRef(null),Bn=x.useRef(!1),an=x.useRef(!1),vs=x.useRef(""),ys=x.useRef(g),Fn=x.useRef(B),Ir=x.useRef(t),Wn=x.useRef(null),Hn=x.useRef(null),is=We(On),rn=typeof window<"u"?window.location.pathname:"",Jt=rn.startsWith("/newsletter"),xr=typeof window<"u"&&(rn.startsWith("/builder")||rn.startsWith("/builder-app")),Mt=typeof window<"u"&&(rn==="/"||rn==="/app"||rn==="/apps"||rn.startsWith("/app/")||rn.startsWith("/apps/")||rn.startsWith("/builder")||rn.startsWith("/builder-app")||rn.startsWith("/chat/")||rn==="/newsletter"||rn.startsWith("/newsletter/"));x.useEffect(()=>{ys.current=g,Fn.current=B,Ir.current=t},[g,B,t]);const Gs=p!==null?{activePlanId:p}:y!==null?{dreamWeaverToken:y}:{};x.useEffect(()=>{(async()=>{try{await Fl("/api/check-auth",{method:"GET"}),await rv(),bs(!0)}catch{bs(!1)}})()},[]),x.useRef(null);const[ir,Ai]=x.useState(!0),Xn=x.useMemo(()=>{const ge=gQ(X,U);return Jt?Ad(X||ge,N).workspaceTitle:ge},[N,X,Jt,U]),os=`${r?"started":"landing"}:${is?.email||"guest"}:${Jt?"newsletter":xr?"builder":"app"}`,[Ur,ui]=x.useState("desktop"),[nn,St]=x.useState(!1),[Ei,Tn]=x.useState(null);x.useEffect(()=>{const ge=()=>{const Ue=window.scrollY<50;Ai(Ue)};return window.addEventListener("scroll",ge),()=>window.removeEventListener("scroll",ge)},[]),x.useEffect(()=>{Jr&&Yt(!0)},[Jr]);const{historyRestoring:fr,aborted:Sn,backgroundHomeActive:kr,backgroundHomeReturnPath:Ot}=We(Ve),Or=kr&&typeof window<"u"&&window.location.pathname==="/",zr=typeof window<"u"&&Mt&&lQ(window.location.search),Pr=Or;x.useEffect(()=>{!kr||typeof document>"u"||document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[kr]),x.useCallback(()=>{Ve.setKey("backgroundHomeActive",!1);const ge=Ot||window.location.pathname||"/";typeof window<"u"&&ge!==window.location.pathname&&_r(ge)},[Ot,_r]);const as=x.useMemo(()=>Sn||!ee?[]:ee.filter(ge=>typeof ge=="object"&&ge.type==="progress"),[Sn,ee]),jt=Mt&&r&&!(se||!!ie),_s=!!(ie&&ie.status!=="ready"&&!jt),Rn=_s?48:eQ,jr=We(j.artifacts),wr=We(j.activeProgressMessageId),In=We(j.ignoredProgressMessageIds),Xt=We(j.restoreProgress),ur=We(j.frozenProgress),di=We(j.previews),ls=We(j.builderLifecyclePhase),ln=x.useMemo(()=>xd(U||[]),[U]),Gr=x.useMemo(()=>new Set(ln.filter(ge=>ge.annotations?.includes("hidden")).map(ge=>ge.id)),[ln]),Bi=x.useMemo(()=>{const ge=zJ(U||[],{hideAssistantMessages:jt});return Jt?ge.filter(Ue=>Ue.role!=="assistant"?!0:!JM(BN(Ue))):ge},[Jt,U,jt]),br=x.useMemo(()=>Jt?QM(U||[]):null,[Jt,U]),Tr=x.useMemo(()=>br?ZM(br.html):null,[br]);x.useEffect(()=>{Tn(null)},[br]);const Vt=x.useMemo(()=>Object.entries(jr).filter(([ge,Ue])=>{const er=yA(Ue)>0,Ct=!!wr&&ge===wr;return!In.has(ge)&&!Gr.has(ge)&&Ku(Ue)&&(er||Ct)}).map(([ge])=>ge),[wr,Gr,In,jr]),Qr=x.useMemo(()=>{if(Vt.length===0)return[];const ge=new Set(Vt),Ue=new Set,er=[];for(const Ct of U||[])!ge.has(Ct.id)||Ue.has(Ct.id)||(Ue.add(Ct.id),er.push(Ct.id));for(const Ct of Vt)Ue.has(Ct)||(Ue.add(Ct),er.push(Ct));return er},[Vt,U]),Ar=x.useMemo(()=>{if(Qr.length===0)return[];const ge=new Set(Qr),Ue=[],er=new Set;let Ct;for(const nr of ln)if(!nr.annotations?.includes("hidden")){if(nr.role==="user"){Ct=nr;continue}!ge.has(nr.id)||er.has(nr.id)||(er.add(nr.id),Ue.push({messageId:nr.id,promptMessage:Ct,promptPreview:Hy(Ct)}))}for(const nr of Qr)er.has(nr)||Gr.has(nr)||!wr||nr!==wr||(er.add(nr),Ue.push({messageId:nr}));return Ue.map((nr,Cn)=>{const Ti=Ue[Cn-1]?.promptMessage?.id,Un=nr.promptMessage?.id;return Un&&Un===Ti?{...nr,promptMessage:void 0,promptPreview:void 0}:nr})},[wr,Gr,ln,Qr]),cs=x.useMemo(()=>{if(Ar.length<=1)return Ar;if(wr){const ge=Ar.find(Ue=>Ue.messageId===wr);if(ge)return[ge]}return Ar.slice(-1)},[wr,Ar]),Ut=x.useMemo(()=>
694{if(wr)return Ar.find(ge=>ge.messageId===wr)||cs.find(ge=>ge.messageId===wr)},[wr,cs,Ar]),xs=x.useMemo(()=>Qr.slice().reverse().find(ge=>{const Ue=jr[ge];return!In.has(ge)&&Ku(Ue)&&yA(Ue)>0}),[In,jr,Qr]),Nr=x.useMemo(()=>{const ge=wr?jr[wr]:void 0;return!!ge&&!In.has(wr||"")&&Ku(ge)?wr:!!ur?.messageId&&ur.actions.length>0&&!In.has(ur.messageId)&&!Gr.has(ur.messageId)?ur?.messageId:xs||Object.entries(jr).filter(([Ct,nr])=>!In.has(Ct)&&Ku(nr)).map(([Ct])=>Ct).slice(-1)[0]||void 0},[wr,ur?.actions.length,ur?.messageId,Gr,In,xs,jr]),js=x.useMemo(()=>{if(!Nr)return;const ge=Ar.find(er=>er.messageId===Nr),Ue=Ut||cs.slice(-1)[0]||Ar.slice(-1)[0];return ge||(Ue?{...Ue,messageId:Nr}:{messageId:Nr})},[Ut,Nr,cs,Ar]),pn=x.useMemo(()=>js?[js]:Ar.length<=1?Ar:cs,[js,cs,Ar]),te=x.useMemo(()=>new Set(pn.map(ge=>ge.promptMessage?.id).filter(ge=>typeof ge=="string"&&ge.length>0)),[pn]),De=x.useMemo(()=>Bi.filter(ge=>!te.has(ge.id)&&mQ(ge)),[te,Bi]),je=x.useMemo(()=>Nr?jr[Nr]:void 0,[Nr,jr]),Ge=x.useMemo(()=>[Qr[0]?jr[Qr[0]]:void 0,j.firstArtifact,...Object.values(jr)].find(Ue=>Ku(Ue)),[jr,Qr]),$t=x.useMemo(()=>Jt?Ad(pt?.workspaceTitle||X||Xn,N):null,[N,X,Jt,pt?.workspaceTitle,Xn]),qe=x.useMemo(()=>{const ge=Jt&&$t?pt?.primaryArtifactId||$t.primaryArtifactId:pt?.primaryArtifactId,Ue=Jt&&$t&&pt?.workspaceTitle?.includes("[CloudMySite Newsletter")?$t.workspaceTitle:pt?.workspaceTitle;return m_({persistedPrimaryArtifactId:ge,persistedWorkspaceTitle:Ue,originalArtifact:Ge,fallbackTitle:Xn})},[Jt,pt?.primaryArtifactId,pt?.workspaceTitle,$t,Ge,Xn]),Bt=x.useMemo(()=>Jt?{icon:"i-ph:envelope-simple-duotone",iconClassName:"bg-sky-500/15 text-sky-500",subtitle:"Newsletter Workspace"}:vQ(`${qe} ${X||""}`.trim()),[X,Jt,qe]),Lr=x.useMemo(()=>Zl(je?.runner.actions??tQ,ge=>Object.values(ge)),[je]),Nn=We(Lr),Ln=jt&&Nn.some(ge=>ge.status==="pending"||ge.status==="running"&&ge.type!=="start"),qs=n||i||se||Ln,Sr=qs||Yn;x.useEffect(()=>{if(Bn.current=qs,qs){an.current=!0;return}Yn&&an.current&&(an.current=!1,$n(!1))},[Yn,qs]);const or=Sr&&(Nr||pn.length>0)?Ut?.messageId||Nr||pn.slice(-1)[0]?.messageId:void 0,Ks=x.useMemo(()=>!!Nr&&pn.some(ge=>ge.messageId===Nr),[Nr,pn]),Ys=Sr&&Nr&&!Ks?Nr:void 0,Vr=nt?.requestMode==="update"||!nt&&l,Xs=x.useMemo(()=>di.filter(ge=>ge.ready).length,[di]),ki=nt?.status==="failed",ws=nt?.status==="canceled",Dn=ki||ws,Fi=!Dn&&(nt?.previewReady||Xs>0),G=!Dn&&Fi&&(nt?.status==="ready"||ls==="PREVIEW_RUNNING"),xe=ki?"Build failed":ws?"Build canceled":G?Jt?"Newsletter draft ready":Fi?xr?"Site ready":"App ready":"Build ready":Vr?Jt?"Updating your newsletter campaign":"Updating your app":Jt?"Working on newsletter":"Working on app",Je=Jt?"Email preview is ready":Fi?"Live preview is ready":"Opening live preview",It=x.useMemo(()=>{if(Dn)return[String(nt?.error||"").trim()||(ws?"The request was canceled before the preview was ready.":"The app could not be generated. Please retry the prompt.")];if(G)return[Je];const ge=Jt?Vr?aQ:oQ:Vr?iQ:sQ,Ue=String(nt?.currentStep||"").trim();return Ue?[Ue,...ge.filter(er=>er.toLowerCase()!==Ue.toLowerCase())]:ge},[nt?.currentStep,nt?.error,Jt,ws,G,Dn,Vr,Je]),wt=It[Os%It.length]||xe,Gt=x.useMemo(()=>{if(De.length!==0&&!(!Sr&&pn.length===0))return De[De.length-1]},[Sr,pn.length,De]),Qt=x.useMemo(()=>Gt?De.filter(ge=>ge.id!==Gt.id):De,[Gt,De]),Nt=x.useMemo(()=>Gt?pn.filter(ge=>ge.promptMessage?.id===Gt.id||wr&&ge.messageId===wr?!0:ur?.messageId===ge.messageId):pn,[wr,ur?.messageId,pn,Gt]),pr=x.useMemo(()=>!!Xt?.some(ge=>ge.status==="running"||ge.status==="pending"),[Xt]),Ft=Nt.length>0||!!Ys,ot=jt&&(fr||pr&&!Ft),qt=!ot&&Nt.length===0&&!!Ys,Zt=!ot&&(Nt.length>0||qt),mn=ot||Zt,cn=jt&&Sr&&!mn&&!G,Ss=jt&&G&&!mn,Js=jt&&Dn&&!mn,ro=(cn||Ss||Js)&&!!Gt,Wi=Hy(Gt);x.useEffect(()=>{if(!cn){ci(0);return}const ge=window.setInterval(()=>{ci(Ue=>Ue+1)},2200);return()=>{window.clearInterval(ge)}},[cn]);const rr=()=>f.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx("div",{className:"p-4",children:f.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-3",children:[f.jsx("div",{className:ue("mt-0.5",Dn?"i-ph:warning-circle-fill text-red-500":G?"i-ph:check-circle-fill text-emerald-500":"i-svg-spinners:90-ring-with-bg text-bolt-elements-item-contentAccent")}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("div",{className:"text-sm font-medium text-bolt-elements-textPrimary",children:xe}),f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary transition-opacity duration-300",children:wt}),!G&&!Dn&&f.jsx("div",{className:"mt-3 flex items-center gap-1.5","aria-hidden":"true",children:It.slice(0,4).map((ge,Ue)=>
694f.jsx("div",{className:ue("h-1.5 rounded-full transition-all duration-300",Ue===Os%Math.min(It.length,4)?"w-6 bg-bolt-elements-item-contentAccent":"w-1.5 bg-bolt-elements-borderColor")},ge))}),!G&&!Dn&&a>=12&&f.jsx("div",{className:"mt-2 text-[11px] text-bolt-elements-textTertiary",children:"Still working through the request."})]})]})})}),Dr=ge=>f.jsxs("div",{className:"rounded-xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-4 py-3",children:[f.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-bolt-elements-textTertiary",children:"Request"}),f.jsx("div",{className:"mt-2 text-sm text-bolt-elements-textPrimary",children:f.jsx(Ml,{fallback:f.jsx("div",{className:"whitespace-pre-wrap",children:ge}),children:()=>f.jsx(x.Suspense,{fallback:f.jsx("div",{className:"whitespace-pre-wrap",children:ge}),children:f.jsx(ZJ,{children:ge})})})})]});x.useEffect(()=>{wn.current!==Sr&&(wn.current=Sr,s?.(Sr))},[Sr,s]),x.useEffect(()=>{if(!jt)return;const ge=Wn.current,Ue=Hn.current;if(!ge||!Ue||!Sr&&!Gt&&Nt.length===0&&!ot)return;const er=window.requestAnimationFrame(()=>{Ue.scrollIntoView({block:"end",behavior:Sr?"smooth":"auto"})});return()=>{window.cancelAnimationFrame(er)}},[Sr,Nr,ot,Nt.length,Gt?.id,jt]);const wa=x.useCallback(ge=>{const Ue=String(ge||"").trim();if(!Ue)return;const Ct=[vs.current.trim(),Ue].filter(Boolean).join(" ");Fr(Ue);const nr=ys.current;!Fn.current&&nr&&nr({target:{value:Ct},currentTarget:{value:Ct}}),requestAnimationFrame(()=>{Ir.current?.current?.focus({preventScroll:!0}),Ir.current?.current?.setSelectionRange(Ct.length,Ct.length)})},[]);x.useEffect(()=>{if(typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)){const ge=window.SpeechRecognition||window.webkitSpeechRecognition,Ue=new ge;return Ue.continuous=!0,Ue.interimResults=!0,Ue.lang=navigator.language||"en-US",Ue.onresult=er=>{const Ct=Array.from(er.results).map(nr=>nr[0]).map(nr=>nr.transcript).join("");wa(Ct)},Ue.onerror=er=>{const Ct=String(er.error||"");be(!1),Ct!=="aborted"&&(console.error("Speech recognition error:",Ct),Ct!=="no-speech"&&Se.error("Voice input stopped. Please check microphone access and try again."))},Ue.onend=()=>{be(!1)},Ne(Ue),()=>{Ue.abort()}}},[wa]);const Sa=()=>{if(B){Se.info(B);return}if(!Pe){if(Te){try{vs.current=m.trim(),Te.start(),be(!0)}catch(ge){console.error("Unable to start speech recognition:",ge),be(!1),Se.error("Voice input is unavailable right now.")}return}Se.info("Voice input is not supported in this browser. Try Chrome or Edge for speech to text.")}},Ca=()=>{if(Te)try{Te.stop()}catch(ge){console.error("Unable to stop speech recognition:",ge)}finally{be(!1)}},Qs=(ge,Ue,er)=>{if(Sr||B||!_){B&&Se.info(B);return}$n(!0),an.current=!1;try{const Ct=_(ge,Ue,er);
694Promise.resolve(Ct).catch(nr=>{console.error("Failed to submit chat message",nr)}).finally(()=>{window.setTimeout(()=>{!Bn.current&&!an.current&&$n(!1)},250)}),Ye?.(null),Te&&(Te.abort(),Fr(""),be(!1),g&&g({target:{value:""}}))}catch(Ct){$n(!1),console.error("Failed to submit chat message",Ct)}},Aa=async()=>{if(!br){Se.info("Generate a newsletter draft first.");return}if(!nn){St(!0);try{const ge=lp(void 0,pt?.newsletterContext),Ue=ge?.workspace_id||"",er=ge?.publication_id||"",Ct=ge?.return_url||"",nr=await Fl("/api/newsletter/account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:Ue||void 0,newsletterContext:ge?.newsletterContext||{workspace_id:Ue||void 0,publication_id:er||void 0,return_url:Ct||void 0},newsletterDraft:br})}),Cn=await nr.json().catch(()=>({}));if(!nr.ok||!Cn?.success)throw new Error(Cn?.message||"Unable to save this campaign to Newsletter.");const Ti=String(Cn.campaignId||"").trim();if(!Ti)throw new Error("Newsletter saved the draft but did not return a campaign id.");const Un={campaignId:Ti,accountId:Cn.accountId,publicationId:Cn.publicationId,editUrl:Cn.editUrl,dashboardUrl:Cn.dashboardUrl,savedAt:new Date().toISOString(),storageSaved:!!Cn.storageSaved,storageWarning:Cn.storageWarning||null};Tn(Un),await Lt?.({...pt||{},workspaceTitle:br.title,newsletterContext:ge?.newsletterContext||pt?.newsletterContext,newsletterCampaignDraft:br,newsletterCampaignSave:Un,newsletterStatus:"saved_to_newsletter",newsletterPublicationName:Cn.publicationName||ge?.publication_name||ge?.workspace_name||pt?.newsletterPublicationName||null,historyStatusOverride:"draft"}),Cn.storageWarning?Se.warn(`Campaign saved, but storage returned: ${Cn.storageWarning}`):Se.success("Saved to Newsletter as a campaign draft.");const so=Cn.editUrl||Cn.dashboardUrl;so&&typeof window<"u"&&window.open(so,"_blank","noopener,noreferrer")}catch(ge){const Ue=ge instanceof Error?ge.message:"Unable to save this campaign to Newsletter.";Se.error(Ue)}finally{St(!1)}}},pl=async ge=>{const Ue=ge.filter(er=>er.type.startsWith("image/")||er.type.startsWith("video/")||er.type.startsWith("audio/"));Ue.length!==0&&await k?.(Ue)},dc=()=>{const ge=document.createElement("input");ge.type="file",ge.accept="image/*,video/*,audio/*",ge.multiple=!0,ge.onchange=async Ue=>{const er=Array.from(Ue.target.files||[]);if(er.length>0)try{await pl(er)}catch(Ct){console.error("Failed to attach uploaded media",Ct),Se.error("Failed to upload that media.")}},ge.click()},us=async ge=>{const Ue=ge.clipboardData?.items;if(!Ue)return;const er=Array.from(Ue).filter(Ct=>Ct.type.startsWith("image/")).map(Ct=>Ct.getAsFile()).filter(Ct=>!!Ct);if(er.length>0){ge.preventDefault();try{await pl(er)}catch(Ct){console.error("Failed to attach pasted images",Ct),Se.error("Failed to upload the pasted image.")}}},Uo=Jt&&br&&f.jsx("div",{className:"modern-scrollbar flex h-full w-full flex-col overflow-auto bg-bolt-elements-background-depth-1 p-4",children:f.jsxs("div",{className:"mx-auto flex w-full max-w-[900px] flex-col gap-4 roun
694ded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 p-4 shadow-sm sm:p-5",children:[f.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-bolt-elements-textSecondary",children:"Newsletter draft"}),f.jsx("h3",{className:"mt-1 truncate text-xl font-semibold text-bolt-elements-textPrimary",children:br.title}),f.jsxs("div",{className:"mt-2 text-sm text-bolt-elements-textSecondary",children:[f.jsx("span",{className:"font-medium text-bolt-elements-textPrimary",children:"Subject:"})," ",br.subject]}),f.jsxs("div",{className:"mt-1 text-sm text-bolt-elements-textSecondary",children:[f.jsx("span",{className:"font-medium text-bolt-elements-textPrimary",children:"Preview:"})," ",br.preview_text]})]}),f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Tr?f.jsxs("span",{className:ue("inline-flex min-h-9 items-center gap-1 rounded-lg border px-3 text-xs font-semibold",Tr.safe?"border-emerald-200 bg-emerald-50 text-emerald-700":"border-amber-200 bg-amber-50 text-amber-700"),children:[f.jsx("span",{className:Tr.safe?"i-ph:check-circle":"i-ph:warning-circle"}),Tr.safe?"Email safe":"Review HTML"]}):null,f.jsxs("button",{type:"button",className:"inline-flex min-h-9 items-center gap-2 rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 px-3 text-xs font-semibold text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 disabled:cursor-not-allowed disabled:opacity-60",disabled:nn,onClick:()=>{Aa()},children:[f.jsx("span",{className:ue(nn?"i-ph:circle-notch animate-spin":"i-ph:floppy-disk","text-base")}),f.jsx("span",{children:nn?"Saving...":"Save to Newsletter"})]})]})]}),f.jsx("div",{className:"flex flex-wrap gap-2",children:[["desktop","Desktop email preview"],["mobile","Mobile email preview"],["html","Raw HTML"],["text","Plain text"]].map(([ge,Ue])=>f.jsx("button",{type:"button",className:ue("min-h-9 rounded-lg border px-3 text-xs font-semibold transition-colors",Ur===ge?"border-[#075fae] bg-[#075fae] text-white":"border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3"),onClick:()=>ui(ge),children:Ue},ge))}),Tr&&!Tr.safe?f.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-800",children:Tr.issues.join(" ")}):null,Ur==="html"?f.jsx("pre",{className:"max-h-[32rem] overflow-auto rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-4 text-xs leading-5 text-bolt-elements-textPrimary",children:br.html}):Ur==="text"?f.jsx("pre",{className:"max-h-[32rem] overflow-auto whitespace-pre-wrap rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1 p-4 text-sm leading-6 text-bolt-elements-textPrimary",children:br.text_version}):f.jsx("div",{className:"overflow-auto rounded-lg border border-bolt-elements-borderColor bg-slate-100 p-4",children:f.jsx("div",{className:ue("mx-auto overflow-hidden rounded bg-white shadow-sm",Ur==="mobile"?"max-w-[390px]":"max-w-[680px]"),children:f.jsx("iframe",{title:`${Ur} newsletter preview`,srcDoc:br.html,sandbox:"",className:"h-[680px] w-full border-0 bg-white"})})})]})}),zo=as[as.length-1],_o=Jt?Uo||f.jsx("div",{className:"flex h-full min-h-[24rem] items-center justify-center bg-bolt-elements-background-depth-1 p-6 text-center",children:f.jsxs("div",{className:"max-w-sm",children:[f.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-[#e7f4ff] text-[#075fae]",children:f.jsx("span",{className:Sr?"i-svg-spinners:90-ring-with-bg text-xl":"i-ph:envelope-simple-open text-xl"})}),f.jsx("div",{className:"mt-4 text-sm font-semibold text-bolt-elements-textPrimary",children:Sr?"Creating your newsletter campaign draft":"Newsletter draft will appear here"}),f.jsx("div",{className:"mt-2 text-sm leading-6 text-bolt-elements-textSecondary",children:zo?.message||"Use the normal prompt box to describe the campaign. The email preview will appear here."})]})}):null,$r=f.jsxs("div",{className:"mx-auto flex w-full max-w-chat flex-col gap-4 pb-4",children:[Qt.length>0&&f.jsx(Hb,{className:"z-1 flex w-full flex-col",messages:Qt,isStreaming:!1,append:ye,chatMode:le,setChatMode:ve,model:d,addToolResult:ft}),Gt&&f.jsxs("div",{className:"flex w-full flex-col gap-4",children:[Wi?Dr(Wi):f.jsx(Hb,{className:"z-1 flex w-full flex-col",messages:[Gt],isStreaming:!1,append:ye,chatMode:le,setChatMode:ve,model:d,addToolResult:ft}),ro&&rr()]}),(cn||Ss||Js)&&!Gt&&rr(),f.jsxs(_t.Suspense,{fallback:f.jsx("div",{className:"min-h-[220px] w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx("div",{className:"flex h-full min-h-[220px] items-center justify-center p-4 text-sm text-bolt-elements-textSecondary",children:"Loading workspace progress..."})}),children:[ot&&f.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx(Rf,{embedded:!0,isStreaming:Sr,isFollowUpRequest:Vr,progressMessage:xe})}),Zt?f.jsxs("div",{className:"flex w-full flex-col gap-4",children:[Nt.map(ge=>{const Ue=Sr&&ge.messageId===or;return f.jsxs("div",{className:"flex w-full flex-col gap-2",children:[ge.promptPreview?Dr(ge.promptPreview):null,f.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx(Rf,{embedded:!0,messageId:ge.messageId,isStreaming:Ue,progressMessage:xe,isFollowUpRequest:Vr})})]},ge.messageId)}),qt&&Ys&&f.jsx("div",{className:"flex w-full flex-col gap-2",children:f.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx(Rf,{embedded:!0,messageId:Ys,isStreaming:!0,progressMessage:xe,isFollowUpRequest:Vr})})},Ys)]}):ot||Gt?null:f.jsx("div",{className:"min-h-[220px] w-full overflow-hidden rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-1",children:f.jsx(Rf,{embedded:!0,isStreaming:Sr,isFollowUpRequest:Vr,progressMessage:xe})})]}),f.jsx("div",{ref:Hn,"aria-hidden":"true"})]}),Su=f.jsx(f.Fragment,{children:f.jsx(Hb,{className:"z-1 mx-auto flex w-full max-w-chat flex-col pb-4",messages:Bi,isStreaming:n,append:ye,chatMode:le,setChatMode:ve,model:d,addToolResult:ft})}),ds=!Pr,Pi=!r||Pr,no=x.useMemo(()=>cQ(U),[U]),xo=f.jsxs("div",{className:ue("z-prompt mx-auto mb-6 flex w-full min-w-0 shrink-0 flex-col gap-2",Pi?"max-w-[900px]":"max-w-chat"),children:[f.jsxs("div",{className:ue("flex min-w-0 flex-col gap-2"),children:[ds&&!jt&&!zr&&z&&q&&ae&&f.jsx(QX,{onSelectIntent:q,onDismiss:ae}),ds&&!jt&&F&&f.jsx(YX,{alert:F,clearAlert:()=>V?.(),postMessage:ge=>{_?.({},ge)}}),ds&&!jt&&oe&&f.jsx(JX,{alert:oe,clearAlert:()=>L?.(),postMessage:ge=>{_?.({},ge),L?.()}}),ds&&!jt&&Z&&f.jsx(HJ,{alert:Z,clearAlert:()=>K?.()}),ds&&!jt&&se&&!ie&&f.jsx("div",{className:"mx-auto w-full max-w-chat rounded-2xl border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-4 py-3",children:f.jsxs("div",{className:"flex items-start gap-3 text-sm text-bolt-elements-textPrimary",children:[f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg mt-0.5 text-bolt-elements-item-contentAccent"}),f.jsxs("div",{className:"flex-1",children:[f.jsx("div",{className:"font-medium",children:"Checking your request"}),f.jsx("div",{className:"mt-1 text-bolt-elements-textSecondary",children:"Clear requests continue straight to generation. I'll only ask when an essential detail is missing."})]})]})}),ds&&!jt&&ie&&Y&&f.jsx(sJ,{qualification:ie,busy:se,error:fe,onUseSmartDefaults:Y,onApplySuggestion:I})]}),ds&&!jt&&i&&f.jsx("div",{className:"mx-auto w-full max-w-chat rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-3 py-2",children:f.jsxs("div",{className:"flex items-start gap-2 text-sm text-bolt-elements-textPrimary",children:[f.jsx("div",{className:"i-svg-spinners:90-ring-with-bg mt-0.5 text-bolt-elements-item-contentAccent"}),f.jsxs("div",{className:"flex-1",children:[f.jsx("div",{children:o}),a>=12&&f.jsx("div",{className:"mt-1 text-xs text-bolt-elements-textSecondary",children:"Still working... this can take up to 1-2 minutes for larger prompts."})]})]})}),ds&&c&&f.jsx("div",{className:"mx-auto w-full max-w-chat rounded-lg border border-bolt-elements-borderColor bg-bolt-elements-background-depth-2 px-3 py-2",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"i-ph:info text-bolt-elements-item-contentAccent"}),f.jsx("div",{className:"flex-1 text-sm text-bolt-elements-textPrimary",children:"Generation looks paused for this chat."}),f.jsx("button",{type:"button",className:"rounded-md border border-bolt-elements-borderColor px-2 py-1 text-xs text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3",onClick:u,children:"Continue generation"})]})}),ds&&!jt&&as.length>0&&f.jsx(iJ,{data:as}),ds&&!jt&&no&&!Sr&&f.jsx("div",{className:"mx-auto w-full max-w-chat",children:f.jsx(LN,{annotation:no})}),f.jsx(WJ,{uploadedFiles:E,imageDataList:S,textareaRef:t,input:m,handleInputChange:g,handlePaste:us,TEXTAREA_MIN_HEIGHT:Rn,TEXTAREA_MAX_HEIGHT:ht,compactEmptyComposer:_s,isStreaming:Sr,handleStop:w,handleSendMessage:Qs,enhancingPrompt:b,enhancePrompt:v,isListening:Pe,startListening:Sa,stopListening:Ca,speechRecognitionSupported:!!Te,chatStarted:r,exportChat:A,qrModalOpen:Dt,setQrModalOpen:Yt,handleFileUpload:dc,handleImageFilesSelected:k,handleExistingAssetSelected:O,removeImageAttachment:T,clearImageAttachments:R,assetWorkspaceId:N,assetLibraryWorkspaceId:M,readOnlyReason:B,chatMode:le,setChatMode:ve,designScheme:Ae,setDesignScheme:we,selectedElement:pe,setSelectedElement:Ye,isEleventy:xr,isNewsletterMode:Jt},os)]}),mt=r&&!Pr,Pt=f.jsxs("div",{ref:ct,className:ue(Tf.BaseChat,"relative flex w-full",mt?"h-full overflow-hidden":"min-h-full"),"data-chat-visible":e,"data-chat-started":r?"true":"false",style:e?void 0:{"--workbench-inner-width":"100%","--workbench-left":"0"},children:[f.jsx(Ml,{children:()=>Mt&&!Or&<&&is?f.jsx(kB,{}):null}),f.jsxs("div",{className:ue("cms-surface-bg flex w-full flex-col lg:flex-row",mt?"h-full min-h-0 overflow-hidden":"min-h-full"),children:[f.jsxs("div",{className:ue(Tf.Chat,"cms-surface-bg flex flex-grow flex-col lg:min-w-[var(--chat-min-width)]",mt?"h-full min-h-0 overflow-hidden":"min-h-[90vh]",{"lg:!flex-none lg:!w-0 lg:!min-w-0 lg:!max-w-0 lg:!overflow-hidden lg:pointer-events-none lg:opacity-0":!e}),style:e?void 0:{flex:"0 0 0",width:0,minWidth:0,maxWidth:0,transform:"translateX(-1rem)"},children:[Mt&&r&&!Pr&&f.jsx("div",{className:"cms-workbench-header-bg flex h-12 items-center border-b border-bolt-elements-borderColor bg-[#d9ecff] px-3 dark:bg-black",children:f.jsx(QJ,{productType:xr?"genie-builder":"genie ai",workspaceName:qe,workspaceSubtitle:Bt.subtitle,trigger:f.jsxs("button",{type:"button",className:"flex min-w-0 max-w-[min(360px,calc(100vw-6rem))] items-center gap-2.5 rounded-2xl bg-[#eef1f6] px-3 py-1.5 text-left transition-colors hover:bg-[#e7ebf3] dark:bg-[#23252b] dark:hover:bg-[#2b2e35]","aria-label":`Open workspace menu for ${qe}`,children:[f.jsx("img",{src:"/headerlogo.png",alt:"CloudMySite",className:"h-6 w-auto shrink-0 dark:hidden"}),f.jsx("img",{src:"/headerlogo.png",alt:"CloudMySite",className:"hidden h-6
694w-auto shrink-0 dark:block"}),f.jsx("div",{className:"h-5 w-px bg-slate-300 dark:bg-white/10"}),f.jsx("div",{className:ue("flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-[#d9e6ff] text-[18px] dark:bg-[#1f2330]",Bt.iconClassName),children:f.jsx("span",{className:Bt.icon})}),f.jsxs("div",{className:"min-w-0 flex-1 leading-tight",children:[f.jsx("div",{className:"truncate text-sm font-semibold text-slate-950 dark:text-white",children:qe}),f.jsx("div",{className:"truncate text-xs text-slate-700 dark:text-slate-300",children:Bt.subtitle})]}),f.jsx("span",{className:"i-ph:caret-down shrink-0 text-sm text-slate-500 dark:text-slate-300"})]})})}),(!r||Pr)&&f.jsx("div",{id:"intro",className:"mt-[10vh] max-w-[900px] mx-auto text-center px-4 lg:px-0",children:xr?f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-2xl lg:text-4xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in",children:"Build Websites With CloudMySite Genie"}),f.jsx("p",{className:"text-s lg:text-l mb-8 text-bolt-elements-textSecondary animate-fade-in animation-delay-200",children:"Transform your ideas into a polished, ready-to-launch website in minutes."})]}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-3xl lg:text-5xl font-bold text-bolt-elements-textPrimary mb-4 animate-fade-in",children:"CloudMySite â From Idea to App, Instantly"}),f.jsx("p",{className:"text-s lg:text-l mb-4 text-bolt-elements-textSecondary animate-fade-in animation-delay-200",children:"Turn your ideas into fully functional apps, tools, and websites in minutes â no coding required."})]})}),r&&!Pr?jt?f.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden px-2 pt-6 sm:px-6",children:[f.jsx("div",{className:ue(Tf.WorkspaceTimelineScroller,"modern-scrollbar flex min-h-0 flex-1 flex-col gap-4"),ref:Wn,children:f.jsx(Ml,{children:()=>$r})}),xo]}):f.jsxs(fv,{className:ue("relative flex min-h-0 flex-1 flex-col overflow-hidden px-2 sm:px-6",ie&&!jt?"pt-1 sm:pt-2":"pt-6",ie&&!jt?Tf.PromptQualificationActive:void 0),resize:"smooth",initial:"smooth",children:[f.jsxs(fv.Content,{className:ue("relative flex min-h-0 flex-1 flex-col",ie&&!jt?"gap-0":"gap-4"),children:[f.jsx(Ml,{children:()=>Su}),f.jsx(_Q,{})]}),xo]}):f.jsx("div",{className:"px-2 pt-6 sm:px-6",children:f.jsx("div",{className:"mt-6",children:xo})}),f.jsx("div",{className:"flex flex-col justify-center pb-6",children:f.jsx("div",{className:"flex flex-col gap-5",children:(!r||Pr)&&!Jt&&!B&&f.jsx(KX,{isEleventy:xr,onPromptSelect:ge=>{if(n&&w?.(),!ge||!g)return;g({target:{value:ge}}),t?.current?.focus(),t?.current?.setSelectionRange(ge.length,ge.length)}})})})]}),!Pr&&Mt?f.jsx(Ml,{children:()=>f.jsx(K7,{chatStarted:r,isStreaming:n,isFollowUpRequest:l,buildJob:nt,onCancelBuild:xt,setSelectedElement:Ye,metadata:pt,updateChatMestaData:Lt,newsletterPreviewContent:_o,...Gs})}):null]})]});return f.jsx(t_,{delayDuration:200,children:f.jsx(f.Fragment,{children:Pt})})});function _Q(){const{isAtBottom:t,scrollToBottom:e}=TE();return!t&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"sticky bottom-0 left-0 right-0 bg-gradient-to-t from-bolt-elements-background-depth-1 to-transparent h-20 z-10"}),f.jsxs("button",{className:"sticky z-50 bottom-0 left-0 right-0 text-4xl rounded-lg px-1.5 py-0.5 flex items-center justify-center mx-auto gap-2 bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm",onClick:()=>e(),children:["Go to last message",f.jsx("span",{className:"i-ph:arrow-down animate-bounce"})]})]})}const Ec=t=>t.toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim(),Uy=t=>{if(!t)return;const e=t.trim();if(!e)return;if(e==="blank")return"blank";const r=Mf.find(o=>o.name===e);if(r)return r.name;const n=Ec(e),s=Ec(n.replace(/\b(template|starter|project|app)\b/g," ")),i=Mf.find(o=>{const l=Ec(o.name),c=Ec(o.label||"");return n===l||n===c||s===l||s===c});return i?i.name:Mf.find(o=>{const l=Ec(o.name),c=Ec(o.label||"");return n.includes(l)||n.includes(c)||l.includes(s)||c.includes(s)})?.name},FN=t=>{for(const e of t){const r=Uy(e);if(r)return r}},zb=()=>FN(["Vanilla Vite",uo])||"Vanilla Vite",xQ=()=>FN(["Phaser Vite","Vanilla Vite",uo])||"Phaser Vite",wQ=t=>{const e=t.search(/<!--\s*system:/i);return(e>=0?t.slice(0,e):t).replace(/<!--[\s\S]*?-->/g," ")},Hm=t=>wQ(t).toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim(),k0=t=>
694t.split(/\s+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),SQ=t=>{switch(t){case"application":return"App";case"site":return"Site";case"landing page":return"Landing Page";default:return k0(t)}},CQ=t=>{const e=Hm(t);if(!e)return;const r="application|website|landing page|dashboard|marketplace|platform|portal|store|shop|tool|game|app|site",n=[new RegExp(String.raw`\b(?:create|build|make|develop|generate|design)\s+(?:an?\s+|the\s+)?(.+?)\s+(${r})\b`),new RegExp(String.raw`\b(.+?)\s+(${r})\b`)];for(const s of n){const i=e.match(s);if(!i)continue;const a=i[1].replace(/\b(with|using|for|that|which|including|featuring|plus|and)\b.*$/,"").replace(/^(?:an?|the)\s+/,"").trim();if(a)return`${k0(a)} ${SQ(i[2])}`.trim()}},AQ=t=>{const e=Hm(t);if(!e)return;const r=e.replace(/^(?:please\s+)?(?:create|build|make|develop|generate|design)\s+(?:me\s+)?(?:an?\s+|the\s+)?/,"").trim();if(!r)return;const n=r.replace(/\b(with|using|that|which|including|featuring|plus|and then|where|who)\b.*$/,"").trim();if(!n)return;const s=n.split(/\s+/).filter(Boolean).slice(0,6).join(" ").trim();if(s&&!/^(?:app|application|website|site|store|shop|marketplace|platform|portal|dashboard|tool|game)$/i.test(s))return k0(s)},SA=t=>{const e=CQ(t);if(e)return e;const r=AQ(t);return r||(Hm(t),"My App")},EQ=t=>{const e=Hm(t);if(!e)return;const r=U=>U.test(e),n=r(/\bphaser(?:\s*3|\.?js)?\b/),s=r(/\b(phaser vite|phaser 3|phaser game|phaser browser game|phaser template|phaser scene|phaser scenes|phaser engine)\b/),i=r(/\b(do not|don t|dont|never|avoid|without|no|not|exclude)\b(?:\s+\w+){0,6}
694\s+\bphaser\b|\binstead of phaser\b|\brather than phaser\b/),a=n&&(!i||s),o=r(/\b(react|reactjs|react js|jsx|tsx|react three fiber|@react-three\/fiber|r3f)\b/),l=r(/\b(do not|don t|dont|never|avoid|without|no|not|exclude)\b(?:\s+\w+){0,6}\s+\breact\b|\binstead of react\b|\brather than react\b/),c=r(/\b(games?|gameplay|single player|single-player|level|enemy|arcade|platformer)\b/),u=r(/\b(browser|web|html5|canvas|javascript|js)\b/),d=r(/\b(physics simulation|simulation|sandbox)\b/),h=r(/\b(react native|android|ios|iphone|ipad|app store|play store|native app|native mobile)\b/),m=r(/\b(single html|single html file|single-file html|single file html|one html file|one single html|self contained html|self-contained html)\b/),b=r(/\b(plain html css js|plain html css and js|plain html css and javascript|plain html css javascript|plain html javascript css|vanilla html css js|vanilla html css and javascript)\b/),g=r(/\b(vanilla javascript|vanilla js|plain javascript|plain js)\b/),p=r(/\b(html5 canvas|canvas and javascript|canvas and js|javascript and canvas|js and canvas|canvas game|canvas-based|canvas based)\b/),y=r(/\b(2\s*d|two dimensional|two-dimensional|side scrolling|side-scrolling|top down|top-down)\b/)&&c,v=r(/\b(2\s*d|two dimensional|two-dimensional)\b/)&&d&&r(/\b(canvas|html5)\b/),_=c&&u&&r(/\bcanvas\b/),w=c&&r(/\b(3d|three dimensional|three-dimensional|webgl|three js|threejs|babylon js|babylonjs|first person|first-person|fps|voxel|minecraft|open world|open-world)\b/),C=r(/\b(simple|basic|minimal|tiny|small)\b/)&&r(/\b(app|application|page|site|website|web page|landing page)\b/)&&r(/\b(static|plain|html|css|javascript|js)\b/),A=r(/\b(dashboard|crm|saas|admin|analytics|kanban|calendar|tasks?|projects?|inventory|ecommerce|e-commerce|store|shop|checkout|cart|auth|login|sign\s*up|database|crud|api|forms?|booking|reservation|workflow|reports?|charts?|tables?|payments?|subscriptions?|multi[- ]page|multiple pages|routing|router)\b/);if(a)return xQ();if(w&&!h)return np;if(C&&!A&&!o&&!h&&!w||m||g||b||u&&l&&r(/\b(html css js|html css and javascript|html css and js)\b/)||p&&(c||d||!o)||_||v||y&&!h)return zb();const E=r(/\bexpo\b/),S=r(/\b(without expo|no expo|non expo|bare workflow|react native cli|bare react native)\b/),k=r(/\breact native\b/),O=r(/\b(android|ios|iphone|ipad)\b/),T=r(/\b(app store|play store)\b/),R=r(/\bnative app|native mobile\b/),N=r(/\bmobile\b/)&&r(/\b(app|application)\b/),M=r(/\b(mobile[- ]first|mobile friendly|responsive|website|web site|landing page|web app|webapp|pwa|progressive web app)\b/);if(E&&!S)return"Expo App";if(S||k||R||N&&!M||(O||T)&&!M)return"Vite React";if(r(/\b(slide|slides|presentation|deck|speaker notes)\b/))return"Slidev";if(r(/\b(shadcn)\b/)){if(r(/\b(nextjs|next js|next)\b/))return"NextJS Shadcn";if(r(/\b(vite|react)\b/))return"Vite Shadcn"}if(r(/\b(vue|vuejs)\b/))return"Vue";if(r(/\b(angular)\b/))return"Angular";if(r(/\b(solid|solidjs)\b/))return"SolidJS";if(r(/\b(qwik)\b/))return"Qwik Typescript";if(r(/\b(astro)\b/))return"Basic Astro";if(r(/\b(eleventy|11ty)\b/))return uo;if(r(/\b(vanilla|plain javascript|plain js|html css js)\b/)&&l)return zb();if(r(/\b(typescript only|ts only|typescript app)\b/))return"Vite Typescript";if(r(/\b(remix)\b/))return"Remix Typescript"},P0=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),CA=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="App icon"> 695 <defs> 696 <linearGradient id="bg" x1="8" y1="8" x2="56" y2="56" gradientUnits="userSpaceOnUse"> 697 <stop offset="0" stop-color="#0F766E" /> 698 <stop offset="1" stop-color="#2563EB" /> 699 </linearGradient> 700 </defs> 701 <rect x="6" y="6" width="52" height="52" rx="14" fill="url(#bg)" /> 702 <path 703 d="M20 38.5 29 25l7.2 10.4 7.4-14 6.4 4.3-12 20.8-8-10.9-4.7 7.1z" 704 fill="#FFF7ED" 705 /> 706</svg>`,WN="${quoteIdentifier(}`${table}_created_at_idx`)}",HN="${quoteIdentifier(`${table}_created_at_idx`)}",kQ="const PASSWORD_HASH_ITERATIONS = 310000",PQ="const PASSWORD_HASH_ITERATIONS = 100000",TQ="normalizeInteger(rawIterations, PASSWORD_HASH_ITERATIONS, 100000, 1000000)",RQ="normalizeInteger(rawIterations, PASSWORD_HASH_ITERATIONS, 100000, PASSWORD_HASH_ITERATIONS)",IQ="^6.30.1",UN={"@react-three/drei":"9.121.4","@react-three/fiber"
706:"8.17.14",three:"0.159.0"},NQ=new Set(Object.keys(UN)),LQ=new Set(["@eslint/js","eslint","eslint-plugin-react-hooks","eslint-plugin-react-refresh","globals","typescript-eslint","wrangler"]),zN=new Set(["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]),AA=(t,e)=>{const r={...t};let n=!1;return e.forEach(s=>{Object.prototype.hasOwnProperty.call(r,s)&&(delete r[s],n=!0)}),{next:r,removedAny:n}},DQ=t=>/\b(3d|three dimensional|three-dimensional|webgl|three js|threejs|react three fiber|@react-three\/fiber|r3f|babylon js|babylonjs|first person|first-person|fps|voxel|minecraft|open world|open-world)\b/i.test(t||""),MQ=t=>{const e=t||"";if(!DQ(e))return!1;const r=/\b(technical blueprint|implementation guide|implementation roadmap|architecture overview|architecture recommendation|technology stack recommendation|development roadmap|code snippets?|deliverables?)\b/i.test(e),n=/\b(build|create|make|develop|implement|generate|prototype)\b(?:\s+[\w-]+){0,10}\s+\b(3d|three-dimensional|three dimensional|webgl|game|interactive experience|scene|prototype|app|application)\b/i.test(e)||/\b(playable|working|runnable)\b(?:\s+[\w-]+){0,8}\s+\b(3d|webgl|game|experience|scene|app)\b/i.test(e);return!r||n},OQ=new Set([...zN,"package.json","vite.config.js","vite.config.ts","vite.config.mjs","vite.local-db.ts","counter.js","javascript.svg","public/vite.svg"]),EA=t=>`<!doctype html> 707<html lang="en"> 708 <head> 709 <meta charset="UTF-8" /> 710 <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> 711 <link rel="stylesheet" href="/style.css" /> 712 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 713 <title>${P0(t)}</title> 714 </head> 715 <body> 716 <main id="app"></main> 717 <script src="/main.js" defer><\/script> 718 </body> 719</html> 720`,jQ=t=>P0(t).replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),kA=t=>`const app = document.querySelector('#app'); 721 722if (app) { 723 app.innerHTML = \` 724 <section class="app-shell" aria-labelledby="app-title"> 725 <p class="eyebrow">CloudMySite</p> 726 <h1 id="app-title">${jQ(t)}</h1> 727 <p>Start building your app by editing index.html, style.css, and main.js.</p> 728 </section> 729 \`; 730} 731`,PA=`${$1} 732 733:root { 734 font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; 735 color: #111827; 736 background: #f8fafc; 737 font-synthesis: none; 738 text-rendering: optimizeLegibility; 739 -webkit-font-smoothing: antialiased; 740 -moz-osx-font-smoothing: grayscale; 741} 742 743* { 744 box-sizing: border-box; 745} 746 747body { 748 min-width: 320px; 749 min-height: 100vh; 750 margin: 0; 751} 752 753#app { 754 min-height: 100vh; 755} 756 757.app-shell { 758 display: grid; 759 min-height: 100vh; 760 place-content: center; 761 gap: 1rem; 762 padding: 2rem; 763 text-align: center; 764} 765 766.eyebrow { 767 margin: 0; 768 color: #2563eb; 769 font-size: 0.75rem; 770 font-weight: 700; 771 letter-spacing: 0.18em; 772 text-transform: uppercase; 773} 774 775h1 { 776 margin: 0; 777 color: #020617; 778 font-size: 4rem; 779 line-height: 1; 780} 781 782p { 783 margin: 0; 784 color: #475569; 785 font-size: 1.125rem; 786} 787 788@media (max-width: 640px) { 789 h1 { 790 font-size: 2.5rem; 791 } 792} 793`,$Q=`import React, { StrictMode } from 'react' 794import { createRoot } from 'react-dom/client' 795import { BrowserRouter } from 'react-router-dom' 796import App from './App.tsx' 797import { AppAuthBoundary, AuthProvider } from './lib/appAuth.tsx' 798import './index.css' 799 800createRoot(document.getElementById('root')!).render( 801 <StrictMode> 802 <BrowserRouter> 803 <AuthProvider> 804 <AppAuthBoundary> 805 <App /> 806 </AppAuthBoundary> 807 </AuthProvider> 808 </BrowserRouter> 809 </StrictMode>, 810) 811`;function BQ(t){let e=t;return e.includes("async function readUserById(")||(e=e.replace(/async function readUserByProvider\([\s\S]*?\n}\n\nasync function readAuthenticatedSession/,r=>`${r.replace(/\n\nasync function readAuthenticatedSession$/,"")} 812 813async function readUserById(db, usersTable, id) { 814 if (!Number.isFinite(Number(id))) { 815 return null 816 } 817 818 return readFirstRow( 819 db, 820 \`SELECT id, email, password_hash, provider, provider_id, created_at FROM \${quoteIdentifier(usersTable)}
820 WHERE id = ? LIMIT 1\`, 821 [Number(id)], 822 ) 823} 824 825 826async function readAuthenticatedSession`)),e=e.replace(/const user = await readFirstRow\([\s\S]*?return user \? buildAuthenticatedJsonResponse\(request, env, authConfig, user, 201\) : jsonResponse\(\{ error: 'Unable to create the new account\.' \}, 500\)/,`const user = 827 (await readUserById(env.DB, usersTable, insertResult?.meta?.last_row_id)) || 828 (await readUserByEmail(env.DB, usersTable, email)) 829 830 return user ? buildAuthenticatedJsonResponse(request, env, authConfig, user, 201) : jsonResponse({ error: 'Unable to create the new account.' }, 500)`),e=e.replace(/const insertResult = await env\.DB\s+\.prepare\(\s+`INSERT INTO \$\{quoteIdentifier\(usersTable\)\} \(\$\{quoteIdentifier\('provider'\)\}, \$\{quoteIdentifier\('provider_id'\)\}\) VALUES \(\?, \?\)`\s+\)\s+\.bind\('anonymous', randomBase64Url\(18\)\)\s+\.run\(\)/,`const providerId = randomBase64Url(18) 831 const insertResult = await env.DB 832 .prepare( 833 \`INSERT INTO \${quoteIdentifier(usersTable)} (\${quoteIdentifier('provider')}, \${quoteIdentifier('provider_id')}) VALUES (?, ?)\`, 834 ) 835 .bind('anonymous', providerId) 836 .run()`),e=e.replace(/const anonymousUser = await readFirstRow\([\s\S]*?return anonymousUser\s+\? buildAuthenticatedJsonResponse\(request, env, authConfig, anonymousUser\)\s+: jsonResponse\(\{ error: 'Unable to create the guest session\.' \}, 500\)/,`const anonymousUser = 837 (await readUserById(env.DB, usersTable, insertResult?.meta?.last_row_id)) || 838 (await readUserByProvider(env.DB, usersTable, 'anonymous', providerId)) 839 840 return anonymousUser 841 ? buildAuthenticatedJsonResponse(request, env, authConfig, anonymousUser) 842 : jsonResponse({ error: 'Unable to create the guest session.' }, 500)`),e=e.replace(` const response = Response.redirect(new URL(sanitizeReturnTo(returnTo), request.url).toString(), 302) 843 response.headers.set('Set-Cookie', session.cookie) 844 return response`,` const redirectUrl = new URL(sanitizeReturnTo(returnTo), request.url).toString() 845 return new Response(null, { 846 status: 302, 847 headers: { 848 Location: redirectUrl, 849 'Set-Cookie': session.cookie, 850 'Cache-Control': 'no-store', 851 }, 852 })`),e=e.replace(`return user 853 ? buildAuthenticatedRedirectResponse(request, env, authConfig, user, returnTo) 854 : buildAuthErrorRedirect(request, returnTo, 'google_login_failed')`,`return user 855 ? await buildAuthenticatedRedirectResponse(request, env, authConfig, user, returnTo) 856 : buildAuthErrorRedirect(request, returnTo, 'google_login_failed')`),e=e.split("SELECT id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE email = ? LIMIT 1").join("SELECT rowid AS id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE email = ? LIMIT 1"),e=e.split("SELECT id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE provider = ? AND provider_id = ? LIMIT 1").join("SELECT rowid AS id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE provider = ? AND provider_id = ? LIMIT 1"),e=e.split("SELECT id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE id = ? LIMIT 1").join("SELECT rowid AS id, email, password_hash, provider, provider_id, created_at FROM ${quoteIdentifier(usersTable)} WHERE rowid = ? LIMIT 1"),e=e.split("u.id = s.user_id").join("u.rowid = s.user_id"),e=e.split(" u.id,").join(" u.rowid AS id,"),e=e.split(" END WHERE id = ?").join(" END WHERE rowid = ?"),e=e.replace("import { ensureSchema, hasConfiguredSecret, jsonResponse, quoteIdentifier } from './db-runtime.js'","import { ensureSchema, hasConfiguredSecret, jsonResponse, quoteIdentifier, readSchema } from './db-runtime.js'"),e=e.replace(`async function ensureAuthSchema(db, scope) { 857 return ensureSchema(db, buildAuthSchemaDefinition(scope)) 858}`,`async function ensureAuthSchema(db, scope) { 859 await ensureSchema(db, buildAuthSchemaDefinition(scope)) 860 await repairLegacyAuthSessionsTable(db, scope) 861 return getAuthTableNames(scope) 862} 863 864async function readTableForeignKeys(db, tableName) { 865 const result = await db.prepare(\`PRAGMA foreign_key_list(\${quoteIdentifier(tableName)})\`).all() 866 return Array.isArray(result.results) ? result.results : [] 867} 868 869async function rebuildSessionsTableWithoutLegacyForeignKey(db, sessionsTable) { 870 const backupTable = \`\${sessionsTable}_legacy_backup\` 871 872 try { 873 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(backupTable)}\`).run() 874 } catch {} 875 876 await db.prepare(\`ALTER TABLE \${quoteIdentifier(sessionsTable)} RENAME TO \${quoteIdentifier(backupTable)}\`).run() 877 878 try { 879 await db 880 .prepare( 881 \`CREATE TABLE IF NOT EXISTS \${quoteIdentifier(sessionsTable)} ( 882 \${quoteIdentifier('id')} INTEGER PRIMARY KEY AUTOINCREMENT, 883 \${quoteIdentifier('user_id')} INTEGER NOT NULL, 884 \${quoteIdentifier('token')} TEXT NOT NULL UNIQUE, 885 \${quoteIdentifier('expires_at')} TEXT NOT NULL, 886 \${quoteIdentifier('created_at')} TEXT DEFAULT CURRENT_TIMESTAMP 887 )\`, 888 ) 889 .run() 890 891 await db 892 .prepare( 893 \`CREATE INDEX IF NOT EXISTS \${quoteIdentifier(\`\${sessionsTable}_user_id_idx\`)} ON \${quoteIdentifier(sessionsTable)} (\${quoteIdentifier('user_id')})\`, 894 ) 895 .run() 896 await db 897 .prepare( 898 \`CREATE INDEX IF NOT EXISTS \${quoteIdentifier(\`\${sessionsTable}_expires_at_idx\`)} ON \${quoteIdentifier(sessionsTable)} (\${quoteIdentifier('expires_at')})\`, 899 ) 900 .run() 901 await db 902 .prepare( 903 \`CREATE INDEX IF NOT EXISTS \${quoteIdentifier(\`\${sessionsTable}_created_at_idx\`)} ON \${quoteIdentifier(sessionsTable)} (\${quoteIdentifier('created_at')})\`, 904 ) 905 .run() 906 await db 907 .prepare( 908 \`CREATE INDEX IF NOT EXISTS \${quoteIdentifier(\`\${sessionsTable}_user_expires_idx\`)} ON \${quoteIdentifier(sessionsTable)} (\${quoteIdentifier('user_id')}, \${quoteIdentifier('expires_at')})\`, 909 ) 910 .run() 911 912 const backupColumns = new Set((await readSchema(db, backupTable)).map((column) => String(column?.name || ''))) 913 const copyColumns = ['id', 'user_id', 'token', 'expires_at', 'created_at'].filter((column) => 914 backupColumns.has(column), 915 ) 916 917 if (copyColumns.includes('user_id') && copyColumns.includes('token') && copyColumns.includes('expires_at')) { 918 await db 919 .prepare( 920 \`INSERT OR REPLACE INTO \${quoteIdentifier(sessionsTable)} (\${copyColumns 921 .map((column) => quoteIdentifier(column)) 922 .join(', ')}) SELECT \${copyColumns 923 .map((column) => quoteIdentifier(column)) 924 .join(', ')} FROM \${quoteIdentifier(backupTable)}\`, 925 ) 926 .run() 927 } 928 929 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(backupTable)}\`).run() 930 } catch (error) { 931 try { 932 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(sessionsTable)}\`).run() 933 } catch {} 934 935 try { 936 await db.prepare(\`ALTER TABLE \${quoteIdentifier(backupTable)} RENAME TO \${quoteIdentifier(sessionsTable)}\`).run() 937 } catch {} 938 939 throw error 940 } 941} 942 943async function repairLegacyAuthSessionsTable(db, scope) { 944 const { usersTable, sessionsTable } = getAuthTableNames(scope) 945 const usersSchema = await readSchema(db, usersTable) 946 947 if (!Array.isArray(usersSchema) || usersSchema.length === 0) { 948 return 949 } 950 951 const usersHasExplicitId = usersSchema.some((column) => String(column?.name || '') === 'id') 952 953 if (usersHasExplicitId) { 954 return 955 } 956 957 const sessionsSchema = await readSchema(db, sessionsTable) 958 959 if (!Array.isArray(sessionsSchema) || sessionsSchema.length === 0) { 960 return 961 } 962 963 const foreignKeys = await readTableForeignKeys(db, sessionsTable) 964 const hasLegacyUsersForeignKey = foreignKeys.some( 965 (foreignKey) => 966 String(foreignKey?.table || '') === usersTable && 967 String(foreignKey?.from || '') === 'user_id' &&
968 String(foreignKey?.to || '') === 'id', 969 ) 970 971 if (!hasLegacyUsersForeignKey) { 972 return 973 } 974 975 await rebuildSessionsTableWithoutLegacyForeignKey(db, sessionsTable) 976}`),e=e.replace(`async function ensureAuthSchema(db, scope, profileFieldNames = []) { 977 return ensureSchema(db, buildAuthSchemaDefinition(scope, profileFieldNames)) 978}`,`async function ensureAuthSchema(db, scope, profileFieldNames = []) { 979 await ensureSchema(db, buildAuthSchemaDefinition(scope, profileFieldNames)) 980 await repairLegacyAuthChildTables(db, scope, profileFieldNames) 981 return getAuthTableNames(scope) 982} 983 984async function readTableForeignKeys(db, tableName) { 985 const result = await db.prepare(\`PRAGMA foreign_key_list(\${quoteIdentifier(tableName)})\`).all() 986 return Array.isArray(result.results) ? result.results : [] 987} 988 989async function rebuildAuthTablePreservingRows(db, tableName, recreateTable) { 990 const backupTable = \`\${tableName}_legacy_backup\` 991 992 try { 993 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(backupTable)}\`).run() 994 } catch {} 995 996 await db.prepare(\`ALTER TABLE \${quoteIdentifier(tableName)} RENAME TO \${quoteIdentifier(backupTable)}\`).run() 997 998 try { 999 await recreateTable() 1000 1001 const backupColumns = new Set((await readSchema(db, backupTable)).map((column) => String(column?.name || ''))) 1002 const targetColumns = (await readSchema(db, tableName)).map((column) => String(column?.name || '')) 1003 const copyColumns = targetColumns.filter((column) => backupColumns.has(column)) 1004 1005 if (copyColumns.length > 0) { 1006 await db 1007 .prepare( 1008 \`INSERT OR REPLACE INTO \${quoteIdentifier(tableName)} (\${copyColumns 1009 .map((column) => quoteIdentifier(column)) 1010 .join(', ')}) SELECT \${copyColumns 1011 .map((column) => quoteIdentifier(column)) 1012 .join(', ')} FROM \${quoteIdentifier(backupTable)}\`, 1013 ) 1014 .run() 1015 } 1016 1017 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(backupTable)}\`).run() 1018 } catch (error) { 1019 try { 1020 await db.prepare(\`DROP TABLE IF EXISTS \${quoteIdentifier(tableName)}\`).run() 1021 } catch {} 1022 1023 try { 1024 await db.prepare(\`ALTER TABLE \${quoteIdentifier(backupTable)} RENAME TO \${quoteIdentifier(tableName)}\`).run() 1025 } catch {} 1026 1027 throw error 1028 } 1029} 1030 1031async function repairLegacyAuthChildTables(db, scope, profileFieldNames = []) { 1032 const { usersTable, userProfilesTable, sessionsTable } = getAuthTableNames(scope) 1033 const usersSchema = await readSchema(db, usersTable) 1034 1035 if (!Array.isArray(usersSchema) || usersSchema.length === 0) { 1036 return 1037 } 1038 1039 const usersHasExplicitId = usersSchema.some((column) => String(column?.name || '') === 'id') 1040 1041 if (usersHasExplicitId) { 1042 return 1043 } 1044 1045 const legacyChildTables = [] 1046 1047 for (const tableName of [userProfilesTable, sessionsTable]) { 1048 const tableSchema = await readSchema(db, tableName) 1049 1050 if (!Array.isArray(tableSchema) || tableSchema.length === 0) { 1051 continue 1052 } 1053 1054 const foreignKeys = await readTableForeignKeys(db, tableName) 1055 const hasLegacyUsersForeignKey = foreignKeys.some( 1056 (foreignKey) => 1057 String(foreignKey?.table || '') === usersTable && 1058 String(foreignKey?.from || '') === 'user_id' && 1059 String(foreignKey?.to || '') === 'id', 1060 ) 1061 1062 if (hasLegacyUsersForeignKey) { 1063 legacyChildTables.push(tableName) 1064 } 1065 } 1066 1067 if (legacyChildTables.length === 0) { 1068 return 1069 } 1070 1071 for (const tableName of legacyChildTables) { 1072 await rebuildAuthTablePreservingRows(db, tableName, async () => { 1073 await ensureSchema(db, buildAuthSchemaDefinition(scope, profileFieldNames)) 1074 }) 1075 } 1076}`),AI(e)}function FQ(t){let e=t;return e=e.split(kQ).join(PQ),e=e.split(TQ).join(RQ),e=e.replace(/\n\s*references: \{\n\s*table: usersTable,\n\s*column: 'id',\n\s*onDelete: 'CASCADE',\n\s*onUpdate: 'CASCADE',\n\s*\},/g,""),SI(e)}function WQ(t){let e=t;return e.includes("function sanitizeClientReturnTo(")||(e=e.replace(`function buildGoogleLoginUrl(returnTo?: string) { 1077 const url = new URL('/api/auth/google/start', window.location.origin) 1078 1079 if (returnTo) { 1080 url.searchParams.set('returnTo', returnTo) 1081 } 1082 1083 return url.toString() 1084}`,`function buildGoogleLoginUrl(returnTo?: string) { 1085 const url = new URL('/api/auth/google/start', window.location.origin) 1086 1087 if (returnTo) { 1088 url.searchParams.set('returnTo', returnTo) 1089 } 1090 1091 return url.toString() 1092} 1093 1094function sanitizeClientReturnTo(value?: string) { 1095 const normalized = normalizeProtectedPath(value || '/') 1096 return normalized && !normalized.startsWith('/api/') ? normalized : '/' 1097}`)),e=e.replace(" const startGoogleLogin = (returnTo?: string) => {\n window.location.assign(buildGoogleLoginUrl(returnTo || `${window.location.pathname}${window.location.search}`))\n }"," const startGoogleLogin = (returnTo?: string) => {\n const currentReturnTo = `${window.location.pathname}${window.location.search}`\n const sanitizedReturnTo = sanitizeClientReturnTo(returnTo || currentReturnTo)\n window.location.assign(buildGoogleLoginUrl(sanitizedReturnTo))\n }"),e=e.split("function sanitizeAuthenticatedReturnTo(value?: string, fallback = '/account')").join("function sanitizeAuthenticatedReturnTo(value?: string, fallback = '/')").split("const rawReturnTo = new URLSearchParams(window.location.search).get('returnTo') || '/account'").join("const rawReturnTo = new URLSearchParams(window.location.search).get('returnTo') || '/'").split("const successHref = sanitizeAuthenticatedReturnTo(rawReturnTo, '/account')").join("const successHref = sanitizeAuthenticatedReturnTo(rawReturnTo, '/')").split("const sanitizedReturnTo = sanitizeAuthenticatedReturnTo(rawReturnTo, '/account')").join("const sanitizedReturnTo = sanitizeAuthenticatedReturnTo(rawReturnTo, '/')"),e=e.replace("path === '/logout' ? sanitizeClientReturnTo(returnTo, '/') : sanitizeAuthenticatedReturnTo(returnTo, '/account')","path === '/logout' ? sanitizeClientReturnTo(returnTo, '/') : sanitizeAuthenticatedReturnTo(returnTo, '/')"),e.includes("function isAuthEntryPath(")||(e=e.replace("function normalizeClientAuthSettings(input: unknown): AppAuthSettings {",`function isAuthEntryPath(pathname: string) { 1098 const currentPath = normalizeProtectedPath(pathname || '/') || '/' 1099 const authEntryPrefixes = ['/login', '/signup', '/sign-in', '/sign-up', '/register'] 1100 1101 return authEntryPrefixes.some((entryPath) => currentPath === entryPath || currentPath.startsWith(\`\${entryPath}/\`)) 1102} 1103 1104function normalizeClientAuthSettings(input: unknown): AppAuthSettings {`)),e=e.replace(" const isProtected = auth.requireLogin || matchesProtectedPath(pathname, auth.protectedPaths)",` const isAuthEntryRoute = isAuthEntryPath(pathname) 1105 const isProtected = (auth.requireLogin || matchesProtectedPath(pathname, auth.protectedPaths)) && !isAuthEntryRoute`),e=e.replace(/disabled=\{props\.loading \|\| !props\.googleConfigured\}/g,"disabled={props.loading}").replace(/disabled=\{loading \|\| !props\.googleConfigured\}/g,"disabled={loading}").replace(/disabled=\{loading \|\| !auth\.googleConfigured\}/g,"disabled={loading}"),e.includes("showBackToAppLink = false")||(e=e.replace(`export function AuthGate({ 1106 title = 'Sign in to continue', 1107 description = 'Authentication is enabled for this part of the app.', 1108}: { 1109 title?: string 1110 description?: string 1111}) {`,`export function AuthGate({ 1112 title = 'Sign in to continue', 1113 description = 'Authentication is enabled for this part of the app.', 1114 showBackToAppLink = false, 1115 backToPath = '/', 1116}: { 1117 title?: string 1118 description?: string 1119 showBackToAppLink?: boolean 1120 backToPath?: string 1121}) {`)),e.includes("const resolvedBackToPath = sanitizeClientReturnTo(backToPath)")||(e=e.replace(" const [localError, setLocalError] = useState<string | null>(null)",` const [localError, setLocalError] = useState<string | null>(null) 1122 const resolvedBackToPath = sanitizeClientReturnTo(backToPath)`)),e.includes("const handleBackToApp = () => {")||(e=e.replace(" const googleMissingMessage = auth.enableGoogleLogin && !auth.googleConfigured ? 'Google sign-in is unavailable.' : null",` const googleMissingMessage = auth.enableGoogleLogin && !auth.googleConfigured ? 'Google sign-in is unavailable.' : null 1123 const handleBackToApp = () => { 1124 if (window.history.length > 1) { 1125 window.history.back() 1126 return 1127 } 1128 1129 window.location.assign(resolvedBackToPath) 1130 }`)),e.includes("Back to app")||(e=e.replace(` {auth.enableGoogleLogin ? ( 1131 <button 1132 type="button" 1133 className="inline-flex w-full items-center justify-center rounded-xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60" 1134 onClick={() => startGoogleLogin()} 1135 disabled={loading} 1136 > 1137 Continue with Google 1138 </button> 1139 ) : null} 1140 </div>`,` {auth.enableGoogleLogin ? ( 1141 <button 1142 type="button" 1143 className="inline-flex w-full items-center justify-center rounded-xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60" 1144 onClick={() => startGoogleLogin()} 1145 disabled={loading} 1146 > 1147 Continue with Google 1148 </button> 1149 ) : null} 1150 1151 {showBackToAppLink ? ( 1152 <button 1153 type="button" 1154 className="inline-flex w-full items-center justify-center rounded-xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition hover:bg-slate-50" 1155 onClick={handleBackToApp} 1156 > 1157 Back to app 1158 </button> 1159 ) : null} 1160 </div>`)),e=e.replace(' <AuthGate description="Sign in with an existing account or create one to open this protected area." />',` <AuthGate 1161 description="Sign in with an existing account or create one to open this protected area." 1162 showBackToAppLink 1163 />`),CI(e)}const HQ=` 1164function normalizeCloudMySiteDomainHost(value) { 1165 return String(value || '') 1166 .trim() 1167 .toLowerCase() 1168 .replace(/^https?:\\/\\//, '') 1169 .replace(/\\/.*$/, '') 1170 .replace(/:\\d+$/, '') 1171 .replace(/\\.$/, '') 1172} 1173
1174async function resolveCloudMySitePrimaryDomainRedirect(request, env) { 1175 if (!env.AI_DB) { 1176 return null 1177 } 1178 1179 const requestUrl = new URL(request.url) 1180 const host = normalizeCloudMySiteDomainHost(requestUrl.hostname) 1181 1182 if (!host) { 1183 return null 1184 } 1185 1186 try { 1187 const row = await env.AI_DB.prepare([ 1188 'SELECT primary_domain.hostname AS primary_hostname', 1189 'FROM cms_ai_project_domains current_domain', 1190 'INNER JOIN cms_ai_project_domains primary_domain', 1191 ' ON primary_domain.project_id = current_domain.project_id', 1192 " AND primary_domain.status = 'active'", 1193 ' AND primary_domain.is_primary = 1', 1194 'WHERE current_domain.hostname = ?', 1195 " AND current_domain.status = 'active'", 1196 ' AND current_domain.redirect_to_primary = 1', 1197 'LIMIT 1', 1198 ].join(' ')) 1199 .bind(host) 1200 .first() 1201 1202 const primaryHost = normalizeCloudMySiteDomainHost(row && row.primary_hostname) 1203 1204 if (!primaryHost || primaryHost === host) { 1205 return null 1206 } 1207 1208 requestUrl.protocol = 'https:' 1209 requestUrl.hostname = primaryHost 1210 return Response.redirect(requestUrl.toString(), 301) 1211 } catch (error) { 1212 console.warn('[cloudmysite-domain] redirect lookup failed', error && error.message ? error.message : error) 1213 return null 1214 } 1215} 1216`;function UQ(t){let e=t;return e.includes("resolveCloudMySitePrimaryDomainRedirect")||(e=e.replace(/\nexport\s+default\s+\{/,` 1217${HQ} 1218export default {`)),e.includes("const customDomainRedirect = await resolveCloudMySitePrimaryDomainRedirect")||(e=e.replace(/(async\s+fetch\s*\(\s*request\s*,\s*env(?:\s*,\s*ctx)?\s*\)\s*\{\s*)/,`$1 1219 const customDomainRedirect = await resolveCloudMySitePrimaryDomainRedirect(request, env) 1220 if (customDomainRedirect) return customDomainRedirect 1221`)),e=e.replace(`function createAdminAuthInitCorsHeaders() { 1222 return { 1223 'access-control-allow-origin': '*', 1224 'access-control-allow-methods': 'POST, OPTIONS', 1225 'access-control-allow-headers': 'Content-Type', 1226 'access-control-max-age': '86400', 1227 vary: 'Origin', 1228 } 1229} 1230 1231function withAdminAuthInitCors(response) { 1232 const headers = createAdminAuthInitCorsHeaders() 1233`,`function resolveAdminAuthInitAllowedOrigin(request) { 1234 const requestUrl = new URL(request.url) 1235 const originHeader = request.headers.get('Origin') 1236 1237 if (!originHeader) { 1238 return requestUrl.origin 1239 } 1240 1241 try { 1242 const originUrl = new URL(originHeader) 1243 return originUrl.origin === requestUrl.origin ? originUrl.origin : requestUrl.origin 1244 } catch { 1245 return requestUrl.origin 1246 } 1247} 1248 1249function createAdminAuthInitCorsHeaders(request) { 1250 const allowedOrigin = resolveAdminAuthInitAllowedOrigin(request) 1251 1252 return { 1253 'access-control-allow-origin': allowedOrigin, 1254 'access-control-allow-methods': 'POST, OPTIONS', 1255 'access-control-allow-headers': 'Content-Type, Authorization', 1256 'access-control-max-age': '86400', 1257 vary: 'Origin', 1258 } 1259} 1260 1261function withAdminAuthInitCors(response, request) { 1262 const headers = createAdminAuthInitCorsHeaders(request) 1263`),e=e.replace("headers: createAdminAuthInitCorsHeaders(),","headers: createAdminAuthInitCorsHeaders(request),"),e=e.replace("if (request.method !== 'POST') return withAdminAuthInitCors(jsonResponse({ error: 'Method not allowed' }, 405))","if (request.method !== 'POST') return withAdminAuthInitCors(jsonResponse({ error: 'Method not allowed' }, 405), request)"),e=e.replace("return withAdminAuthInitCors(await handleAdminAuthInit(request, env))","return withAdminAuthInitCors(await handleAdminAuthInit(request, env), request)"),e=e.replace(` if (env.ASSETS) { 1264 const asset = await env.ASSETS.fetch(request) 1265 1266 if (asset.status !== 404) { 1267 return asset 1268 } 1269 1270 return env.ASSETS.fetch(new Request(new URL('/index.html', request.url), request)) 1271 }`,` if (env.ASSETS) { 1272 const asset = await env.ASSETS.fetch(request) 1273 1274 if (asset.status !== 404) { 1275 return asset 1276 } 1277 1278 if (request.method !== 'GET' && request.method !== 'HEAD') { 1279 return new Response('Not found', { status: 404 }) 1280 } 1281 1282 return env.ASSETS.fetch(
1283 new Request(new URL('/index.html', request.url), { 1284 method: request.method === 'HEAD' ? 'HEAD' : 'GET', 1285 headers: request.headers, 1286 }), 1287 ) 1288 }`),EI(e)}function zQ(t){let e=t;return e=e.replace('run_worker_first = ["/api/*"]','run_worker_first = ["/api/*", "/auth/complete"]'),e.includes('not_found_handling = "single-page-application"')||(e=e.replace(`binding = "ASSETS" 1289run_worker_first = ["/api/*", "/auth/complete"]`,`binding = "ASSETS" 1290run_worker_first = ["/api/*", "/auth/complete"] 1291not_found_handling = "single-page-application"`)),e.includes('binding = "AI_DB"')||(e=e.replace(/(\[\[d1_databases\]\]\s*\nbinding = "DB"[\s\S]*?(?:preview_database_id = "[^"]+"\s*))/,`$1 1292 1293[[d1_databases]] 1294binding = "AI_DB" 1295database_name = "cloudmysite_ai" 1296database_id = "50caa8f5-b72b-49cf-9e2d-27c5f39892e6" 1297preview_database_id = "50caa8f5-b72b-49cf-9e2d-27c5f39892e6" 1298`)),e}function VQ(t){let e=t;return e.includes("const AUTH_STATE_CONFIG_KEY = 'auth_config'")||(e=e.replace(`const AUTH_STATE_TABLE_SUFFIX = 'auth_state' 1299const AUTH_STATE_SESSION_SECRET_KEY = 'session_secret'`,`const AUTH_STATE_TABLE_SUFFIX = 'auth_state' 1300const AUTH_STATE_CONFIG_KEY = 'auth_config' 1301const AUTH_STATE_SESSION_SECRET_KEY = 'session_secret'`)),e=e.replace(`const setAdminAuthInitCorsHeaders = (response: ServerResponse) => { 1302 response.setHeader('access-control-allow-origin', '*') 1303 response.setHeader('access-control-allow-methods', 'POST, OPTIONS') 1304 response.setHeader('access-control-allow-headers', 'Content-Type') 1305 response.setHeader('access-control-max-age', '86400') 1306 response.setHeader('vary', 'Origin') 1307} 1308 1309const sendAdminAuthInitPreflight = (response: ServerResponse) => { 1310 setAdminAuthInitCorsHeaders(response) 1311`,`const resolveAdminAuthInitAllowedOrigin = (request: LocalDbRequest) => { 1312 const hostHeader = String(request.headers.host || '').trim() 1313 const originHeader = String(request.headers.origin || '').trim() 1314 1315 if (originHeader) { 1316 try { 1317 const originUrl = new URL(originHeader) 1318 1319 if (!hostHeader || originUrl.host === hostHeader) { 1320 return originUrl.origin 1321 } 1322 } catch {} 1323 } 1324 1325 if (hostHeader) { 1326 const protocolHeader = String(request.headers['x-forwarded-proto'] || '').trim().toLowerCase() 1327 const protocol = protocolHeader === 'https' ? 'https' : 'http' 1328 return protocol + '://' + hostHeader 1329 } 1330 1331 return originHeader || 'http://local' 1332} 1333 1334const setAdminAuthInitCorsHeaders = (response: ServerResponse, request: LocalDbRequest) => { 1335 response.setHeader('access-control-allow-origin', resolveAdminAuthInitAllowedOrigin(request)) 1336 response.setHeader('access-control-allow-methods', 'POST, OPTIONS') 1337 response.setHeader('access-control-allow-headers', 'Content-Type, Authorization') 1338 response.setHeader('access-control-max-age', '86400') 1339 response.setHeader('vary', 'Origin') 1340} 1341 1342const sendAdminAuthInitPreflight = (response: ServerResponse, request: LocalDbRequest) => { 1343 setAdminAuthInitCorsHeaders(response, request) 1344`),e=e.replace("setAdminAuthInitCorsHeaders(response)","setAdminAuthInitCorsHeaders(response, request)"),e=e.replace("sendAdminAuthInitPreflight(response)","sendAdminAuthInitPreflight(response, request)"),e.includes("const readPersistedLocalAuthSettingsPatch = (")||(e=e.replace(`const writeLocalAuthStateValue = ( 1345 state: LocalDbState, 1346 scope: string, 1347 key: string, 1348 value: string, 1349) => {
1350 const authStateTable = getOrCreateTable(state, getLocalAuthStateTableName(scope)) 1351 const existingRow = authStateTable.rows.find((candidate) => String(candidate.key || '') === key) || null 1352 1353 if (existingRow) { 1354 existingRow.value = String(value ?? '') 1355 existingRow.updated_at = new Date().toISOString() 1356 return 1357 } 1358 1359 const nextId = authStateTable.nextId++ 1360 authStateTable.rows.push({ 1361 rowid: nextId, 1362 id: nextId, 1363 key, 1364 value: String(value ?? ''), 1365 created_at: new Date().toISOString(), 1366 }) 1367} 1368`,`const writeLocalAuthStateValue = ( 1369 state: LocalDbState, 1370 scope: string, 1371 key: string, 1372 value: string, 1373) => { 1374 const authStateTable = getOrCreateTable(state, getLocalAuthStateTableName(scope)) 1375 const existingRow = authStateTable.rows.find((candidate) => String(candidate.key || '') === key) || null 1376 1377 if (existingRow) { 1378 existingRow.value = String(value ?? '') 1379 existingRow.updated_at = new Date().toISOString() 1380 return 1381 } 1382 1383 const nextId = authStateTable.nextId++ 1384 authStateTable.rows.push({ 1385 rowid: nextId, 1386 id: nextId, 1387 key, 1388 value: String(value ?? ''), 1389 created_at: new Date().toISOString(), 1390 }) 1391} 1392 1393const readPersistedLocalAuthSettingsPatch = ( 1394 state: LocalDbState, 1395 scope: string, 1396) => { 1397 const rawValue = readLocalAuthStateValue(state, scope, AUTH_STATE_CONFIG_KEY) 1398 1399 if (!rawValue) { 1400 return {} 1401 } 1402 1403 try { 1404 return normalizeAuthSettingsPatch(JSON.parse(rawValue)) 1405 } catch { 1406 return {} 1407 } 1408} 1409 1410const resolveLocalAuthConfig = async ( 1411 state: LocalDbState, 1412 request: IncomingMessage, 1413 baseConfig?: ReturnType<typeof normalizeAuthConfig>, 1414) => { 1415 const runtimeConfig = baseConfig || (await readRuntimeConfig()) 1416 const requestOrigin = \`http://\${request.headers.host || 'localhost'}\` 1417 const scope = resolveAuthScope(runtimeConfig, requestOrigin) 1418 const persistedPatch = readPersistedLocalAuthSettingsPatch(state, scope) 1419 1420 if (Object.keys(persistedPatch).length === 0) { 1421 return runtimeConfig 1422 } 1423 1424 const mergedConfig = normalizeAuthConfig({ 1425 app: { 1426 ...runtimeConfig.app, 1427 }, 1428 auth: { 1429 ...runtimeConfig.auth, 1430 ...persistedPatch, 1431 }, 1432 }) 1433 1434 if (JSON.stringify(mergedConfig) !== JSON.stringify(runtimeConfig)) { 1435 await writeRuntimeConfig(mergedConfig) 1436 } 1437 1438 return mergedConfig 1439} 1440`)),e.includes(`const incomingPatch = normalizeAuthSettingsPatch(options.auth) 1441 let config = options.config || (await readRuntimeConfig()) 1442 let dirty = false 1443`)||(e=e.replace(`const incomingPatch = normalizeAuthSettingsPatch(options.auth) 1444 let config = options.config || (await readRuntimeConfig()) 1445`,`const incomingPatch = normalizeAuthSettingsPatch(options.auth) 1446 let config = options.config || (await readRuntimeConfig()) 1447 let dirty = false 1448`)),e.includes(` writeLocalAuthStateValue(state, scope, AUTH_STATE_CONFIG_KEY, JSON.stringify(incomingPatch)) 1449 dirty = true 1450 } 1451 1452 config = await resolveLocalAuthConfig(state, request, config) 1453 const scope = resolveAuthScope(config, \`http://\${request.headers.host || 'localhost'}\`) 1454`)||(e=e.replace(` await writeRuntimeConfig(config) 1455 } 1456 1457 const scope = resolveAuthScope(config, \`http://\${request.headers.host || 'localhost'}\`) 1458`,` await writeRuntimeConfig(config) 1459 1460 const scope = resolveAuthScope(config, \`http://\${request.headers.host || 'localhost'}\`) 1461 writeLocalAuthStateValue(state, scope, AUTH_STATE_CONFIG_KEY, JSON.stringify(incomingPatch)) 1462 dirty = true 1463 } 1464 1465 config = await resolveLocalAuthConfig(state, request, config) 1466 const scope = resolveAuthScope(config, \`http://\${request.headers.host || 'localhost'}\`) 1467`)),e=e.replace(` const alreadyInitialized = authConfig.auth.enabled 1468 ? isLocalAuthRuntimeReady(state, authConfig.app.slug, bindings) 1469 : false 1470 let dirty = false 1471 let runtime = { 1472`,` const alreadyInitialized = authConfig.auth.enabled 1473 ? isLocalAuthRuntimeReady(state, authConfig.app.slug, bindings) 1474 : false 1475 let runtime = { 1476`),e.includes(" const config = await readRuntimeConfig()")&&(e=e.replace(" const config = await readRuntimeConfig()"," const config = await resolveLocalAuthConfig(state, request)")),e.includes(` const ensureLocalAuthBootstrap = async (request: LocalDbRequest) => { 1477 const config = await readRuntimeConfig() 1478`)&&(e=e.replace(` const ensureLocalAuthBootstrap = async (request: LocalDbRequest) => { 1479 const config = await readRuntimeConfig() 1480 1481 if (!config.auth.enabled) { 1482 return 1483 } 1484 1485 const state = await readState() 1486`,` const ensureLocalAuthBootstrap = async (request: LocalDbRequest) => { 1487 const state = await readState() 1488 const config = await resolveLocalAuthConfig(state, request) 1489 1490 if (!config.auth.enabled) { 1491 return 1492 } 1493 1494`)),e=e.replace(` let config = options.config || (await readRuntimeConfig()) 1495 let dirty = false 1496 let dirty = false
1497`,` let config = options.config || (await readRuntimeConfig()) 1498 let dirty = false 1499`),eE(e)}function GQ(t){let e=t;return e.includes("normalizeAppSchemaTokenWithFallback")||(e=e.replace(`const normalizeLookupToken = (value: string) => 1500 String(value || '') 1501 .replace(/([a-z0-9])([A-Z])/g, '$1_$2') 1502 .toLowerCase() 1503 .replace(/[^a-z0-9]/g, ''); 1504 1505export const normalizeAppSchemaToken = (value: string): string => { 1506 const normalized = String(value || '') 1507 .replace(/([a-z0-9])([A-Z])/g, '$1_$2') 1508 .toLowerCase() 1509 .replace(/[^a-z0-9_]/g, '_') 1510 .replace(/_+/g, '_') 1511 .replace(/^_+|_+$/g, ''); 1512 1513 if (!normalized) { 1514 throw new Error('Invalid app schema token.'); 1515 } 1516 1517 return normalized; 1518};`,`const normalizeLookupToken = (value: string) => 1519 String(value || '') 1520 .replace(/([a-z0-9])([A-Z])/g, '$1_$2') 1521 .toLowerCase() 1522 .replace(/[^a-z0-9]/g, ''); 1523 1524const normalizeAppSchemaTokenValue = (value: string): string => 1525 String(value || '') 1526 .replace(/([a-z0-9])([A-Z])/g, '$1_$2') 1527 .toLowerCase() 1528 .replace(/[^a-z0-9_]/g, '_') 1529 .replace(/_+/g, '_') 1530 .replace(/^_+|_+$/g, ''); 1531 1532const normalizeAppSchemaTokenWithFallback = (value: string, fallback: string): string => { 1533 const normalized = normalizeAppSchemaTokenValue(value); 1534 1535 if (normalized) { 1536 return normalized; 1537 } 1538 1539 const normalizedFallback = normalizeAppSchemaTokenValue(fallback); 1540 return normalizedFallback || 'app'; 1541}; 1542 1543export const normalizeAppSchemaToken = (value: string): string => { 1544 const normalized = normalizeAppSchemaTokenValue(value); 1545 1546 if (!normalized) { 1547 throw new Error('Invalid app schema token.'); 1548 } 1549 1550 return normalized; 1551};`)),e=e.replace("export const buildAppEntityTableName = (appSlug: string, entityName: string): string =>\n `app_${normalizeAppSchemaToken(appSlug)}_${normalizeAppSchemaToken(entityName)}`;","export const buildAppEntityTableName = (appSlug: string, entityName: string): string =>\n `app_${normalizeAppSchemaTokenWithFallback(appSlug, 'app')}_${normalizeAppSchemaTokenWithFallback(entityName, 'entity')}`;"),e=e.replace(" return entity.fields.find((field) => field.keyToken === lookupToken || field.columnName === normalizeAppSchemaToken(inputKey));",` return entity.fields.find( 1552 (field) => field.keyToken === lookupToken || field.columnName === normalizeAppSchemaTokenWithFallback(inputKey, 'field'), 1553 );`),e=e.replace(" const normalizedValue = normalizeAppSchemaToken(value);"," const normalizedValue = normalizeAppSchemaTokenWithFallback(value, 'column');"),e=e.replace(" const appToken = normalizeAppSchemaToken(input.app);"," const appToken = normalizeAppSchemaTokenWithFallback(input.app, 'app');"),e=e.replace(" const entities = entityEntries.map(([entityName, entityInput]) => {"," const entities = entityEntries.map(([entityName, entityInput], entityIndex) => {"),e=e.replace(" const entityToken = normalizeAppSchemaToken(entityName);"," const entityToken = normalizeAppSchemaTokenWithFallback(entityName, `entity_${entityIndex + 1}`);"),e=e.replace(` const fields = fieldEntries.map(([fieldKey, fieldInput]) => { 1554 const normalizedInput = toFieldInputObject(fieldInput); 1555 1556 return { 1557 key: fieldKey, 1558 keyToken: normalizeLookupToken(fieldKey), 1559 columnName: normalizeAppSchemaToken(normalizedInput.column || fieldKey),`,` const fields = fieldEntries.map(([fieldKey, fieldInput], fieldIndex) => { 1560 const normalizedInput = toFieldInputObject(fieldInput); 1561 const fallbackFieldToken = \`field_\${fieldIndex + 1}\`; 1562 const resolvedFieldKey = fieldKey || fallbackFieldToken; 1563 1564 return { 1565 key: resolvedFieldKey, 1566 keyToken: normalizeLookupToken(resolvedFieldKey), 1567 columnName: normalizeAppSchemaTokenWithFallback(normalizedInput.column || resolvedFieldKey, fallbackFieldToken),`),e=e.replace(` entity: normalizeAppSchemaToken(normalizedInput.references.entity), 1568 field: normalizeAppSchemaToken(normalizedInput.references.field || 'id'),`,` entity: normalizeAppSchemaTokenWithFallback(normalizedInput.references.entity, entityToken), 1569 field: normalizeAppSchemaTokenWithFallback(normalizedInput.references.field || 'id', 'id'),`),e=e.replace(" normalizeAppSchemaToken(\n index.name ||\n `${entitySchema.tableName}_${index.columns.map((columnName) => resolveIndexColumnName(entitySchema, columnName)).join('_')}_${index.unique ? 'uidx' : 'idx'}`,\n ),"," normalizeAppSchemaTokenWithFallback(\n index.name ||\n `${entitySchema.tableName}_${index.columns.map((columnName) => resolveIndexColumnName(entitySchema, columnName)).join('_')}_${index.unique ? 'uidx' : 'idx'}`,\n `${entitySchema.tableName}_${indexPosition + 1}_${index.unique ? 'uidx' : 'idx'}`,\n ),"),e=e.replace(" app: input.app,"," app: String(input.app || '').trim() || appToken,"),e}function qQ(t,e={}){try{const r=JSON.parse(t);
1569let n={...r.dependencies||{}},s={...r.devDependencies||{}};const i=r.scripts?{...r.scripts}:void 0;let a=!1;if(e.ensureReactRouter!==!1&&!n["react-router-dom"]&&(n["react-router-dom"]=IQ,a=!0),e.optimizeViteReactPreview){if(e.keepThreeDDependencies)for(const[l,c]of Object.entries(UN))n[l]||(n[l]=c,a=!0);else{const l=AA(n,NQ);n=l.next,a=a||l.removedAny}const o=AA(s,LQ);s=o.next,a=a||o.removedAny,i&&Object.prototype.hasOwnProperty.call(i,"lint")&&(delete i.lint,a=!0)}return a?`${JSON.stringify({...r,...i?{scripts:i}:{},dependencies:n,...r.devDependencies||Object.keys(s).length>0?{devDependencies:s}:{}},null,2)} 1570`:t}catch{return t}}function KQ(t){return t.includes("import { BrowserRouter } from 'react-router-dom'")&&t.includes("<BrowserRouter>")?t:$Q}const YQ=`name: Build (CloudMySite) 1571 1572on: 1573 push: 1574 branches: [main] 1575 1576jobs: 1577 build: 1578 runs-on: ubuntu-latest 1579 permissions: 1580 contents: read 1581 1582 steps: 1583 - uses: actions/checkout@v5 1584 1585 - uses: actions/setup-node@v5 1586 with: 1587 node-version: 22 1588 1589 - name: Install dependencies 1590 shell: bash 1591 run: | 1592 set -euo pipefail 1593 1594 if [ -f pnpm-lock.yaml ]; then 1595 corepack enable 1596 pnpm install 1597 elif [ -f yarn.lock ]; then 1598 corepack enable 1599 yarn install 1600 else 1601 npm install 1602 fi 1603 1604 - name: Fix TypeScript build issues (AI-generated apps) 1605 shell: bash 1606 run: | 1607 set -euo pipefail 1608 1609 if [ -f package.json ]; then 1610 if grep -q "tsc -b" package.json; then 1611 echo "Fixing build script for Vite projects..." 1612 node -e " 1613 const fs=require('fs'); 1614 const p=JSON.parse(fs.readFileSync('package.json','utf8')); 1615 if(p.scripts && p.scripts.build && p.scripts.build.includes('tsc')){ 1616 p.scripts.build='vite build'; 1617 fs.writeFileSync('package.json',JSON.stringify(p,null,2)); 1618 } 1619 " 1620 fi 1621 fi 1622 1623 - name: Repair protected runtime files 1624 shell: bash 1625 run: | 1626 set -euo pipefail 1627 1628 node <<'NODE' 1629 const fs = require('fs'); 1630 1631 const repairs = [ 1632 { 1633 path: 'js/db-runtime.js', 1634 broken: '${WN}', 1635 fixed: '${HN}', 1636 }, 1637 ]; 1638 1639 let repairedAny = false; 1640 1641 for (const repair of repairs) { 1642 if (!fs.existsSync(repair.path)) { 1643 continue; 1644 } 1645 1646 const currentContent = fs.readFileSync(repair.path, 'utf8'); 1647 1648 if (!currentContent.includes(repair.broken)) { 1649 continue; 1650 } 1651 1652 fs.writeFileSync(repair.path, currentContent.split(repair.broken).join(repair.fixed)); 1653 repairedAny = true; 1654 console.log('Repaired known protected runtime corruption in ' + repair.path); 1655 } 1656 1657 if (!repairedAny) { 1658 console.log('No protected runtime repairs were needed.'); 1659 } 1660 NODE 1661 1662 - name: Build 1663 shell: bash 1664 run: | 1665 set -euo pipefail 1666 if npm run | grep -qE '^[[:space:]]+build'; then 1667 npm run build 1668 elif [ -f package.json ] && grep -q '"expo"' package.json; then 1669 npx expo export --platform web --output-dir dist 1670 else 1671 echo "No build script found and not an Expo web export project." 1672 exit 1 1673 fi 1674 1675`;function XQ(t,e,r,n={}){let s=!1;const i=t.map(p=>{if(p.path===".github/workflows/deploy.yml"&&p.encoding!=="base64")return{...p,content:YQ};if(p.path==="js/db-runtime.js"&&p.encoding!=="base64"){const y=p.content.split(WN).join(HN);return y!==p.content&&console.info("[template.import] repaired known db-runtime created_at index corruption in js/db-runtime.js"),{...p,content:y}}if(p.path==="js/auth-worker.js"&&p.encoding!=="base64"){const y=BQ(p.content);return y!==p.content&&console.info("[template.import] repaired auth-worker user readback flow in js/auth-worker.js"),{...p,content:y}}if(p.path==="js/auth-runtime.js"&&p.encoding!=="base64"){const y=FQ(p.content);return y!==p.content&&console.info("[template.import] repaired auth-runtime password hashing settings in js/auth-runtime.js"),{...p,content:y}}if(p.path==="src/lib/appSchema.ts"&&p.encoding!=="base64"){const y=GQ(p.content);return y!==p.content&&console.info("[template.import] hardened appSchema token normalization in src/lib/appSchema.ts"),{...p,content:y}}if(p.path==="src/lib/appAuth.tsx"&&p.encoding!=="base64"){const y=WQ(p.content);return y!==p.content&&console.info("[template.import] hardened appAuth redirect sanitization in src/lib/appAuth.tsx"),{...p,content:y}}if(p.path==="src/lib/cloudMySiteForms.ts"&&p.encoding!=="base64"){const y=_M(p.content);return y!==p.content&&console.info("[template.import] repaired src/lib/cloudMySiteForms.ts for proxy-based submit routing"),{...p,content:y}}if(p.path==="src/components/forms/CloudMySiteContactForm.tsx"&&p.encoding!=="base64"){const y=xM(
1675p.content);return y!==p.content&&console.info("[template.import] repaired CloudMySiteContactForm.tsx to use the same-origin submit proxy"),{...p,content:y}}if(p.path==="js/worker.js"&&p.encoding!=="base64"){const y=UQ(p.content);return y!==p.content&&console.info("[template.import] hardened js/worker.js for admin auth and SPA asset fallback"),{...p,content:y}}if(p.path==="wrangler.toml"&&p.encoding!=="base64"){const y=zQ(p.content);return y!==p.content&&console.info("[template.import] enabled SPA asset fallback in wrangler.toml"),{...p,content:y}}if(p.path==="vite.local-db.ts"&&p.encoding!=="base64"){const y=VQ(p.content);return y!==p.content&&console.info("[template.import] hardened vite.local-db.ts for admin auth"),{...p,content:y}}if(p.path==="package.json"&&p.encoding!=="base64"){const y=qQ(p.content,{optimizeViteReactPreview:e==="Vite React",keepThreeDDependencies:MQ(n.prompt),ensureReactRouter:e!=="Phaser Vite"});return y!==p.content&&(s=!0,console.info(e==="Vite React"?"[template.import] optimized Vite React package.json for faster preview installs":"[template.import] repaired package.json for the selected template")),{...p,content:y}}if(p.path==="src/main.tsx"&&p.encoding!=="base64"){const y=KQ(p.content);return y!==p.content&&console.info("[template.import] ensured BrowserRouter root shell in src/main.tsx"),{...p,content:y}}return p}),a=i.find(p=>p.path==="package.json"&&p.encoding!=="base64")?.content;let o=i.flatMap(p=>{if(p.path==="package-lock.json"&&p.encoding!=="base64"&&a){const y=AD(p.content,a);return y?(y!==p.content&&console.info("[template.import] synchronized package-lock.json with the preview package manifest"),[{...p,content:y}]):(console.info("[template.import] removed package-lock.json because it does not cover the preview dependencies"),[])}return s&&zN.has(p.path)?(console.info(`[template.import] removed stale ${p.path} after repairing package.json`),[]):[p]});const l=o.findIndex(p=>p.encoding!=="base64"&&/^(?:src\/(?:index|main|style|styles)|app\/globals|styles\/globals|style)\.(?:css|scss|sass)$/i.test(p.path));if(l>=0&&(o[l].content.includes("cloudmysite-responsive-baseline")||(o=o.map((y,v)=>v===l?{...y,content:`${$1} 1676 1677${y.content}`}:y))),e===uo)return o.map(p=>p.encoding==="base64"?p:p.path===".eleventy.js"||p.path==="eleventy.config.js"?{...p,content:ED(p.content)}:p);if(e==="Vanilla Vite"){const p=(r||"").trim()||"My App",v=[...o.filter(w=>{const C=OQ.has(w.path);return C&&console.info(`[template.import] removed ${w.path} from Vanilla Vite import for dependency-free preview`),!C}).map(w=>w.encoding==="base64"?w:w.path==="index.html"?{...w,content:EA(p)}:w.path==="main.js"?{...w,content:kA(p)}:w.path==="style.css"?{...w,content:PA}:w)],_=(w,C)=>{v.some(A=>A.path===w)||v.push({name:w.split("/").pop()||w,path:w,content:C})};return _("index.html",EA(p)),_("main.js",kA(p)),_("style.css",PA),_("favicon.svg",CA),v}if(e!=="Vite React")return o;const c=(r||"").trim()||"My App",u=P0(c),d=h0(kn(c)||"my_app"),h=o.map(p=>{if(p.encoding==="base64")return p;if(p.path==="index.html"){let y=p.content.replace(/<title>[\s\S]*?<\/title>/i,`<title>${u}</title>`);return y=y.replace(/href="\/vite\.svg"/i,'href="/favicon.svg"'),/rel="icon"/i.test(y)||(y=y.replace(/<meta name="viewport"[\s\S]*?\/>/i,`<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> 1678 $&`)),{...p,content:y}}if(p.path==="app.config.json"){const y=Ay(c,d);try{const v=JSON.parse(p.content),_={...y,...v,app:{...y.app,...v?.app&&typeof v.app=="object"?v.app:{},name:c,slug:d},auth:v?.auth&&typeof v.auth=="object"?{...y.auth,...v.auth}:y.auth};return{...p,content:Kf(_)}}catch{return{...p,content:Kf(y)}}}return p}),m=h.find(p=>p.path==="app.config.json"&&p.encoding!=="base64");if(m){const p=h.findIndex(y=>y.path==="public/app.config.json"&&y.encoding!=="base64");p>=0?h[p]={...h[p],content:m.content}:h.push({name:"app.config.json",path:"public/app.config.json",content:m.content,encoding:"utf-8"})}if(h.some(p=>p.path==="public/favicon.svg")||h.push({name:"favicon.svg",path:"public/favicon.svg",content:CA,encoding:"utf-8"}),!h.some(p=>p.path==="app.config.json")){const p=Kf(Ay(c,d));h.push({name:"app.config.json",path:"app.config.json",content:p,encoding:"utf-8"}),h.push({name:"app.config.json",path:"public/app.config.json",content:p,encoding:"utf-8"})}return h}const JQ=async t=>{const{message:e,isEleventy:r,fallbackTemplateName:n}=t,s=Uy(n)||np;if(r)return{template:uo,title:"My Website"};const i=Uy(EQ(e));return i?{template:i,title:SA(e)}:{template:s,title:SA(e)}},QQ=async t=>{try{const e=await fetch(`/api/github-template?repo=${encodeURIComponent(t)}`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!e.ok){let i="";try{const a=await e.json();i=a?.details||a?.error||""}catch{}throw new Error(`HTTP error! status: ${e.status}${i?` - ${i}`:""}`)}const r=await e.json(),n={repo:e.headers.get("X-Template-Repo")||t,source:e.headers.get("X-Template-Source")||"unknown",fetcher:e.headers.get("X-Template-Fetcher")||"unknown",localPath:e.headers.get("X-Template-Local-Path")||void 0,fileCount:Number(e.headers.get("X-Template-File-Count"))||r.length,deployWorkflow:e.headers.get("X-Template-Deploy-Workflow")==="true",cloudflareRuntime:e.headers.get("X-Template-Cloudflare-Runtime")==="true"},s={appAuthTsx:r.some(i=>i.path==="src/lib/appAuth.tsx"),mainTsx:r.some(i=>i.path==="src/main.tsx"),mainJsx:r.some(i=>i.path==="src/main.jsx"),authContextJsx:r.some(i=>i.path==="src/contexts/AuthContext.jsx"),workerRuntime:r.some(i=>i.path==="js/worker.js"),deployWorkflow:r.some(i=>i.path===".github/workflows/deploy.yml")};return console.info(`[template.fetch] repo="${n.repo}" source="${n.source}" fetcher="${n.fetcher}" files=${n.fileCount} cloudflareRuntime=${n.cloudflareRuntime} markers=${JSON.stringify(s)}`),{files:r,metadata:n}}catch(e){throw console.error("Error fetching release contents:",e),e}};async function TA(t,e,r={}){const n=Mf.find(X=>X.name==t),s=t===uo;if(!n&&!s)return null;const i=n?.name||uo,a=s?pD:n.githubRepo,{files:o,metadata:l}=await QQ(a),c=o.some(X=>X.path===".github/workflows/deploy.yml");console.info(`[template.import] template="${i}" repo="${a}" fetchedFiles=${o.length} deployWorkflowInSource=${c}`);let u=XQ(o,i,e,r);u=u.filter(X=>X.path!==".git"&&X.path.startsWith(".git/")==!1);const d=u.some(X=>X.path===".github/workflows/deploy.yml");console.info(`[template.import] template="${i}" repo="${a}" afterGitFilter=${u.length} deployWorkflowAfterGitFilter=${d}`),u=u.filter(X=>X.path.startsWith(".bolt")==!1);const h=o.find(X=>X.path.startsWith(".bolt")&&X.name=="ignore"),m={files:u,ignoreFile:[]};if(h){const X=h.content.split(` 1679`).map(F=>F.trim()),oe=wD().add(X),L=u.filter(F=>oe.ignores(F.path));m.files=u,m.ignoreFile=L}const b=m.files.some(X=>X.path===".github/workflows/deploy.yml"),g=m.ignoreFile.some(X=>X.path===".github/workflows/deploy.yml");console.info(`[template.import] template="${i}" repo="${a}" importFiles=${m.files.length} ignoredFiles=${m.ignoreFile.length} deployWorkflowInImportSet=${b} deployWorkflowIgnored=${g}`);const p=await SD(m.files.filter(X=>typeof X.content=="string"&&X.encoding!=="base64").map(X=>({path:X.path,content:X.content}))),y=CD(p).trim(),v=!!p.setupCommand,_=p.setupCommand?`\`${p.setupCommand}\``:"`npm install`",w=p.startCommand?`\`${p.startCommand}\``:"`npm run dev`",C=p.type==="Static"&&!!p.startCommand&&!v,A=i==="Expo App"?`IMPORTANT: Use Expo-compatible dependencies and avoid deprecated packages like \`react-query\`, \`react-native-vector-icons\`, and \`@react-navigation/stack\`. The platform will install dependencies with ${_} and start the app with ${w} after your files finish streaming, so do not emit setup or start shell actions.`:v?`IMPORTANT: The platform will install dependencies with ${_} and start the app with ${w} after your files finish streaming. Declare every required package in package.json, but do not emit setup, install, build, or start shell actions.`:C?`IMPORTANT: This imported project is dependency-free for preview. Start it with ${w}. Do not add npm dependencies unless the user's request genuinely requires them.`:"IMPORTANT: No depen
1679dency installation step was detected. Keep the project dependency-free unless the user's request genuinely requires packages.",E=!C&&(i==="Vite React"||i==="Vanilla Vite"||i==="Phaser Vite"||i==="Vite Typescript"||i==="Vite Shadcn"),S=i==="Vanilla Vite"||i===uo,k=i==="Phaser Vite",O=m.files,T=m.files.filter(X=>X.path==="package-lock.json"),R=m.files.filter(X=>X.path!=="package-lock.json"),N=y.length>0&&!v?` 1680<boltArtifact id="template-bootstrap" title="Template bootstrap" type="bundled"> 1681${y} 1682</boltArtifact>`:"",M=` 1683<boltArtifact id="starter-template-files" title="${e||"Create initial files"}" type="bundled"> 1684${R.map(X=>`<boltAction type="file" filePath="${X.path}"${X.encoding==="base64"?' encoding="base64"':""}> 1685${X.content} 1686</boltAction>`).join(` 1687`)} 1688</boltArtifact>${N} 1689`;let B="";const U=o.filter(X=>X.path.startsWith(".bolt")).find(X=>X.name=="prompt");return U&&(B=` 1690TEMPLATE INSTRUCTIONS: 1691${U.content} 1692 1693--- 1694`),m.ignoreFile.length>0&&(B=B+` 1695STRICT FILE ACCESS RULES - READ CAREFULLY: 1696 1697The following files are READ-ONLY and must never be modified: 1698${m.ignoreFile.map(X=>`- ${X.path}`).join(` 1699`)} 1700 1701Permitted actions: 1702â Import these files as dependencies 1703â Read from these files 1704â Reference these files 1705 1706Strictly forbidden actions: 1707â Modify any content within these files 1708â Delete these files 1709â Rename these files 1710â Move these files 1711â Create new versions of these files 1712â Suggest changes to these files 1713 1714Any attempt to modify these protected files will result in immediate termination of the operation. 1715 1716If you need to make changes to functionality, create new files instead of modifying the protected ones listed above. 1717--- 1718`),B+=` 1719--- 1720template import is done, and you can now use the imported files,
1721edit only the files that need to be changed, and you can create new files as needed. 1722NO NOT EDIT/WRITE ANY FILES THAT ALREADY EXIST IN THE PROJECT AND DOES NOT NEED TO BE MODIFIED 1723Replace default placeholder UI and wire your implementation into the app entry flow. 1724For React templates, update \`src/App.tsx\` (and related imports) so the requested feature is visible on first load. 1725For browser-based templates, replace placeholder browser metadata. \`index.html\` must use an app-appropriate \`<title>\` and keep a real favicon reference instead of default Vite placeholders. 1726 1727IMPORTANT FILE PRESERVATION RULES: 1728- Do NOT delete or remove any files unless the user explicitly requests deletion. 1729- Do NOT remove or revert freshly created or edited files. 1730- There is no concept of temporary or unused files; all files remain valid unless the user says otherwise. 1731 1732--- 1733Now that the Template is imported please continue with my original request 1734 1735**CRITICAL**: You MUST create ALL pages/sections requested in the original prompt. Do NOT just modify the existing template files. Create new page files for each distinct page/section mentioned in the user's request. 1736 1737${i===uo?"ELEVENTY SOURCE-OF-TRUTH RULES:\n- Never create or edit files under `public/` directly.\n- For styling and assets, only edit source folders: `css/`, `js/`, `images/`, `assets/`, `workspace-assets/`, and `src/`.\n- `public/` is generated build output and will be overwritten.\n- Uploaded website images should live under `workspace-assets/` in source and be referenced with URLs like `/workspace-assets/example.png`.\n- Never edit, rename, or delete `.eleventy.js` (or `eleventy.config.js`) unless the user explicitly asks.\n- The template includes `src/pages/index.html` as the root page. CREATE ADDITIONAL PAGE FILES for each distinct page requested.\n- For single HTML browser game requests, keep the implementation in the source root page (`src/pages/index.html`) with inline CSS and JavaScript unless the user explicitly asks for more files or pages.\n- For multi-page websites (which most requests are), create separate files under `src/pages/`: `about.html`, `skills.html`, `projects.html`, `blog.html`, `contact.html`, etc.\n- Each page under `src/pages/` must use a unique `permalink` in frontmatter and must not use `/` or `/index.html`.\n- Example: `src/pages/about.html` should have `permalink: /about/`, `src/pages/projects.html` should have `permalink: /projects/`.\n- Before finishing, verify no two pages write to the same output path.\n- Nunjucks in this template does not support `{% break %}` or `{% continue %}`; never use those tags.\n- Never use a Nunjucks filter unless it already exists in the project config (for example, do not assume a `date` filter exists).\n- Update `src/_partials/header.html` to include navigation links to ALL pages you created.\n---":""} 1738${E?'VITE BUILD RULES:\n- Use `<script type="module" ...>` for app entry points in `index.html`.\n- If you intentionally use non-module static files like `script.js` or `style.css`, place them under `public/` and reference them as root paths (for example `/script.js`, `/style.css`).\n- Do not rely on root non-module files being bundled by Vite automatically.\n- In JSX/TSX text nodes, never use raw `<` or `>` characters (example: write `(<500B)` instead of `(<500B)`).\n---':""} 1739${S?'PLAIN HTML/CANVAS GENERATION RULES:\n- If the user asks for "single HTML file", "HTML5 Canvas", "Canvas and JavaScript", "vanilla JavaScript", or "plain HTML/CSS/JS", do not convert the request into React, TSX, or Phaser.\n- For a single HTML game in Vanilla Vite, prefer one `index.html` file with inline `<style>` and `<script>` containing CSS, JavaScript, and game logic. Use `main.js` or `src/main.js` only when the selected template\'s existing entry flow requires it.\n- For dependency-free Vanilla Vite previews, keep JavaScript browser-native: do not import CSS files, image assets, npm packages, or local modules from `main.js` unless you also keep valid browser script wiring in `index.html`.\n- For a single HTML game in the Eleventy static template, implement the source page in `src/pages/index.html` with inline CSS and JavaScript; do not edit generated `public/` output directly.\n- Plain 2D browser games should use the HTML5 Canvas API, `requestAnimationFrame`, and vanilla JavaScript.\n- Board/UI games such as Tic Tac Toe, Connect Four, memory cards, quizzes, and other DOM-first games should use semantic HTML controls, CSS, and vanilla JavaScript DOM updates instead of Canvas unless the user asked for Canvas.\n- Do not add npm dependencies unless the requested feature truly requires them.\n- Do not import Phaser or add a Phaser dependency unless the user explicitly requested Phaser by name.\n- Do not use React unless the user explicitly requested React or the app genuinely needs React-style UI/state management beyond the game canvas.\n- For 3D browser games, prefer the React/Vite app template rather than this Vanilla Vite template unless the user explicitly asked for a single-file or plain
1739non-React 3D implementation.\n---':""} 1740${k?`PHASER TEMPLATE RULES: 1741- Use Phaser only because this template was selected for an explicit Phaser request. 1742- Keep Phaser imports backed by the template's \`package.json\` dependency. 1743- Do not introduce React unless the user explicitly requested a React UI around the Phaser game. 1744---`:`PHASER GUARDRAIL: 1745- Do not import Phaser, reference \`phaser\`, or add a Phaser npm dependency unless the user's original request explicitly asked for Phaser. 1746- If the user asked for Canvas, vanilla JavaScript, plain HTML/CSS/JS, or a single HTML file, implement the game with browser APIs instead of Phaser. 1747---`} 1748${i==="Vite React"?"APP DATA PERSISTENCE RULES:\n- The template exposes four built-in data endpoints:\n - `GET /api/db/select?table=...` for reads\n - `POST /api/db/insert` for creates only\n - `POST /api/db/update` for updates to an existing row by `id`\n - `POST /api/db/delete` for deletes by `id`\n- The template also exposes `POST /api/db/ensure-schema` to create app tables safely with `CREATE TABLE IF NOT EXISTS` and additive schema updates.\n- For apps that manage user-created records, the built-in persistence API must remain the primary source of truth in published environments. Do not build the main CRUD flow as localStorage-only.\n- If `src/lib/appData.ts` and `src/lib/appSchema.ts` exist, use them for schema definition, table-name resolution, and CRUD requests.\n- If only `src/lib/cloudflareCrud.ts` exists, you may use it as an internal adapter, but keep user-facing copy and summaries infrastructure-neutral.\n- Treat `src/lib/appSchema.ts`, `src/lib/appData.ts`, `src/lib/cloudflareCrud.ts`, `js/auth-runtime.js`, `js/auth-worker.js`, and `js/db-runtime.js` as platform infrastructure. Do not modify those files unless the user explicitly asks to change platform internals.\n- You may extend `js/worker.js` and `vite.local-db.ts` with app-specific `/api/*` routes when a feature needs secure server-side logic (for example Stripe checkout), but keep the built-in auth/db/secret-status routes intact and do not rewrite platform internals wholesale.\n- Keep `vite.config.ts` importing `createLocalDbApiPlugin` from `./vite.local-db` and registering `createLocalDbApiPlugin()` in the Vite `plugins` array so built-in `/api/auth/*` and `/api/db/*` endpoints return JSON in preview.\n- Define app-specific schemas in app files by importing `defineAppSchema`; do not rewrite the schema library itself.\n- Keep the template export contract intact: `defineAppSchema` comes from `src/lib/appSchema.ts`, `ensureAppSchema` comes from `src/lib/appData.ts`, and `buildAppSchemaWorkerPayload` must continue returning `{ app, tables }`.\n- Never create circular imports between `src/lib/appSchema.ts` and `src/lib/appData.ts`.\n- For apps with more than one entity type, define an explicit schema with `defineAppSchema({ app, entities })` and call `ensureAppSchema(appSchema)` during app startup before the first CRUD fetch.\n- In `defineAppSchema({ app, entities })`, the `app` value must be a non-empty stable slug token such as `gujarati_restaurant` or the existing `app.config.json` slug. Never pass an empty string, an undefined variable, or punctuation-only display text as the schema app key.\n- Use one table per entity. Never mix different entity types into one generic `records` table.\n- Entity tables must be named `app_<appname>_<entity>`. Example: `app_customer_contact_manager_contacts`, `app_customer_contact_manager_interactions`.\n- Prefer the entity helpers from `src/lib/appData.ts`: `getAppEntityTableName`, `selectAppEntityRows`, `insertAppEntityRow`, `updateAppEntityRow`, and `deleteAppEntityRow`.\n- If you use low-level CRUD helpers directly, resolve the table with the schema helper instead of hardcoding one shared table for multiple entities.\n- Preserve relationships with explicit foreign-key columns such as `contact_id` that reference the parent entity's `id`.\n- localStorage may be used only as a cache or offline fallback. A successful-looking UI change must also persist through the built-in API.\n- Never replace a real persistence layer with mock data, no-op CRUD helpers, or local-only sample data just to silence preview errors.\n- If local preview needs fallback behavior, preserve the same API contract so the published app still saves real data.\n- Never implement updates by sending existing records back to `/api/db/insert`. That creates duplicate rows in persisted storage and breaks delete behavior after refresh.\n- For repeated domain content such as menus, products, services, locations, destinations, team members, FAQs, testimonials, galleries, courses, events, packages, properties, or any item list shown in the UI, treat the persisted entity rows as the source of truth. Do not only edit page JSX or swap in static arrays if the screen reads from stored rows.\n- Before changing a screen that shows repeated content, inspect the imported hooks, stores, schema objects, and seed/default data files that feed that screen. If the request changes the collection itself, update the backing data flow and not just the rendered page markup.\n- If starter/default rows are needed, keep their sync idempotent: seed only when the table is truly empty or reconcile by stable keys, avoid duplicate inserts during React StrictMode or refresh retries, preserve custom/user-created rows, and safely repair stale seeded rows instead of silently reintroducing deleted content.\n- When building client-side CRUD flows, check `response.ok`, validate the response type, and keep local UI state consistent with the saved result.\n- In user-facing UI copy, status text, summaries, and explanations, describe this generically as saved data or persistent storage. Do not mention Cloudflare, D1, workers, bindings, or other infrastru
1748cture details unless the user explicitly asks.\n- Unless the user explicitly asks for another language, keep all user-facing copy in English. This includes headings, labels, button text, validation, checkout feedback, confirmation messages, and error states.\n- If the app uses an external integration such as OpenAI, Stripe, SendGrid, Slack, Resend, or another third-party API, define the required server-side secrets in `src/lib/appSecrets.ts` with `defineAppIntegrations(...)`.\n- For generic payment features such as checkout, accepting payments, selling products, deposits, subscriptions, or billing, build provider-neutral checkout UI and order-summary flows. Do not mention Stripe, Admin -> Stripe, API keys, checkout-session routes, or webhooks in generated user-facing copy unless the user explicitly asks for Stripe.\n- Generic checkout UI should collect only pre-checkout details such as email, quantity, shipping, plan choice, or order summary. Do not collect raw card number, expiry, CVV, or similar payment fields. Do not render fake card-entry areas or placeholder panels that say a payment provider will appear later; hosted checkout providers show the real payment form after redirect.\n- For checkout contact and shipping fields, use standard `name`, `id`, and `autoComplete` values such as `email`, `given-name`, `family-name`, `street-address`, `address-line1`, `address-line2`, `address-level2`, `address-level1`, `postal-code`, and `country` so the checkout action can reuse entered details.\n- Keep generic checkout actions local and honest: show order review, pending/unavailable payment processing, or provider-neutral copy such as \"Payment processing can be enabled later.\" Do not fake a completed live payment.\n\n**EXPLICIT STRIPE CHECKOUT IMPLEMENTATION RULES:**\n- Apply these rules only when the user explicitly asks for Stripe or Admin -> Stripe binding patches a selected checkout target.\n- Templates do not ship live Stripe checkout routes by default. Keep first-pass checkout, pricing, subscription, and buy-button UI provider-neutral and admin-configurable.\n- Live Stripe wiring is applied from Admin -> Stripe after the user saves Stripe credentials and chooses the exact app checkout target to bind.\n- Do not assume `/api/create-checkout-session` already exists in a fresh template. Do not create a live Stripe route during first-pass generation unless the user explicitly asks to wire live Stripe now.\n- If the user explicitly asks to wire live Stripe in code, create a server-side route such as `/api/stripe/create-checkout-session` in `js/app-runtime.js` and call it from the selected checkout action only.\n- When an explicitly live Stripe checkout button is clicked, call the endpoint like this:\n ```typescript\n const response = await fetch('/api/stripe/create-checkout-session', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n items: [{ name: 'Pro plan', price: 29, currency: 'usd', quantity: 1 }],\n successUrl: window.location.origin + '/success',\n cancelUrl: window.location.origin + '/cancel',\n }),\n });\n if (!response.ok) throw new Error('Checkout failed');\n const { url } = await response.json();\n window.location.href = url; // Redirect to Stripe hosted checkout\n ```\n- **Do NOT collect credit card numbers in the React app**. Let Stripe host the payment form for explicit Stripe Checkout.\n- **Do NOT mark payment as successful** until the user returns from Stripe's success URL.\n- **Check `response.ok`** before parsing JSON. Show server error messages when checkout fails.\n- Do not mention Stripe setup or Admin -> Stripe in user-facing generated UI unless the user explicitly asked for Stripe.\n- For integration-backed features, keep the browser talking to your own server route. The route may call the external provider with a server-side secret, but the browser must never call the provider directly with a secret.\n- If a required secret is missing, explain the secure setup path in polished prose before coding: mention the server-side route, the missing secret name, where to add it, and what you will build once it is configured. Never tell the user to enter the provider key into component state or a client-side prompt.\n- If the app needs user accounts, signup, login, or protected content, use the built-in auth system already present in the template.\n- Auth config lives in `app.c
1748onfig.json`. Keep it up to date with the app name/slug and enable the needed auth flags there.\n- Keep `auth.requireLogin` false by default for customer-facing apps so public routes remain accessible. Set `requireLogin: true` only when the user explicitly asks to lock the entire site.\n- If the app should stay publicly visible until the user clicks a CTA such as Start Play, Book Now, Checkout, or another protected action, keep the main experience reachable at `/` and send only that CTA to `/login` or `/signup`. Do not make `/login` the default landing route unless the user explicitly asked for a login-first app.\n- Never include `/login` or `/signup` in `auth.protectedPaths`; those routes must stay reachable.\n- The builder owns the real auth routes (`/login`, `/signup`, `/account`, `/logout`, and `/auth/complete`), the D1 auth integration, and the runtime/session logic.\n- Qwen must generate only the GUI/presentation for auth screens.\n- Preferred implementation: either update `src/components/auth/AuthScreens.tsx` directly while preserving `LoginScreen`, `SignupScreen`, and `AccountScreen`, or keep `AuthScreens.tsx` as the stable mount point and move visual pieces into presentation-only subcomponents it imports.\n- Treat `src/components/auth/AuthScreens.tsx` and any generated auth UI helpers as presentation-only. Do not add `useAuth()`, `RequireAuth`, `login()`, `signup()`, `logout()`, direct `/api/auth/*` calls, password hashing, cookie logic, tokens, session storage, auth API handlers, Google OAuth logic, or custom auth backend flows in app-owned generated files.\n- Do not create parallel auth route files or route-level auth logic. The builder provisions and owns the auth routes and mounts the generated UI there when Admin -> Authentication is enabled.\n- If a generated header/nav needs auth controls, import and render the builder-owned `AuthNav` from `src/lib/appAuth.tsx` and style its wrapper/classes. Do not hardcode static Sign in / Sign up links when auth is enabled.\n- If auth is requested before Admin -> Authentication is enabled, keep the main app public and generate only themed auth presentation. Show clear setup-needed or locked-action UI instead of broken auth requests, fake sessions, or global redirects.\n- When auth behavior changes, update the route shell together: `src/App.tsx`, redirects, wildcard/fallback routes, CTA links/buttons, and logout destinations. Do not only edit the leaf page or widget that mentioned auth.\n- If logout should return the user to the public app, send them back to that public route instead of forcing `/login` unless the user explicitly asked for a logged-out login landing page.\n- When the user asks for login or signup, do not replace that with hardcoded demo credentials, fake auth success flows, or mock local-only auth state.\n- Passwords, sessions, cookies, tokens, and OAuth flows remain builder-owned/server-side concerns. Managed Google login starts through `/api/auth/google/start`, returns through `/auth/complete`, and exchanges through `/api/auth/cloudmysite/exchange`; do not implement those flows in generated app-owned frontend files.\n---":""} 1749${i==="Vite React"?'\nVITE REACT STRUCTURE RULES:\n- Treat the imported template structure as the source of truth.\n- If the template includes `src/main.tsx`, `src/App.tsx`, and `src/lib/appAuth.tsx`, continue from those files instead of replacing the app with parallel `.jsx` entry files or a separate auth architecture.\n- Do not create parallel auth files such as `src/contexts/AuthContext.*` or `src/services/auth.*` unless the user explicitly asks for a custom architecture and it still uses the built-in auth endpoints.\n- `react-router-dom` is already available in the template.\n- The root router is already mounted in `src/main.tsx`. Define routes in `src/App.tsx` and child components instead of adding another top-level `<BrowserRouter>`.\n- If you use `Link`, `Routes`, `Route`, or `Navigate`, keep the router-based approach intact. Do not remove routing just to silence a compile/runtime error; instead fix the dependency wiring or router context correctly.\n- If you create or keep a route/page file, do not leave placeholder copy such as "content will be displayed here" or "coming soon". Build the real page or remove the route/link.\n- Never leave mounted
1749internal navigation items on `href="#"` or `to="#"`. Every visible header/sidebar/footer nav item must point to a real route or be removed.\n- When fixing missing npm packages, reuse versions already present in the starter template or current `package.json` when available. Do not invent unpublished semver ranges. For flat ESLint config imports, use `typescript-eslint`, `@eslint/js`, and `globals` unless the code explicitly imports a different package.\n---':""} 1750 1751${A} 1752`,{assistantMessage:M,userMessage:B,metadata:l,starterFiles:O,runtimeFiles:T,protectedFiles:Array.from(new Set([...m.ignoreFile.map(X=>X.path),...i==="Vite React"?["src/main.tsx"]:[]]))}}const RA=oh(!1);function ZQ(t,e){return e?.aborted?Promise.reject(e.reason??new DOMException("The operation was aborted.","AbortError")):new Promise((r,n)=>{const s=setTimeout(r,t);e?.addEventListener("abort",()=>{clearTimeout(s),n(e.reason??new DOMException("The operation was aborted.","AbortError"))},{once:!0})})}async function eZ(t){try{return await t.clone().json()}catch{return{}}}async function tZ(t,e,r,n={}){const s=n.delaysMs??[1e3,2500],i=n.sleep??ZQ;for(let a=0;;a++)try{const o=await t(e,r);if(!(o.status>=500&&o.status<=599)||a>=s.length||r?.signal?.aborted)return o;const c=await eZ(o);if(c.isRetryable===!1)return o;const u=s[a];n.onRetry?.({attempt:a+1,delayMs:u,status:o.status,message:c.message||o.statusText||"Transient chat server error"}),await i(u,r?.signal)}catch(o){if(a>=s.length||r?.signal?.aborted)throw o;const l=s[a];n.onRetry?.({attempt:a+1,delayMs:l,message:o instanceof Error?o.message:String(o)}),await i(l,r?.signal)}}async function IA(t){const e=new URLSearchParams,r=String(t?.product_type||"genie ai");e.set("product_type",r);const n=gO(r)?"/api/runtime/entitlements":"/api/runtime/billing-records",s=await Fl(`${n}?${e.toString()}`,{method:"GET"}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(i.error||"Failed to load billing records.");return Array.isArray(i.items)?i.items:i.subscription?[i.subscription]:[]}const Qd={explicitGameIntent:[/\bgame\b/i,/\bgameplay\b/i,/\bracing\b/i,/\bshooter\b/i,/\bminecraft\b/i,/\bvoxel\b/i,/\bsandbox\b/i,/\bplatformer\b/i,/\bfirst[-\s]?person\b/i,/\bfps\b/i,/\bopen[-\s]?world\b/i,/\bplayer\b/i,/\blevel\b/i,/\benemy\b/i,/\bquest\b/i],gameLike:[/\bgame\b/i,/\bracing\b/i,/\bshooter\b/i,/\bminecraft\b/i,/\bvoxel\b/i,/\bsandbox\b/i,/\bsimulation\b/i,/\bphysics\b/i,/\bwebgl\b/i],siteLike:[/\bwebsite\b/i,/\bsite\b/i,/\blanding\s+page\b/i,/\bpage\b/i,/\bsection\b/i,/\bhero\b/i,/\bscroll(?:-based)?\b/i,/\bresponsive\b/i,/\bmobile(?:-first|-optimized)?\b/i,/\btypography\b/i,/\btrailer\b/i,/\bprofile\b/i,/\bshowcase\b/i,/\bstorytelling\b/i,/\bparallax\b/i,/\bsocial\s+(?:media|sharing)\b/i],twoD:[/\b2[-\s]?d\b/i,/\btwo[-\s]?dimensional\b/i,/\bside[-\s]?scroll/i,/\btop[-\s]?down\b/i],threeD:[/\b3d\b/i,/\bwebgl\b/i,/\bthree(?:[\s.]?js)?\b/i,/\bbabylon(?:[\s.]?js)?\b/i,/\bvoxel\b/i,/\bminecraft\b/i,/\bphysics simulation\b/i,/\bsimulation\b/i,/\bopen[-\s]?world\b/i,/\bfirst[-\s]?person\b/i,/\bfps\b/i]};function Zd(t,e){return e.some(r=>r.test(t))}function rZ(t){return t.replace(/<!--\s*system:[\s\S]*?<!--\s*\/system:[\s\S]*?-->/gi," ")}function NA(t){return Zd(t,Qd.explicitGameIntent)}function nZ(t){return Zd(t,Qd.siteLike)}function sZ(t){return/\bminecraft\b/i.test(t)||/\bvoxel\b/i.test(t)?"minecraft":/\bracing\b/i.test(t)?"racing":/\bshooter\b/i.test(t)||/\bfps\b/i.test(t)?"shooter":/\bphysics\b/i.test(t)?"physics":/\bsimulation\b/i.test(t)?"simulation":"generic"}function iZ(t,e){return Zd(t,Qd.threeD)?"3d":Zd(t,Qd.twoD)?"2d":e==="racing"||e==="shooter"||e==="minecraft"||e==="physics"||e==="simulation"?"3d":null}function oZ(t){return/\bphaser(?:\s*3|\.?js)?\b/i.test(t)}function VN(t){return/\b(single html|single html file|single-file html|single file html|one html file|one single html|self contained html|self-contained html)\b/i.test(t)}function aZ(t){return VN(t)||/\b(html5 canvas|canvas and javascript|canvas and js|javascript and canvas|js and canvas|vanilla javascript|vanilla js|plain javascript|plain js|plain html css js|plain html css and javascript|plain html css and js)\b/i.test(t)}function lZ(t){return/\b(tic[-\s]?tac[-\s]?toe|noughts\s+and\s+crosses|connect\s+four|sudoku|wordle|memory\s+card|matching\s+card|card\s+game|board\s+game|quiz|trivia)\b/i.test(t)||/\busing\s+only\s+
1752html\b/i.test(t)&&/\bcss\b/i.test(t)&&/\bvanilla\s+javascript\b/i.test(t)&&!/\bcanvas\b/i.test(t)}function cZ(t,e){return oZ(t)?"phaser":e==="3d"?"react-3d":lZ(t)?"plain-dom":"plain-canvas"}function uZ(t,e){const r=t==="2d"?"2D":"3D";switch(e){case"racing":return`${r} racing game.`;case"shooter":return`${r} shooter game.`;case"minecraft":return`${r} voxel sandbox game (Minecraft-style).`;case"physics":return`${r} physics simulation experience.`;case"simulation":return`${r} simulation game.`;default:return t==="2d"?"2D game.":t==="3d"?"3D game.":"Browser game."}}function dZ(t,e){return e==="phaser"?["phaser (only because the user explicitly requested Phaser)"]:e==="react-3d"||t==="3d"?["Vite React browser runtime","Three.js or Babylon.js only if requested or clearly needed for real 3D rendering"]:e==="plain-dom"?["HTML, CSS, and vanilla JavaScript","DOM events and CSS grid/layout","no external libraries"]:t==="2d"?["HTML5 Canvas API","vanilla JavaScript","no game framework by default"]:["Vanilla Vite or static HTML","browser APIs","no npm dependencies unless required"]}function hZ(t,e,r){return r&&e!=="phaser"?["index.html"," inline <style> for layout and game UI",` inline <script> for ${e==="plain-dom"?"game state, rules, input handlers, UI updates, scoring, and restart logic":"Canvas setup, game loop, controls, state, and restart logic"}`]:e==="phaser"?["src/"," main.ts"," game/"," scenes/MainScene.ts"," entities/Player.ts"," systems/controls.ts"," systems/state.ts"]:e==="plain-dom"?["index.html","src/main.js (game state, rules, input handlers, and UI updates)","src/style.css (responsive layout and visual states)"]:t==="2d"?["index.html","src/main.js (only if the template entry flow requires it)","src/game.js (optional, if not single-file)"]:["index.html","src/"," main.js"," game/scene.js"," game/controls.js"," game/state.js"]}function fZ(t){switch(t){case"racing":return["Player objective: complete laps as fast as possible while avoiding track obstacles.","Track progression: checkpoints and lap counter with best-time tracking.","Failure/penalty: collisions reduce speed and increase completion time."];case"shooter":return["Player objective: survive enemy waves and maximize score.","Combat loop: aim, shoot, reload, and avoid incoming damage.","Failure condition: health reaches zero; progression through increasing wave difficulty."];case"minecraft":return["Player objective: explore a voxel world and build structures by placing/removing blocks.","Core loop: movement, terrain interaction, and basic resource-driven building.","Progression: expanding builds and exploring additional world regions."];case"physics":return["Player objective: interact with objects and observe physics behavior in real time.","Core loop: spawn/manipulate objects, apply forces, and track collisions.","Reset/progression: scene reset and configurable simulation parameters."];case"simulation":return["Player objective: run and interact with a simulation scenario.","Core loop: adjust parameters, observe outcomes, and iterate.","Progression: scenario complexity and measurable performance metrics."];default:return["Player objective: complete level goals and improve score/performance.","Core loop: movement, interaction, and objective completion.","Progression: increasing challenge with clear success/failure states."]}}function pZ(t,e,r){if(r==="plain-dom")return["Mouse/touch click activates controls and board cells.","Keyboard focus, Enter, and Space activate playable cells/buttons.","Disable or ignore already-filled cells after selection."];switch(t){case"racing":return["W/ArrowUp accelerate","S/ArrowDown brake-reverse","A,D / ArrowLeft,ArrowRight steer","R reset vehicle"];case"shooter":return["W,A,S,D move","Mouse move aim camera/crosshair","Left click shoot","R reload","Space jump"];case"minecraft":return["W,A,S,D move","Mouse move look","Space jump","Left click remove block","Right click place block"];case"physics":return["Mouse drag manipulate objects","Scroll zoom camera","W,A,S,D orbit/pan camera","R reset simulation"];default:return e==="2d"?["Arrow keys / WASD move","Space primary action/jump","R reset"]:["W,A,S,D move","Mouse look/aim","Space jump or primary action","R reset"]}}
1752function mZ(t,e){return e==="phaser"?["Use the Phaser Vite template and mount a Phaser.Game instance from the template entry.","Implement MainScene with preload/create/update lifecycle for the game loop.","Keep Phaser state modular and route updates through scene systems."]:e==="plain-dom"?["Use semantic HTML buttons/elements for board cells and controls.","Use CSS for layout, responsive sizing, disabled states, and visual feedback.","Keep turn state, scoring, win/draw detection, restart behavior, and keyboard actions in vanilla JavaScript."]:t==="2d"?["Use a <canvas> element and CanvasRenderingContext2D for all gameplay rendering.","Drive the game loop with requestAnimationFrame and delta time.","Keep input, collision, scoring, win/loss, and restart state in vanilla JavaScript."]:["Use a Vite React entry for app structure and browser WebGL rendering for the scene when needed.","Add Three.js or Babylon.js only when requested or clearly needed for 3D rendering.","Keep HUD/menu overlays as normal HTML outside the WebGL canvas."]}function gZ(t,e,r){const n=["Do not assume React. Use React only if the user explicitly requested React or the app clearly needs React UI/state management.","Do not use Phaser unless the user explicitly requested Phaser by name.","Replace starter template content with the requested runnable implementation; avoid unrelated boilerplate.","Do not add npm dependencies unless the requested mechanics or rendering stack require them."];return r&&e!=="phaser"?[...n,"Generate only index.html with inline CSS and JavaScript unless the selected platform requires main.js or src/main.js.","Keep all game logic, controls, scoring, collision, screens, and restart behavior in that single HTML file."]:e==="phaser"?[...n,"Use the dedicated Phaser Vite template and keep phaser declared in package.json.","Do not mix Phaser with a React host unless the user explicitly requested React.","Treat Phaser.GameObjects.Graphics as a Phaser drawing object, not a CanvasRenderingContext2D; do not call canvas-only methods such as bezierCurveTo on it.","KeyboardPlugin.addKeys returns an object keyed by the supplied names; never cast it to Key[] or read numeric indexes. Use a named key-code mapping and keys.W / keys.A / keys.SPACE access."]:t==="3d"||e==="react-3d"?[...n.filter(i=>!i.startsWith("Do not assume React.")),"Use the Vite React template for the browser shell.","If Three.js or Babylon.js is used, add the dependency to package.json first and run the install command once."]:e==="plain-dom"?[...n,"Use plain HTML, CSS, and vanilla JavaScript DOM updates; do not convert board/UI games into Canvas unless the user asks for Canvas."]:t==="2d"?[...n,"Use plain HTML5 Canvas and vanilla JavaScript for the 2D game loop."]:["Use the existing template dependencies unless gameplay requires additional libraries.",...n]}function bZ(t,e){const r=["Emit real file updates for the runnable game implementation in this same response; do not stop after describing the plan.","If dependency installation is needed, also emit the game entry/scene/module file updates in the same response.","Replace the starter entry with the actual game bootstrap and create every newly referenced local module immediately.","Do not leave the workspace on the starter placeholder after this response."];return e==="phaser"?[...r,"For Phaser games, use Phaser scene/modules from the Phaser Vite template and keep package.json dependency wiring intact.","Keep controls null-safe and use named Phaser key mappings so every key read in update() exists at runtime."]:t==="3d"?[...r,"For 3D games, wire the scene through the Vite React app and create the referenced scene/entity/system modules in the same response."]:e==="plain-dom"?[...r,"For DOM board/UI games, implement the visible interface, game rules, accessibility states, scoring, and restart flow in the same response."]:t==="2d"?[...r,"For 2D Canvas games, wire the canvas, controls, game loop, collision, scoring, and restart flow in the same response."]:r}function vZ(t){const e=rZ(String(t||"")).trim();if(!e||nZ(e)&&!NA(e)||!Zd(e,Qd.gameLike))return null;const r=sZ(e),n=iZ(e,r),s=cZ(e,n),i=VN(e),a=aZ(e),o=/\b(browser|web|html5|canvas|javascript|js)\b/i.test(e)&&NA(e);if(s!=="phaser"&&n!=="2d"&&!a||!n&&r==="generic"&&s!=="phaser"&&!o)return null;const l=dZ(n,s).map(p=>`- ${p}`).join(` 1753`),c=hZ(n,s,i).map(p=>`- ${p}`).join(` 1754`),u=fZ(r).map(p=>`- ${p}`).join(` 1755`),d=pZ(r,n,s).map(p=>`- ${p}`).join(` 1756`),h=mZ(n,s).map(p=>`- ${p}`).join(` 1757`),m=gZ(n,s,i).map(p=>`- ${p}`).join(` 1758`),b=bZ(n,s).map(p=>`- ${p}`).join(` 1759`);return["Original User Request:",e,"","Project Type:",s==="phaser"?"Browser-based game using the dedicated Phaser Vite template.":s==="react-3d"?"Browser-based 3D game using the Vite React template, with Three.js/Babylon.js only if requested or clearly needed.":s==="plain-dom"?"Browser-based game using plain HTML, CSS, and vanilla JavaScript DOM interactions.":"Browser-based game using plain HTML5 Canvas and vanilla JavaScript.","","Game Type:",uZ(n,r),"","Libraries:",l,"","Project Structure:",c,"","Gameplay Mechanics:",u,"","Controls:",d,"","Rendering Setup:",h,"","Execution Requirements:",b,"","Implementation Notes:",m].join(` 1760`)}const yZ=/\.(?:[cm]?[jt]sx?)$/i,_Z=/\.(?:[cm]?[jt]sx?)$/i,Zf=/^\.\.?(?:\/|$)/,xZ=/(?:^|\n)\s*(import|export)\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g,wZ=/(?:^|\n)\s*import\s+['"]([^'"]+)['"]/g,SZ=/\bimport\s*\(\s*['"]([^'"]+)['"]\s
1760*\)/g,LA=[".tsx",".ts",".jsx",".js",".mjs",".cjs",".css",".scss",".sass",".less",".json",".svg",".png",".jpg",".jpeg",".gif",".webp",".avif",".ico"],GN=t=>t.replace(/\\/g,"/").replace(/^\/home\/project\//,"").replace(/^home\/project\//,"").replace(/^\.\//,"").replace(/^\/+/,""),eu=t=>String(t||"").trim().split(/[?#]/)[0]||"",CZ=t=>{const e=GN(t),r=e.lastIndexOf("/");return r===-1?"":e.slice(0,r)},AZ=(t,e)=>{const r=CZ(t).split("/").filter(Boolean),n=eu(e).split("/");for(const s of n)if(!(!s||s===".")){if(s===".."){r.pop();continue}r.push(s)}return r.join("/")},EZ=(t,e)=>{const r=eu(e);if(!Zf.test(r))return[];const n=AZ(t,r);return/\.[A-Za-z0-9]+$/.test(r)?[n]:[...LA.map(i=>`${n}${i}`),...LA.map(i=>`${n}/index${i}`)]};function kZ(t,e){const r=[eu(t),...e].join(" ").toLowerCase();return/\/pages?\//.test(r)||/\/page\.[a-z0-9]+$/.test(r)?"page":/\/routes?\//.test(r)||/route\.[a-z0-9]+$/.test(r)?"route":/\/components?\//.test(r)?"component":/\/hooks?\//.test(r)||/\/use[A-Z]/.test(r)?"hook":/\/(?:utils?|lib)\//.test(r)?"util":/\.(?:css|scss|sass|less)$/.test(r)||/\/styles?\//.test(r)?"style":/\.(?:svg|png|jpe?g|gif|webp|avif|ico)$/.test(r)||/\/assets?\//.test(r)?"asset":"module"}function PZ(t){return t.split(",").map(e=>e.replace(/\btype\s+/g,"").trim()).filter(Boolean).map(e=>{const r=e.match(/^([A-Za-z_$][\w$]*|default)\s+as\s+([A-Za-z_$][\w$]*)$/);return r?{importedName:r[1],localName:r[2],kind:"named"}:{importedName:e,localName:e,kind:"named"}})}function TZ(t,e){let r=String(t||"").replace(/\s+/g," ").trim();if(!r)return[];const n=[],s=r.match(/\{([^}]*)\}/);s&&(n.push(...PZ(s[1]||"")),r=r.replace(s[0],"").trim());const i=r.match(/\*\s+as\s+([A-Za-z_$][\w$]*)/);if(e==="import"&&i&&(n.push({importedName:"*",localName:i[1],kind:"namespace"}),r=r.replace(i[0],"").trim()),r=r.replace(/^type(?:\s+|$)/,"").replace(/,/g," ").trim(),e==="import"){const a=r.match(/^([A-Za-z_$][\w$]*)$/);a&&n.unshift({importedName:"default",localName:a[1],kind:"default"})}return n}function RZ(t){const e=t.split("");let r="code",n=!1;const s=i=>{e[i]!==` 1761`&&e[i]!=="\r"&&(e[i]=" ")};for(let i=0;i<t.length;i+=1){const a=t[i],o=t[i+1]||"";if(r==="line-comment"){a===` 1762`||a==="\r"?r="code":s(i);continue}if(r==="block-comment"){s(i),a==="*"&&o==="/"&&(s(i+1),i+=1,r="code");continue}if(r==="template"){if(s(i),n){n=!1;continue}if(a==="\\"){n=!0;continue}a==="`"&&(r="code");continue}if(r==="single-quote"||r==="double-quote"){if(n){n=!1;continue}if(a==="\\"){n=!0;continue}(r==="single-quote"&&a==="'"||r==="double-quote"&&a==='"')&&(r="code");continue}if(a==="/"&&o==="/"){s(i),s(i+1),i+=1,r="line-comment";continue}if(a==="/"&&o==="*"){s(i),s(i+1),i+=1,r="block-comment";continue}if(a==="`"){s(i),r="template",n=!1;continue}if(a==="'"){r="single-quote",n=!1;continue}a==='"'&&(r="double-quote",n=!1)}return e.join("")}function IZ(t){const e=[],r=RZ(t),n=new RegExp(xZ.source,"g");let s;for(;(s=n.exec(r))!==null;){const c=s[1]==="export"?"export":"import",u=String(s[3]||"").trim();Zf.test(eu(u))&&e.push({importSource:u,importedBindings:TZ(String(s[2]||""),c),isDynamic:!1})}const i=new RegExp(wZ.source,"g");let a;for(;(a=i.exec(r))!==null;){const c=String(a[1]||"").trim();Zf.test(eu(c))&&e.push({importSource:c,importedBindings:[],isDynamic:!1})}const o=new RegExp(SZ.source,"g");let l;for(;(l=o.exec(r))!==null;){const c=String(l[1]||"").trim();Zf.test(eu(c))&&e.push({importSource:c,importedBindings:[],isDynamic:!0})}return e}function NZ(t){const e=new Set;for(const r of t.matchAll(/\bexport\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s+(?:const|let|var|class|interface|type|enum)\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s*\{\s*([^}]+)\s*\}/g)){const n=String(r[1]||"").split(",").map(s=>s.trim()).filter(Boolean);for(const s of n){const i=s.match(/^([A-Za-z_$][\w$]*|default)\s+as\s+([A-Za-z_$][\w$]*|default)$/);if(i){if(i[2]==="default")continue;e.add(i[2]);continue}s!=="default"&&e.add(s)}}
1762return{hasDefaultExport:/\bexport\s+default\b/.test(t)||/\bexport\s*\{[^}]*\bdefault\b[^}]*\}/.test(t),namedExports:e,hasWildcardReExport:/\bexport\s+\*\s+from\b/.test(t)}}function LZ(t,e){if(t.length===0)return[];const r=new Set;for(const n of t)if(n.kind!=="namespace"){if(n.importedName==="default"){e.hasDefaultExport||r.add("default");continue}e.hasWildcardReExport||e.namedExports.has(n.importedName)||r.add(n.importedName)}return[...r]}function DZ(t,e,r){for(const n of t)if(e.has(n))return{resolvedPath:n,caseMismatchPath:null};for(const n of t){const s=r.get(n.toLowerCase());if(s)return{resolvedPath:s,caseMismatchPath:s}}return{resolvedPath:null,caseMismatchPath:null}}function MZ(t,e){return e||t==="route"?"orphaned-route-import":t==="page"||t==="component"?"missing-page-component":"missing-local-file"}function zy(t,e){const r=e?.includeWarnings??!1,n=e?.limit??50,s=new Set,i=new Map,a=new Map;for(const[b,g]of Object.entries(t)){if(!g||g.type!=="file")continue;const p=GN(b);s.add(p),i.set(p.toLowerCase(),p),typeof g.content=="string"&&a.set(p,g.content)}const o=[...a.keys()].filter(b=>yZ.test(b)).sort((b,g)=>b.localeCompare(g)),l=[],c=[];let u=0;for(const b of o){const g=a.get(b)||"",p=IZ(g);for(const y of p){u+=1;const v=EZ(b,y.importSource),_=kZ(y.importSource,v),w=DZ(v,s,i);if(!w.resolvedPath){c.push({importerFile:b,importSource:y.importSource,expectedPaths:v,importType:_,importedBindings:y.importedBindings,isDynamic:y.isDynamic}),l.push({code:MZ(_,y.isDynamic),sourceFile:b,importSource:y.importSource,resolvedPath:null,expectedPaths:v,message:`Local import '${y.importSource}' in '${b}' cannot be resolved to any existing file.`,severity:"error",importType:_,importedBindings:y.importedBindings,missingExportNames:[],isDynamic:y.isDynamic});continue}if(w.caseMismatchPath&&l.push({code:"import-path-mismatch",sourceFile:b,importSource:y.importSource,resolvedPath:w.caseMismatchPath,expectedPaths:v,message:`Import '${y.importSource}' in '${b}' resolves to '${w.caseMismatchPath}', but the import path casing does not match the actual file path exactly.`,severity:"error",importType:_,importedBindings:y.importedBindings,missingExportNames:[],isDynamic:y.isDynamic}),!_Z.test(w.resolvedPath))continue;const C=a.get(w.resolvedPath);if(typeof C!="string")continue;const A=LZ(y.importedBindings,NZ(C));A.length!==0&&(kD(w.resolvedPath)||l.push({code:"missing-export",sourceFile:b,importSource:y.importSource,resolvedPath:w.resolvedPath,expectedPaths:v,message:`Import '${y.importSource}' in '${b}' references export(s) that '${w.resolvedPath}' does not provide: ${A.join(", ")}.`,severity:"error",importType:_,importedBindings:y.importedBindings,missingExportNames:A,isDynamic:y.isDynamic}))}}const d=[],h=new Set;for(const b of l){const g=`${b.code}::${b.sourceFile}::${b.importSource}::${b.missingExportNames.join(",")}`;if(!h.has(g)&&(h.add(g),(b.severity==="error"||r)&&d.push(b),d.length>=n))break}const m=c.slice(0,n);return{scannedFileCount:o.length,localImportCount:u,issueCount:d.length,missingDependencyCount:m.length,missingDependencies:m,issues:d,signature:m.map(b=>`${b.importerFile}:${b.importSource}:${b.importType}`).join("||").slice(0,1200)}}function OZ(t,e){if(t.length===0)return"";const r=t.filter(i=>i.code!=="missing-export"),n=t.filter(i=>i.code==="missing-export");let s=`**Import Dependency Graph Issues (${t.length} blocking)** 1763 1764`;if((e?.missingDependencies.length||r.length)>0){s+=`### Missing or Mismatched Local Dependencies: 1765`;const i=e?.missingDependencies.length?e.missingDependencies.slice(0,12).map(a=>{const o=a.importedBindings.length>0?a.importedBindings.map(l=>l.importedName).join(", "):"side-effect/dynamic import";return[`- importer: ${a.importerFile}`,` source: ${a.importSource}`,` type: ${a.importType}`,` expected: ${a.expectedPaths.slice(0,4).join(", ")}`,` bindings: ${o}`].join(` 1766`)}).join(` 1767`):r.slice(0,12).map(a=>{const o=a.importedBindings.length>0?a.importedBindings.map(l=>l.importedName).join(", "):"side-effect/dynamic import";return[`- importer: ${a.sourceFile}`,` source: ${a.importSource}`,` type: ${a.importType}`,` expected: ${a.expectedPaths.slice(0,4).join(", ")}`,` bindings: ${o}`].join(` 1768`)}).join(` 1769`);s+=`${i} 1770 1771`}if(n.length>0){s+=`### Missing Exports: 1772`;for(const i of n.slice(0,8))s+=`- importer: ${i.sourceFile} 1773`,s+=` source: ${i.importSource} 1774`,s+=` resolved: ${i.resolvedPath||"(missing)"} 1775`,s+=` missing exports: ${i.missingExportNames.join(", ")} 1776`;s+=` 1777`}
1777return s+=["Repair requirements:","- Do not leave unresolved imports.","- For every import in emitted code, either create the target file in this repair cycle or remove the import.","- Do not reference pages/components/hooks/utils/assets/routes that are not included in the response.","- Return a self-contained, buildable project delta."].join(` 1778`),s}const jZ=/(?:^|\/)eslint\.config\.[cm]?[jt]s$/i,$Z=/\beslint\b/,BZ=new Set(["protected-runtime-export-contract"]),Ht=/\.(?:[cm]?[jt]sx?)$/i,qN=/(?:^|\/)app\.config\.json$/i,FZ=/(?:import|export)\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,WZ=/https?:\/\/[^"'`\s)]+\/api\/assets\/([A-Za-z0-9_-]+)\/content(?:\?[^"'`\s)]*)?/g,HZ=/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,UZ=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,KN=/(?:import|export)\s+(?:[^'"]*?\s+from\s+)?['"](\.[^'"]+)['"]/g,YN=/\bimport\s*\(\s*['"](\.[^'"]+)['"]\s*\)/g,zZ=/from\s+['"]@react-three\/cannon['"]/,VZ=/<Physics\b/,GZ=/\buse(?:Box|CompoundBody|ConeTwistConstraint|ConvexPolyhedron|Cylinder|DistanceConstraint|Heightfield|HingeConstraint|LockConstraint|Plane|PointToPointConstraint|RaycastVehicle|Sphere|Spring|Trimesh)\b|<(?:Debug|RaycastVehicle)\b/,XN=/from\s+['"](?:three|@react-three\/(?:fiber|drei|cannon))['"]|<Canvas\b|<mesh\b|<group\b|\buseFrame\s*\(|\buseThree\s*\(|\bTHREE\./,qZ=/<textGeometry\b/,KZ=/\bextend\s*\(\s*\{[\s\S]{0,400}\bTextGeometry\b[\s\S]{0,400}\}\s*\)/,JN=/<Route\b[^>]*\bpath\s*=\s*["'`]([^"'`]+)["'`]/g,YZ=/\b(?:href|to)\s*=\s*["'`]#["'`]/g,XZ=/<(?:a|Link|NavLink)\b[^>]*\b(?:href|to)\s*=\s*["'`]#["'`][^>]*>\s*([^<]{1,80}?)\s*<\/(?:a|Link|NavLink)>/g,JZ=/\blabel\s*:\s*["'`]([^"'`]+)["'`][\s\S]{0,140}?\b(?:href|to)\s*:\s*["'`]#["'`]/g,T0=/import\s+(?!type\b)([A-Za-z_$][\w$]*)\s*(?:,\s*(?:type\s+)?\{[^}]*\})?\s*from\s*['"]([^'"]+)['"]/g,Um=/import\s+(?!type\b)(?:[A-Za-z_$][\w$]*\s*,\s*)?(?:type\s+)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g,QZ=/import\s+(?!type\b)\*\s+as\s+([A-Za-z_$][\w$]*)\s*from\s*['"]([^'"]+)['"]/g,ZZ=/(?:import|export)\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"]([^'"]*appSchema(?:\.[cm]?[jt]sx?)?)['"]/g,eee=/import\s+(?!type\b)([A-Za-z_$][\w$]*)\s*(?:,\s*(?:type\s+)?\{[^}]*\})?\s*from\s*['"]([^'"]*appSchema(?:\.[cm]?[jt]sx?)?)['"]/g,tee=[/\b(?:to|href)\s*=\s*["'`](\/[^"'`]+)["'`]/g,/\bnavigate\s*\(\s*["'`](\/[^"'`]+)["'`]/g,/\bwindow\.location\.(?:assign|replace)\(\s*["'`](\/[^"'`]+)["'`]/g],ree=["BrowserRouter","HashRouter","MemoryRouter","RouterProvider","Router"],nee=/<(BrowserRouter|HashRouter|MemoryRouter|RouterProvider|Router)\b/g,see=/from\s+['"]react-router-dom['"]/,QN=/(?:^|\/)vite\.config\.(?:[cm]?[jt]s)$/i,iee=/\bfetch\s*\(\s*["'`]([^"'`]+)["'`]/g,ZN=["/api/auth/me","/api/auth/account","/api/auth/login","/api/auth/signup","/api/auth/logout"],oee=["/api/auth/google/start","/api/auth/google/callback","/api/auth/cloudmysite/exchange","/auth/complete"],eL=["/api/db/tables","/api/db/select","/api/db/insert","/api/db/update","/api/db/delete","/api/db/ensure-schema"],aee=["/api/integrations/secrets/status","/api/admin/auth/init"],lee="to accept payments, connect your stripe account.",cee=/connect stripe|add stripe api keys manually|admin\s*(?:->|â|ââ â)\s*integrations/i,uee=/fetchAppSecretStatus|getBuiltInAppIntegration\(\s*['"`]stripe['"`]\s*\)|\/api\/integrations\/secrets\/status|getAppSecretMissingMessage|PROJECT_SECRET_MISSING_MESSAGE/,tL=/['"`](\/api\/[^'"`]+)['"`]/g,rL=/(?:stripe|checkout|payment|billing|deposit|subscription)/i,zm=/(?:stripe|checkout|payment|billing|deposit|subscription|cart|order)/i,dee=/\breadLocalSecretBindings\s*\(/,hee=/(?:\bprocess\.env\b|\bimport\.meta\.env\b|\benv\b)\s*(?:\.\s*STRIPE_(?:SECRET_KEY|WEBHOOK_SECRET)\b|\[\s*['"`]STRIPE_(?:SECRET_KEY|WEBHOOK_SECRET)['"`]\s*\])/,fee=/(?:window\.)?alert\s*\(\s*(['"`])([\s\S]{1,240}?)\1\s*\)/g,pee=["/api/stripe/create-checkout-session","/api/create-checkout-session"],mee=/\b(?:session|data|payload|result)\.url\b|\b(?:sessionUrl|checkoutUrl)\b/,gee=/(?:window\.)?location(?:\.href\s*=|\.assign\s*\(|\.replace\s*\()/,bee=/\b(?:cardNumber|cardName|expiry(?:Date)?|expiration|cvv|cvc)\b|Card Information|Card Number|MM\/YY/i,vee=/\bset[A-Za-z_$][\w$]*Success\s*\(\s*true\s*\)|\bsetOrderStatus\s*\(\s*['"`]success['"`]\s*\)|\bpaymentSuccess\b|Payment Successful!?/,yee=/\bsuccessUrl\b|\bsuccess_url\b/,_ee=/\bcancelUrl\b|\bcancel_url\b/,xee=/[^\x00-\x7F]/,nL=["js/app-runtime.js","js/worker.js","vite.local-db.ts"],R0=new Set([...ZN,...oee,...eL,...aee]),wee=new Set(["vite.local-db.ts","src/lib/appAuth.tsx","src/lib/appData.ts","src/lib/cloudflareCrud.ts"]),See=new Set(["AppEntityFieldType","AppEntityRelationAction","AppEntityFieldReferenceInput","AppEntityFieldInputObject","AppEntityFieldInput","AppEntityIndexInput","AppEntityInput","DefineAppSchemaInput","AppEntityFieldReference","AppEntityFieldSchema","AppEntityIndexSchema","AppEntitySchema","AppDatabaseSchema","Worker
1778SchemaColumn","WorkerSchemaIndex","WorkerSchemaTable","WorkerAppSchemaPayload","normalizeAppSchemaToken","buildAppEntityTableName","defineAppSchema","getAppEntitySchema","getAppEntityTableName","serializeAppEntityRecord","materializeAppEntityRow","buildAppSchemaWorkerPayload"]),Cee=/^(?:export\s+default\s+|export\s+)?(const|let|var|function|class)\s+([A-Za-z_$][\w$]*)\b/gm,Aee=["Box2","Box3","Color","Euler","Matrix3","Matrix4","MathUtils","Plane","Quaternion","Raycaster","Sphere","Vector2","Vector3"],Eee=["Canvas","createPortal","extend","useFrame","useGraph","useLoader","useThree"],kee=new Set(["a","article","aside","button","canvas","div","fieldset","footer","form","h1","h2","h3","h4","h5","h6","header","img","input","label","li","main","nav","ol","p","section","select","span","strong","table","tbody","td","textarea","th","thead","tr","ul"]),Pee=/<([A-Z][A-Za-z0-9_$]*)\b/g,Tee=/<([a-z][A-Za-z0-9-]*)\b/g,Ree=/<Canvas\b[\s\S]*?<\/Canvas>/g,Iee=new Set(["vite.local-db.ts","js/worker.js","js/auth-worker.js","js/db-runtime.js","src/lib/appAuth.tsx","src/lib/cloudflareCrud.ts"]),Nee={"/api/check-auth":["/api/auth/me"],"/api/check-session":["/api/auth/me"],"/api/me":["/api/auth/me"],"/api/auth/check-auth":["/api/auth/me"],"/api/auth/check-session":["/api/auth/me"],"/api/login":["/api/auth/login"],"/api/signin":["/api/auth/login"],"/api/sign-in":["/api/auth/login"],"/api/signup":["/api/auth/signup"],"/api/sign-up":["/api/auth/signup"],"/api/register":["/api/auth/signup"],"/api/logout":["/api/auth/logout"],"/api/signout":["/api/auth/logout"],"/api/sign-out":["/api/auth/logout"]},sL=/(?:\bpath\b\s*=\s*["']\/(?:login|sign-?in)["']|\bto\b\s*=\s*["']\/(?:login|sign-?in)["']|['"`]\/(?:login|sign-?in)['"`])/i,iL=/(?:\bpath\b\s*=\s*["']\/(?:signup|sign-?up|register)["']|\bto\b\s*=\s*["']\/(?:signup|sign-?up|register)["']|['"`]\/(?:signup|sign-?up|register)['"`])/i,Lee=/(?:<Route\b[^>]*\bpath\s*=\s*["']\/(?:login|sign-?in)["']|\bpath\s*:\s*["']\/(?:login|sign-?in)["'])/i,Dee=/(?:<Route\b[^>]*\bpath\s*=\s*["']\/(?:signup|sign-?up|register)["']|\bpath\s*:\s*["']\/(?:signup|sign-?up|register)["'])/i,Mee=/<(?:Routes|RouterProvider)\b|\buseRoutes\s*\(|\bcreateBrowserRouter\s*\(|\bcreateRoutesFromElements\s*\(/,eh=/(?:^|\/)(?:login|signin|sign-in)(?:page)?\.[cm]?[jt]sx?$/i,hu=/(?:^|\/)(?:signup|sign-up|register)(?:page)?\.[cm]?[jt]sx?$/i,If=/\bdefineAppSchema\s*\(\s*{/g,Oee=/\bapp\s*:\s*['"`]([^'"`]+)['"`]/,jee=/from\s+['"]([^'"]*appAuth(?:\.[cm]?[jt]sx?)?)['"]/g,DA=/import\s+(?:type\s+)?(?:([^'";]+?)\s+from\s+)?['"]([^'"]*AuthScreens(?:\.[cm]?[jt]sx?)?)['"]/g,MA=["LoginScreen","SignupScreen","AccountScreen"],$ee=[/\b(login|signup)\s*\(\s*\{[\s\S]{0,220}?\bemail\s*:\s*["'`][^"'`]+["'`][\s\S]{0,220}?\bpassword\s*:\s*["'`][^"'`]+["'`][\s\S]{0,220}?\}\s*\)/g,/\b(login|signup)\s*\(\s*\{[\s\S]{0,220}?\bpassword\s*:\s*["'`][^"'`]+["'`][\s\S]{0,220}?\bemail\s*:\s*["'`][^"'`]+["'`][\s\S]{0,220}?\}\s*\)/g],OA=/\b(login|signup)\s*\(\s*["'`][^"'`\n]+["'`]\s*,\s*["'`][^"'`\n]+["'`]\s*\)/g,jA=/\bname\s*=\s*["'`]([A-Za-z_$][\w$-]*)["'`]/g,$A=/(?:^|[,{])\s*([A-Za-z_$][\w$]*)\s*(?::|(?=,|$))/gm,BA=/\bsignup\s*\(\s*\{/g,FA=new Set(["email","password","confirm_password","password_confirmation","terms","agree_terms","remember_me"]),WA=/\b(?:name|id)\s*=\s*["'`]([A-Za-z_$][\w$-]*)["'`]/g,Bee=/(?:^|\/)src\/(?:pages|components)\/[A-Za-z0-9_$-]*(?:address|profile|account|settings|onboarding|delivery|shipping|preference|preferences)[A-Za-z0-9_$-]*\.[cm]?[jt]sx?$/i,Fee=new Set(["address","street_address","city","state","province","zip","zip_code","postal_code","country","phone","phone_number","gender","company","contact_time","first_name","last_name","full_name","preferences"]),Wee=/\bonSubmit\s*=|\bhandleSubmit\b|\btype\s*=\s*["'`]submit["'`]/,Hee=/\buseAuth\s*\(|\bRequireAuth\b|<RequireAuth\b/,Uee=/\bsetTimeout\s*\(|\bnew\s+Promise\s*\([\s\S]{0,120}?\bsetTimeout\s*\(|in a real app|would (?:typically|normally) be saved|simulat(?:e|ing)|mock(?:ed)? save|replace (?:this|that) with (?:an )?(?:actual|real) (?:api|backend)|todo:?\s*(?:persist|save)\b/i,zee=/\b(?:saveUserProfile|readUserProfile|getUserProfile|loadUserProfile|persistUserProfile|updateUserProfile|saveProfile|updateProfile|persistProfile|ensureAppSchema|selectAp
1778pEntityRows|insertAppEntityRow|updateAppEntityRow|deleteAppEntityRow|ensureSchema|fetch)\s*\(|\/api\/(?:db|auth)\//,Vee=["content will be displayed here","coming soon","to be added soon"],HA="${quoteIdentifier(}`${table}_created_at_idx`)}",Gee="${quoteIdentifier(`${table}_created_at_idx`)}",th=/\b(?:menu|categor|catalog|product|service|location|destination|listing|inventory|collection|gallery|portfolio|team|staff|testimonial|review|faq|question|course|lesson|event|package|plan|property|ocean|article|story|news|headline|post|blog)\w*/i,qee=/\b(?:sync|seed|catalog|hydrate|initialize)[A-Za-z_$][\w$]*Promise\b|\b(?:existingBy|rowsBy|itemsBy|catalogBy|byKey|byName|seedKey)\b|\bdeleteAppEntityRow\s*\(|\bupdateAppEntityRow\s*\(/,oL=/\bselectAppEntityRows(?:<[^>]+>)?\s*\(|\bfetch\s*\(\s*["'`]\/api\/db\/select\?/,Kee=/const\s*\[\s*([A-Za-z_$][\w$]*)\s*,\s*([A-Za-z_$][\w$]*)\s*\]\s*=\s*useState(?:<[^>]+>)?\(\s*false\s*\)/g,Yee=/(?:^|\/)src\/(?:(?:data|seed|defaults?|mock|sample)s?\/|.*(?:seed|default|mock|sample)[\w-]*\.[cm]?[jt]sx?$)/i,Xee=/export\s+const\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*\[/g,I0=/(?:^|\/)\.cloudmysite\/local-db\.json$/i,Jee=new Set(["id","rowid","created_at","updated_at","createdAt","updatedAt"]),Qee=[{host:"images.unsplash.com",pattern:/https?:\/\/images\.unsplash\.com\/[^\s"'`)>]+/gi},{host:"source.unsplash.com",pattern:/https?:\/\/source\.unsplash\.com\/[^\s"'`)>]+/gi},{host:"unsplash.com",pattern:/https?:\/\/(?:www\.)?unsplash\.com\/[^\s"'`)>]+/gi}],UA=[".tsx",".ts",".jsx",".js",".mjs",".cjs",".css",".json",".svg"],aL=["src/main.tsx","src/main.jsx","src/main.ts","src/main.js","src/App.tsx","src/App.jsx","src/App.ts","src/App.js"],lL=["src/App.tsx","src/App.jsx","src/App.ts","src/App.js",...aL],Zee=new Set(["src/lib/appData.ts","src/lib/appSchema.ts","src/lib/cloudflareCrud.ts","src/lib/appSecrets.ts","js/auth-runtime.js","js/auth-worker.js","js/db-runtime.js","js/worker.js","vite.local-db.ts","src/main.tsx","src/main.jsx","src/main.ts","src/main.js"]),zA=["vite.local-db.ts","js/worker.js","js/auth-worker.js","js/app-runtime.js"],cL=/^(?:Header|Navbar|NavBar|Sidebar|TopNav|Navigation|SiteHeader|AppHeader)$/i,ete=/(?:from\s+['"]react-router-dom['"]|<nav\b|\b(?:to|href)\s*=\s*["'`](\/[^"'`]+)["'`])/i,tte=new Set(["assert","buffer","child_process","cluster","crypto","dgram","dns","events","fs","http","https","module","net","os","path","process","stream","timers","tls","tty","url","util","vm","zlib"]),xn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ce=t=>t.replace(/\\/g,"/").replace(/^\/home\/project\//,"").replace(/^home\/project\//,"").replace(/^\.\//,"").replace(/^\/+/,""),uL=t=>{const e=String(t||"").trim();if(!e)return"";if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||""}catch{return""}if(!e.startsWith("/api/"))return"";const[r]=e.split(/[?#]/,1);return r||""},dL=t=>String(t||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,""),rte=t=>{const e=String(t||"").trim();return!e||!e.startsWith("/")||e.startsWith("//")?"":e.length>1&&e.endsWith("/")?e.slice(0,-1):e},Vy=t=>{const e=String(t||"").trim();if(!e||!e.startsWith("/")||/^\/{2,}/.test(e)||/^\/(?:api|assets)\b/.test(e))return"";const r=e.split(/[?#]/)[0]||"/";return r.startsWith("/")?r.length>1&&r.endsWith("/")&&!r.endsWith("/*")?r.slice(0,-1):r:""},nte=t=>{const e=String(t||"").trim();if(!e)return"";const r=e.split(/[?#]/)[0]||"";if(!r)return"";const n=r.replace(/^https?:\/\/[^/]+/i,"").replace(/^[.][/]/,"").replace(/^[/]+/,"/"),s=n.startsWith("api/")?`/${n}`:n.startsWith("/api/")?n:"";return s?s.length>1&&s.endsWith("/")?s.slice(0,-1):s:""};function fu(t,e){if(e<0||e>=t.length||t[e]!=="{")return null;let r=0,n=!1,s=!1,i=!1,a=!1,o=!1,l=!1;for(let c=e;c<t.length;c+=1){const u=t[c],d=t[c+1];if(a){u===` 1779`&&(a=!1);continue}if(o){u==="*"&&d==="/"&&(o=!1,c+=1);continue}if(n){!l&&u==="'"&&(n=!1),l=!l&&u==="\\";continue}if(s){!l&&u==='"'&&(s=!1),l=!l&&u==="\\";continue}if(i){!l&&u==="`"&&(i=!1),l=!l&&u==="\\";continue}if(u==="/"&&d==="/"){a=!0,c+=1;continue}if(u==="/"&&d==="*"){o=!0,c+=1;continue}if(u==="'"){n=!0,l=!1;continue}if(u==='"'){s=!0,l=!1;continue}if(u==="`"){i=!0,l=!1;continue}if(u==="{"){r+=1;continue}if(u==="}"&&(r-=1,r===0))return{startIndex:e,endIndex:c,body:t.slice(e+1,c)}}return null}function Gy(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")}function ste(t){if(t.length===0)return"";const e=n=>{const s=n.toLowerCase();let i=0;
1779return/\bmenu/.test(s)&&(i+=4),/\bcategor(?:y|ies)/.test(s)&&(i+=2),th.test(n.replace(/[_./-]+/g," "))&&(i+=1),i};return[...t].sort((n,s)=>{const i=e(s)-e(n);return i!==0?i:n.localeCompare(s)})[0]||t[0]}function ite(t){return[...new Set([...[...t.matchAll(/Promise\.all\s*\(\s*([A-Za-z_$][\w$]*)\.map\s*\(/g)].map(e=>e[1]),...[...t.matchAll(/for\s*\(\s*const\s+[A-Za-z_$][\w$]*\s+of\s+([A-Za-z_$][\w$]*)\s*\)/g)].map(e=>e[1])])]}function Vb(t,e){return/insertAppEntityRow(?:<[^>]+>)?\s*\(/.test(t)?!0:e.some(r=>new RegExp(String.raw`\b${xn(r)}\s*\(`).test(t))}function ote(t,e,r){const n=String.raw`${xn(e)}\s*(?:\.\s*length|\?\.\s*length)`,s=new RegExp(String.raw`if\s*\(\s*(?:!\s*${n}|${n}\s*(?:===|<=)\s*0)\s*\)\s*{`,"g"),i=[...t.matchAll(s)];for(const u of i){const d=(u.index??0)+u[0].lastIndexOf("{"),h=fu(t,d);if(!(!h||!Vb(h.body,r)))return h.body}const a=new RegExp(String.raw`if\s*\(\s*(?:${n}|${n}\s*(?:>|>=|!==)\s*(?:0|1)|${n}\s*!=\s*0)\s*\)\s*{`,"g"),o=[...t.matchAll(a)];for(const u of o){const d=(u.index??0)+u[0].lastIndexOf("{"),h=fu(t,d);if(!h||!/\breturn\b/.test(h.body))continue;const m=t.slice(h.endIndex+1);if(Vb(m,r))return m}const c=new RegExp(String.raw`if\s*\(\s*(?:${n}|${n}\s*(?:>|>=|!==)\s*(?:0|1)|${n}\s*!=\s*0)\s*\)\s*return\b`,"g").exec(t);if(c){const u=t.slice((c.index??0)+c[0].length);if(Vb(u,r))return u}return null}function qy(t){return Array.isArray(t)?t.map(r=>qy(r)):!t||typeof t!="object"?t:Object.entries(t).filter(([r])=>!Jee.has(r)).sort(([r],[n])=>r.localeCompare(n)).reduce((r,[n,s])=>(r[n]=qy(s),r),{})}function hL(t){return JSON.stringify(qy(t))}function ate(t){let e;try{e=JSON.parse(String(t||"{}"))}catch{return null}if(!e||typeof e!="object")return null;const r=e,n="tables"in r&&r.tables||null;if(!n||typeof n!="object")return null;const s={...n},i=[];let a=0;for(const[l,c]of Object.entries(n)){if(!c||typeof c!="object")continue;const u=c,d=Array.isArray(u.rows)?u.rows:null;if(!d||d.length<2)continue;const h=[],m=new Set;let b=0,g=0;for(const v of d){if(v&&typeof v=="object"){const _=v,w=Number(_.rowid??_.id);Number.isFinite(w)&&(g=Math.max(g,w));const C=hL(_);if(m.has(C)){b+=1;continue}m.add(C)}h.push(v)}if(b<=0)continue;const p={...u,rows:h},y=Number(u.nextId);Number.isFinite(y)&&(p.nextId=Math.max(y,g+1)),s[l]=p,a+=b,i.push({tableName:l,removedRows:b})}return a<=0?null:{content:`${JSON.stringify({...r,tables:s},null,2)} 1780`,removedRowCount:a,updatedTables:i}}function lte(t){return Object.entries(t).filter(([r,n])=>!!n&&n.type==="file"&&!n.isBinary&&Ht.test(r)&&/selectAppEntityRows(?:<[^>]+>)?\s*\(/.test(String(n.content||""))&&/insertAppEntityRow(?:<[^>]+>)?\s*\(/.test(String(n.content||""))).map(([r])=>r).slice(0,8)}const Vm=t=>{for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file")continue;const n=Ce(e);if(wee.has(n))return!0}return!1},cte=(t,e)=>{if(!t||!e)return!1;if(t==="*"||t==="/*")return!0;if(t.endsWith("/*")){const s=t.slice(0,-2)||"/";return e===s||e.startsWith(`${s}/`)}const r=t.split("/").filter(Boolean),n=e.split("/").filter(Boolean);if(r.length!==n.length)return!1;for(let s=0;s<r.length;s+=1){const i=r[s],a=n[s];if(!i||!a)return!1;if(!(i==="*"||i.startsWith(":"))&&i!==a)return!1}return!0},cr=(t,e)=>[...t].sort((r,n)=>r===e?-1:n===e?1:r.localeCompare(n)),nm=t=>Ce(t).split("/").pop()?.replace(/\.[^.]+$/,"")||t,ute=t=>{const e=Ce(t),r=e.lastIndexOf("/");return r===-1?"":e.slice(0,r)},dte=(t,e)=>{const r=ute(t).split("/").filter(Boolean),n=e.split("/");for(const s of n)if(!(!s||s===".")){if(s===".."){r.pop();continue}r.push(s)}return r.join("/")},ll=t=>new Set(Object.entries(t).filter(([,e])=>!!e&&e.type==="file").map(([e])=>Ce(e))),va=(t,e)=>{const r=dte(t,e);return/\.[A-Za-z0-9]+$/.test(e)?[r]:[...UA.map(s=>`${r}${s}`),...UA.map(s=>`${r}/index${s}`)]},hte=t=>{const e=new Set;for(const r of t.matchAll(/\bexport\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s+(?:const|let|var|class)\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s*\{\s*([^}]+)\s*\}/g)){const n=String(r[1]||"").split(",").map(s=>
1780s.trim()).filter(Boolean);for(const s of n){if(/^type\b/i.test(s))continue;const i=s.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/i),a=String(i?.[2]||i?.[1]||"").trim();a&&e.add(a)}}return e},fte=t=>/\bexport\s+default\b/.test(t)||/\bexport\s*\{[^}]*\bdefault\b[^}]*\}/.test(t),pte=t=>String(t||"").split(",").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(/^type\s+/i,"").split(/\s+as\s+/i)[0]?.trim()||"").filter(Boolean),fL=t=>Object.entries(t).map(([e,r])=>({filePath:Ce(e),entry:r})).filter(({filePath:e,entry:r})=>!!r&&r.type==="file"&&(e==="package.json"||e.endsWith("/package.json"))).sort((e,r)=>e.filePath.length-r.filePath.length||e.filePath.localeCompare(r.filePath))[0]?.filePath||"",pL=t=>{const e=String(t||"").trim().split(/[?#]/)[0]||"";if(!e)return"";if(e.startsWith("@")){const r=e.split("/");return r.length>=2?`${r[0]}/${r[1]}`:e}return e.split("/")[0]||""},mte=t=>{const e=String(t||"").trim().split(/[?#]/)[0]||"";if(!e||e.startsWith(".")||e.startsWith("/")||e.startsWith("~/")||e.startsWith("@/")||e.startsWith("#")||e.startsWith("node:")||/^[a-z][a-z0-9+.-]*:/i.test(e))return!1;const r=pL(e);return!(!r||tte.has(r))},Sh=t=>{const e=ll(t);return lL.find(r=>e.has(r))||""},Ho=t=>{const e=ll(t),r=new Map;for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary)continue;const l=Ce(a);Ht.test(l)&&r.set(l,String(o.content||""))}const n=aL.filter(a=>e.has(a));if(n.length===0)return new Set;const s=new Set,i=[...n];for(;i.length>0;){const a=i.shift();if(!a||s.has(a)||!Ht.test(a))continue;s.add(a);const o=r.get(a);if(!o)continue;const l=[...o.matchAll(KN),...o.matchAll(YN)];for(const c of l){const u=String(c[1]||"").trim();if(!u)continue;const h=va(a,u).find(m=>e.has(m)&&Ht.test(m));h&&!s.has(h)&&i.push(h)}}return s},gte=t=>{const e=[...t.matchAll(/const\s*\{\s*([^}]+)\}\s*=\s*use(?:Auth|AppAuth)\(\s*\)/g)],r=new Set;for(const n of e){const s=String(n[1]||"").split(",").map(i=>i.trim().split(":")[0]?.trim()).filter(Boolean);for(const i of s)/^(?:user|session|currentUser|authenticatedUser)$/i.test(i)&&r.add(i)}return[...r]},bte=t=>{const e=[...t.matchAll(/const\s*\{\s*([^}]+)\}\s*=\s*use(?:Auth|AppAuth)\(\s*\)/g)],r=new Set;for(const n of e){const s=String(n[1]||"").split(",").map(i=>i.trim()).filter(Boolean);for(const i of s){const[a,o]=i.split(":"),l=String(a||"").trim(),c=String(o||"").trim();l==="loading"&&r.add(c||l)}}return[...r]},tn=(t,e)=>{const r=new Set([e]),n=nm(e),s=new RegExp(String.raw`from\s+['"][^'"]*${xn(n)}(?:\.[cm]?[jt]sx?)?['"]`);for(const[i,a]of Object.entries(t))i===e||!a||a.type!=="file"||a.isBinary||!Ht.test(i)||s.test(String(a.content||""))&&r.add(i);return[...r].sort((i,a)=>i===e?-1:a===e?1:i.localeCompare(a))};function vte(t){const e=new Set,r=new Set,n=new Map;let s="../lib/appSchema";const i="src/lib/appSchema.ts",a=(u,d)=>{const h=String(d||"").trim().split(/[?#]/)[0]||"";if(!h)return!1;if(va(u,h).some(g=>Ce(g)===i))return!0;const b=Ce(h.replace(/^~\//,"src/"));return/^src\/lib\/appSchema(?:\.[cm]?[jt]sx?)?$/i.test(b)},o=(u,d)=>{const h=new Set,m=new Set;for(const b of u.matchAll(new RegExp(eee))){const g=String(b[1]||"").trim(),p=String(b[2]||"").trim();a(d,p)&&(g&&h.add(g),p&&m.add(p))}for(const b of u.matchAll(new RegExp(ZZ))){const g=String(b[1]||""),p=String(b[2]||"").trim();if(!a(d,p))continue;p&&m.add(p);const y=g.split(",").map(v=>v.trim()).filter(Boolean);for(const v of y){const _=v.replace(/^type\s+/,"").split(/\s+as\s+/i)[0]?.trim();!_||See.has(_)||h.add(_)}}return{invalidIdentifiers:[...h].sort((b,g)=>b.localeCompare(g)),importSources:[...m].sort((b,g)=>b.localeCompare(g))}};for(const[u,d]of Object.entries(t)){if(!d||d.type!=="file"||d.isBinary||!Ht.test(u))continue;const h=Ce(u);if(h===i)continue;const m=String(d.content||""),b=o(m,h);if(b.invalidIdentifiers.length!==0){e.add(h),n.set(h,b.importSources);for(const g of b.invalidIdentifiers)r.add(g);b.importSources.length>0&&(s=b.importSources[0])}}if(e.size===0)return null;const l=[...e].sort((u,d)=>u.localeCompare(d)),c=n.get(l[0])?.[0];return{code:"invalid-protected-app-schema-import",filePath:l[0],relatedFilePaths:l,importSource:c||s,invalidIdentifiers:[...r].sort((u,d)=>u.localeCompare(d))}}function yte(t){const e=[];for(const[n,s]of Object.entries(t)){if(!s||s.type!=="file"||s.isBinary||!Ht.test(n))continue;const i=Ce(n),a=String(s.content||""),o=new Map,l=new Map;for(const c of a.matchAll(new RegExp(T0))){const u=String(c[1]||"").trim(),d=String(c[2]||"").trim();u&&d&&o.set(u,d)}for(const c of a.matchAll(new RegExp(QZ))){const u=String(c[1]||"").trim(),d=String(c[2]||"").trim();u&&d&&o.set(u,d)}for(const c of a.matchAll(new RegExp(Um))){const u=String(c[1]||""),d=String(c[2]||"").trim();if(!d)continue;const h=u.split(",").map(m=>
1780m.trim()).filter(Boolean);for(const m of h){if(/^type\b/.test(m))continue;const g=m.split(/\s+as\s+/i)[1]?.trim()||m.split(/\s+as\s+/i)[0]?.trim();g&&o.set(g,d)}}for(const c of a.matchAll(new RegExp(Cee))){const u=String(c[1]||"").trim(),d=String(c[2]||"").trim();u&&d&&l.set(d,u)}for(const[c,u]of o){const d=l.get(c);d&&e.push({filePath:i,identifier:c,importSource:u,declarationKind:d})}}if(e.length===0)return null;e.sort((n,s)=>{const i=n.filePath.localeCompare(s.filePath);return i!==0?i:n.identifier.localeCompare(s.identifier)});const r=[...new Set(e.map(n=>n.filePath))];return{code:"duplicate-import-declaration",filePath:r[0],relatedFilePaths:r,duplicateBindings:e}}function _te(t){if(!Vm(t))return null;const e=Object.entries(t).sort(([c],[u])=>Ce(c).localeCompare(Ce(u)));let r="",n="",s="",i=!1;for(const[c,u]of e){if(!u||u.type!=="file"||u.isBinary)continue;const d=Ce(c);d==="vite.local-db.ts"&&(i=!0,s=String(u.content||"")),!(!Ht.test(c)||!QN.test(d)||r)&&(r=d,n=String(u.content||""))}if(!r)return null;const a=/from\s+['"]\.\/vite\.local-db(?:\.[cm]?[jt]s)?['"]/.test(n),o=/\bcreateLocalDbApiPlugin\s*\(/.test(n),l=i&&/(?:\bexport\s+(?:async\s+)?function\s+createLocalDbApiPlugin\b|\bexport\s+const\s+createLocalDbApiPlugin\b|\bexport\s*\{\s*createLocalDbApiPlugin\b)/.test(s);return a&&o&&l?null:{code:"missing-local-db-api-plugin",filePath:r,relatedFilePaths:[r,"vite.local-db.ts"],pluginImportPath:"./vite.local-db"}}function xte(t){const e=fL(t);if(!e)return null;const r=Object.entries(t).find(([m,b])=>!!b&&b.type==="file"&&Ce(m)===e)?.[1];if(!r||r.type!=="file"||r.isBinary)return null;let n;try{n=JSON.parse(String(r.content||"{}"))}catch{return null}
1780const s=new Set(["dependencies","devDependencies","peerDependencies","optionalDependencies"].flatMap(m=>Object.keys(n[m]||{})).filter(Boolean)),i=n.scripts||{},a=Object.values(i).map(m=>String(m||"")).join(` 1781`),o=s.has("react"),l=s.has("vite")||/\bvite\b/.test(a);if(!o||!l)return null;const c=s.has("@vitejs/plugin-react"),d=Object.entries(t).sort(([m],[b])=>Ce(m).localeCompare(Ce(b))).map(([m,b])=>({filePath:Ce(m),entry:b})).find(({filePath:m,entry:b})=>!!b&&b.type==="file"&&!b.isBinary&&Ht.test(m)&&QN.test(m)),h=d?.filePath||"vite.config.ts";if(d?.entry?.type==="file"){const m=String(d.entry.content||""),b=[...m.matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]@vitejs\/plugin-react['"]/g)].map(p=>String(p[1]||"").trim()).filter(Boolean),g=b.some(p=>new RegExp(String.raw`\b${xn(p)}\s*\(`).test(m));if(c&&b.length>0&&g)return null}return{code:"missing-vite-react-plugin",filePath:h,relatedFilePaths:cr(new Set([h,e]),h),packageJsonPath:e,hasReactPluginDependency:c}}function wte(t){if(!Vm(t))return null;const e=Object.entries(t).sort(([r],[n])=>Ce(r).localeCompare(Ce(n)));for(const[r,n]of e){if(!n||n.type!=="file"||n.isBinary||!Ht.test(r))continue;const s=Ce(r);if(Iee.has(s))continue;const a=[...String(n.content||"").matchAll(iee)];for(const o of a){const l=nte(String(o[1]||""));if(!l||!l.startsWith("/api/")||R0.has(l))continue;const c=Nee[l];if(c&&c.length>0)return{code:"invalid-local-api-endpoint",filePath:s,relatedFilePaths:[s],endpointPath:l,suggestionPaths:c};if(l.startsWith("/api/auth/"))return{code:"invalid-local-api-endpoint",filePath:s,relatedFilePaths:[s],endpointPath:l,suggestionPaths:[...ZN]};if(l.startsWith("/api/db/"))return{code:"invalid-local-api-endpoint",filePath:s,relatedFilePaths:[s],endpointPath:l,suggestionPaths:[...eL]}}}return null}function Ste(t){let e=null,r="";for(const[h,m]of Object.entries(t))if(!(!m||m.type!=="file"||m.isBinary)&&qN.test(Ce(h))){e=h,r=String(m.content||"");break}if(!e)return null;const n=Ce(e);let s=null;try{s=JSON.parse(r)}catch{return null}if(!s||typeof s!="object"||Array.isArray(s))return null;const i=s.auth;if(!i||i.enabled!==!0)return null;const a=i.requireLogin===!0,o=Array.isArray(i.protectedPaths)?i.protectedPaths.map(h=>rte(String(h||""))).filter(Boolean):[],l=o.filter(h=>h==="/"||h==="/*"),c=new Set([n]);let u=!1,d=!1;for(const[h,m]of Object.entries(t)){if(!m||m.type!=="file"||m.isBinary)continue;const b=Ce(h),g=String(m.content||"");(eh.test(b)||sL.test(g))&&(u=!0,c.add(b)),(hu.test(b)||iL.test(g))&&(d=!0,c.add(b))}return!u&&!d&&(!a||o.length===0)?null:a?{code:"auth-global-lockout",filePath:n,relatedFilePaths:cr(c,n),hasLoginEntryPoint:u,hasSignupEntryPoint:d,requireLoginEnabled:a,protectedPaths:o,rootProtectedPaths:l}:l.length===0||!u&&!d?null:{code:"auth-global-lockout",filePath:n,relatedFilePaths:cr(c,n),hasLoginEntryPoint:u,hasSignupEntryPoint:d,requireLoginEnabled:a,protectedPaths:o,rootProtectedPaths:l}}function Cte(t,e){const r=new Set,n=new Map,s=[],i=String(t||"").trim(),a=i.match(/\{([\s\S]*?)\}/);if(a?.[1])for(const l of a[1].split(",")){const u=l.trim().match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(!u)continue;const d=u[1],h=u[2]||u[1];if(!MA.includes(d))continue;const m=n.get(d)||[];m.push(h),n.set(d,m)}const o=i.match(/\*\s+as\s+([A-Za-z_$][\w$]*)/);o?.[1]&&s.push(o[1]);for(const[l,c]of n.entries())for(const u of c)new RegExp(`<${u}\\b`).test(e)&&r.add(l);for(const l of s)for(const c of MA)new RegExp(`<${l}\\.${c}\\b`).test(e)&&r.add(c);return[...r]}function Ate(t){const e=ll(t),r="src/components/auth/AuthScreens.tsx";if(!e.has(r))return null;for(const[n,s]of Object.entries(t)){if(!s||s.type!=="file"||s.isBinary||!Ht.test(n))continue;const i=Ce(n);if(i===r||i==="src/lib/appAuth.tsx"||i.startsWith("src/components/auth/"))continue;const a=String(s.content||"");DA.lastIndex=0;for(const o of a.matchAll(DA)){const l=String(o[1]||"").trim(),c=String(o[2]||"").trim();if(!l||!c.startsWith(".")||!va(i,c).find(h=>h===r&&e.has(h)))continue;const d=Cte(l,a);if(d.length!==0)return{code:"direct-auth-screen-mount",filePath:i,relatedFilePaths:cr(new Set([i,r,"src/lib/appAuth.tsx"]),i),authScreensFilePath:r,authScreenNames:d}}}return null}function Ete(t){const e=mL(t);if(!e)return null;const r=Object.entries(t).find(([u,d])=>!!d&&d.type==="file"&&!d.isBinary&&Ce(u)===e.filePath);if(!r)return null;let n=!1;try{const u=r[1]&&r[1].type==="file"?String(r[1].content||"{}"):"{}";n=JSON.parse(u)?.auth?.enabled===!0}catch{return null}if(n)return null;const s="src/lib/appAuth.tsx",i=ll(t);if(!i.has(s))return null;const a=new Set;let o=!1,l=!1;for(const[u,d]of Object.entries(t)){if(!d||d.type!=="file"||d.isBinary||!Ht.test(u))continue;const h=Ce(u);
1781if(h===s||Zee.has(h))continue;const m=String(d.content||"");(eh.test(h)||sL.test(m))&&(o=!0),(hu.test(h)||iL.test(m))&&(l=!0);let b=!1;for(const g of m.matchAll(new RegExp(jee))){const p=String(g[1]||"").trim();if(!p.startsWith("."))continue;if(va(h,p).find(v=>i.has(v))===s){b=!0;break}}!b&&/\/api\/auth\/(?:me|login|signup|logout)\b/.test(m)&&(b=!0),b&&a.add(h)}if(a.size===0)return null;const c=new Set([e.filePath,s,...a]);return{code:"auth-runtime-disabled",filePath:e.filePath,relatedFilePaths:cr(c,e.filePath),builtInAuthModulePath:s,consumerFilePaths:[...a].sort((u,d)=>u.localeCompare(d)),hasLoginEntryPoint:o,hasSignupEntryPoint:l}}function kte(t){const e=[];for(const[n,s]of Object.entries(t)){if(!s||s.type!=="file"||s.isBinary||!Ht.test(n))continue;const i=Ce(n);if(!i.startsWith("src/")||i==="src/lib/appAuth.tsx"||eh.test(i)||hu.test(i))continue;const a=String(s.content||"");let o=null,l="";for(const c of $ee){c.lastIndex=0;const u=c.exec(a);if(u){o=String(u[1]||"").trim()==="signup"?"signup":"login",l=String(u[0]||"").trim();break}}if(!o){OA.lastIndex=0;const c=OA.exec(a);c&&(o=String(c[1]||"").trim()==="signup"?"signup":"login",l=String(c[0]||"").trim())}o&&e.push({code:"hardcoded-auth-shortcut",filePath:i,relatedFilePaths:cr(new Set([i,...tn(t,i).map(c=>Ce(c))]),i),authAction:o,matchedSnippet:l.slice(0,220)})}if(e.length===0)return null;const r=n=>{const s=Ce(n.filePath);return/(?:^|\/)(?:Header|Navbar|NavBar|LandingPage|HomePage|App)\.[cm]?[jt]sx?$/i.test(s)?100:eh.test(s)||hu.test(s)?10:50};return e.sort((n,s)=>{const i=r(s)-r(n);return i!==0?i:n.filePath.localeCompare(s.filePath)}),e[0]}function Pte(t){const e=[];for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||!Ht.test(r))continue;const s=Ce(r);if(!s.startsWith("src/")||!hu.test(s))continue;const i=String(n.content||"");if(!/\bsignup\s*\(/.test(i))continue;const a=new Set;jA.lastIndex=0;for(const u of i.matchAll(new RegExp(jA))){const d=Gy(String(u[1]||""));d&&a.add(d)}const o=[...a].filter(u=>!FA.has(u)).sort((u,d)=>u.localeCompare(d));if(o.length===0)continue;let l=!1,c=!1;BA.lastIndex=0;for(const u of i.matchAll(new RegExp(BA))){const d=(u.index??0)+u[0].lastIndexOf("{"),h=fu(i,d);if(!h)continue;if(h.body.includes("...")){c=!0;break}const m=new Set;$A.lastIndex=0;for(const g of h.body.matchAll(new RegExp($A))){const p=Gy(String(g[1]||""));p&&m.add(p)}if(o.some(g=>m.has(g))){c=!0;break}const b=[...m].filter(g=>!FA.has(g));m.has("email")&&m.has("password")&&b.length===0&&(l=!0)}!l||c||e.push({code:"signup-profile-fields-dropped",filePath:s,relatedFilePaths:cr(new Set([s,...tn(t,s).map(u=>Ce(u))]),s),profileFieldNames:o})}return e.length===0?null:(e.sort((r,n)=>r.filePath.localeCompare(n.filePath)),e[0])}function Tte(t){for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file"||r.isBinary||!Ht.test(e))continue;const n=Ce(e),s=String(r.content||"");if(n==="src/lib/appAuth.tsx"||!Mee.test(s))continue;const i=bte(s);if(i.length===0)continue;const a=[];if(Lee.test(s)&&a.push("/login"),Dee.test(s)&&a.push("/signup"),a.length!==0)for(const o of i){if(!new RegExp(String.raw`if\s*\(\s*${xn(o)}\s*\)\s*{?\s*return\b`).test(s))continue;const c=new Set(tn(t,n));for(const u of Object.keys(t)){const d=Ce(u);(a.includes("/login")&&eh.test(d)||a.includes("/signup")&&hu.test(d))&&c.add(d)}return{code:"auth-shell-loading-gate",filePath:n,relatedFilePaths:cr(c,n),loadingBindingName:o,authEntryPaths:[...a].sort((u,d)=>u.localeCompare(d))}}}return null}function Rte(t){const e=Ho(t),r=Sh(t),n=[];for(const[s,i]of Object.entries(t)){if(!i||i.type!=="file"||i.isBinary||!Ht.test(s))continue;const a=Ce(s);if(!Bee.test(a)||e.size>0&&!e.has(a))continue;const o=String(i.content||"");if(!Wee.test(o)||!Hee.test(o))continue;const l=new Set;WA.lastIndex=0;for(const d of o.matchAll(new RegExp(WA))){const h=Gy(String(d[1]||""));h&&Fee.has(h)&&l.add(h)}const c=[...l].sort((d,h)=>d.localeCompare(h));if(c.length===0||zee.test(o)||!Uee.test(o))continue;const u=new Set([a,...tn(t,a).map(d=>Ce(d))]);r&&u.add(r),n.push({code:"unpersisted-profile-form",filePath:a,relatedFilePaths:cr(u,a),profileFieldNames:c})}return n.length===0?null:(n.sort((s,i)=>s.filePath.localeCompare(i.filePath)),n[0])}function mL(t){for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file"||r.isBinary)continue;const n=Ce(e);if(qN.test(n))try{const s=JSON.parse(String(r.content||"{}")),i=dL(String(s?.app?.slug||""));return i?{filePath:n,slug:i}
1781:null}catch{return null}}return null}function Ite(t){const e=mL(t);if(!e)return null;const r=[];for(const[i,a]of Object.entries(t)){if(!a||a.type!=="file"||a.isBinary||!Ht.test(i))continue;const o=Ce(i);if(o==="src/lib/appSchema.ts")continue;const l=String(a.content||"");if(If.lastIndex=0,!!If.test(l)){If.lastIndex=0;for(const c of l.matchAll(new RegExp(If))){const u=(c.index??0)+c[0].lastIndexOf("{"),d=fu(l,u);if(!d)continue;const h=d.body.match(Oee),m=String(h?.[1]||"").trim();if(m&&dL(m)!==e.slug){r.push({filePath:o,actualAppSlug:m});break}}}}if(r.length===0)return null;r.sort((i,a)=>{const o=i.filePath==="src/appSchema.ts"?-1:0,l=a.filePath==="src/appSchema.ts"?-1:0;return o!==l?o-l:i.filePath.localeCompare(a.filePath)});const n=r[0],s=new Set([e.filePath,...r.map(i=>i.filePath),...tn(t,n.filePath).map(i=>Ce(i))]);return{code:"app-schema-slug-mismatch",filePath:n.filePath,relatedFilePaths:cr(s,n.filePath),runtimeConfigPath:e.filePath,expectedAppSlug:e.slug,actualAppSlug:n.actualAppSlug}}function Nte(t){const e=[];for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||!Ht.test(r))continue;const s=Ce(r);if(!/(?:^|\/)src\/(?:pages|components)\/[A-Za-z0-9_$-]*Page\.[cm]?[jt]sx?$/i.test(s))continue;const i=String(n.content||"");if(!/<[A-Za-z][\w:-]*/.test(i))continue;const a=Vee.find(l=>i.toLowerCase().includes(l));if(!a)continue;const o=cr(new Set([s,...tn(t,s).map(l=>Ce(l))]),s);o.some(l=>lL.includes(l))&&e.push({code:"placeholder-route-shell",filePath:s,relatedFilePaths:o,placeholderCopy:a})}return e.length===0?null:(e.sort((r,n)=>r.filePath.localeCompare(n.filePath)),e[0])}function Lte(t){const e="js/db-runtime.js",r=Object.entries(t).find(([i,a])=>!!a&&a.type==="file"&&!a.isBinary&&Ce(i)===e);if(!r||!r[1]||r[1].type!=="file"||!String(r[1].content||"").includes(HA))return null;const s=new Set([e]);return ll(t).has("package.json")&&s.add("package.json"),ll(t).has(".github/workflows/deploy.yml")&&s.add(".github/workflows/deploy.yml"),{code:"protected-runtime-syntax-corruption",filePath:e,relatedFilePaths:cr(s,e),brokenFragment:HA,fixedFragment:Gee}}function Dte(t){if(!Vm(t))return null;const e=ll(t),r=new Map(Object.entries(t).filter(([,o])=>!!o&&o.type==="file"&&!o.isBinary).map(([o,l])=>[Ce(o),String(l&&l.type==="file"&&l.content||"")])),n=new Map,s=(o,l,c)=>{const u=`${o}::${l}::${c}`,d=n.get(u);if(d)return d;const h={filePath:o,runtimeFilePath:l,importSource:c,relatedFilePaths:cr(new Set([o,l,...tn(t,o).map(m=>Ce(m))]),o),missingExports:new Set};return n.set(u,h),h};for(const[o,l]of Object.entries(t)){if(!l||l.type!=="file"||l.isBinary||!Ht.test(o))continue;const c=Ce(o),u=String(l.content||"");for(const d of u.matchAll(new RegExp(Um))){const h=String(d[1]||""),m=String(d[2]||"").trim();if(!m.startsWith("."))continue;const b=va(c,m).find(w=>ix.has(w)&&e.has(w));if(!b)continue;const g=r.get(b)||"";if(!g)continue;const p=pte(h),y=hte(g),v=p.filter(w=>!y.has(w));if(v.length===0)continue;const _=s(c,b,m);for(const w of v)_.missingExports.add(w)}for(const d of u.matchAll(new RegExp(T0))){const h=String(d[2]||"").trim();if(!h.startsWith("."))continue;const m=va(c,h).find(g=>ix.has(g)&&e.has(g));if(!m)continue;const b=r.get(m)||"";!b||fte(b)||s(c,m,h).missingExports.add("default")}}const i=[...n.values()].filter(o=>o.missingExports.size>0).map(o=>({code:"protected-runtime-export-contract",filePath:o.filePath,relatedFilePaths:o.relatedFilePaths,runtimeFilePath:o.runtimeFilePath,importSource:o.importSource,missingExports:[...o.missingExports].sort((l,c)=>l.localeCompare(c))}));if(i.length===0)return null;const a=o=>{const l=zA.indexOf(o);return l>=0?l:zA.length};return i.sort((o,l)=>{const c=a(o.filePath)-a(l.filePath);if(c!==0)return c;const u=a(o.runtimeFilePath)-a(l.runtimeFilePath);return u!==0?u:o.filePath.localeCompare(l.filePath)}),i[0]}function Mte(t){const e="src/lib/appAuth.tsx",r=ll(t),n=new Map(Object.entries(t).filter(([,l])=>!!l&&l.type==="file"&&!l.isBinary).map(([l,c])=>[Ce(l),String(c&&c.type==="file"&&c.content||"")]));if(!r.has(e))return null;const s=new Map;for(const[l,c]of Object.entries(t)){if(!c||c.type!=="file"||c.isBinary||!Ht.test(l))continue;const u=Ce(l),d=String(c.content||"");for(const h of d.matchAll(new RegExp(Um))){const m=String(h[1]||""),b=String(h[2]||"").trim();if(!b.startsWith(".")||!m.split(",").map(v=>
1781v.trim()).filter(Boolean).map(v=>v.replace(/^type\s+/,"").split(/\s+as\s+/i)[0]?.trim()||"").filter(Boolean).some(v=>v==="AuthProvider"||v==="useAuth"))continue;const p=va(u,b).find(v=>r.has(v));if(!p||p===e)continue;const y=s.get(p)||new Set;y.add(u),s.set(p,y)}for(const h of d.matchAll(new RegExp(T0))){const m=String(h[1]||"").trim(),b=String(h[2]||"").trim();if(!b.startsWith(".")||m!=="AuthProvider"&&m!=="useAuth")continue;const g=va(u,b).find(y=>r.has(y));if(!g||g===e)continue;const p=s.get(g)||new Set;p.add(u),s.set(g,p)}}const i=[...s.entries()].map(([l,c])=>({modulePath:l,consumerPaths:[...c].sort((u,d)=>u.localeCompare(d)),content:n.get(l)||""})).filter(({modulePath:l,content:c})=>!/auth/i.test(l)||/from\s+['"][^'"]*appAuth(?:\.[cm]?[jt]sx?)?['"]/.test(c)?!1:/\bcreateContext(?:<[^>]+>)?\s*\(/.test(c)&&/\buseContext(?:<[^>]+>)?\s*\(/.test(c)&&/\b(?:login|signup|logout)\b/.test(c)).sort((l,c)=>l.modulePath.localeCompare(c.modulePath));if(i.length===0)return null;const a=i[0],o=new Set([e,a.modulePath,...a.consumerPaths]);return{code:"custom-auth-runtime-bypass",filePath:a.modulePath,relatedFilePaths:cr(o,a.modulePath),builtInAuthModulePath:e,customAuthModulePath:a.modulePath,consumerFilePaths:a.consumerPaths}}function Ote(t){const e=zy(t,{includeWarnings:!1,limit:50});if(e.missingDependencies.length===0)return null;const r=e.missingDependencies.map(i=>({filePath:i.importerFile,importSource:i.importSource,expectedPaths:i.expectedPaths,importType:i.importType})),n=r.find(i=>i.filePath==="src/App.tsx")||r[0],s=cr(new Set(r.map(i=>i.filePath)),n.filePath);return{code:"missing-local-import",filePath:n.filePath,relatedFilePaths:s,importSource:n.importSource,expectedPaths:n.expectedPaths,missingImports:r}}function jte(t){const e=fL(t);if(!e)return null;const r=Object.entries(t).find(([m,b])=>!!b&&b.type==="file"&&Ce(m)===e)?.[1];if(!r||r.type!=="file"||r.isBinary)return null;let n;try{n=JSON.parse(String(r.content||""))}catch{return null}const s=n.scripts||{},i=Object.values(s).some(m=>typeof m=="string"&&$Z.test(m)),a=new Set(["dependencies","devDependencies","peerDepen
1781dencies","optionalDependencies"].flatMap(m=>Object.keys(n[m]||{})).filter(Boolean)),o=Object.entries(t).sort(([m],[b])=>Ce(m).localeCompare(Ce(b))),l=new Map;for(const[m,b]of o){if(!b||b.type!=="file"||b.isBinary)continue;const g=Ce(m);if(!Ht.test(g)||g===e)continue;const p=String(b.content||""),y=[...p.matchAll(FZ),...p.matchAll(HZ)];for(const v of y){const _=String(v[1]||"").trim();if(!mte(_))continue;const w=pL(_);!w||a.has(w)||jZ.test(g)&&!i||l.set(`${g}::${w}`,{filePath:g,importSource:_,packageName:w})}}if(l.size===0)return null;const c=[...l.values()],u=c.find(m=>m.filePath==="src/App.tsx")||c[0],d=[...new Set(c.map(m=>m.packageName))].sort(),h=cr(new Set([...c.map(m=>m.filePath),e]),u.filePath);return{code:"missing-package-dependency",filePath:u.filePath,relatedFilePaths:h,packageJsonPath:e,missingPackage:u.packageName,packageNames:d,missingPackages:c}}function $te(t){const e=[];for(const[i,a]of Object.entries(t)){if(!a||a.type!=="file"||a.isBinary)continue;const o=Ce(i);if(!o.startsWith("src/")||!Ht.test(o))continue;const l=String(a.content||""),c=[...l.matchAll(UZ)];for(const u of c){const d=String(u[1]||"").trim();if(!d)continue;const h=u.index??0,m=Math.max(0,h-80),b=Math.min(l.length,h+u[0].length+80),g=l.slice(m,b).replace(/\s+/g," ").trim();e.push({filePath:o,requireSource:d,snippet:g})}}if(e.length===0)return null;const r=e[0],n=[...new Set(e.map(i=>i.requireSource))].sort(),s=cr(new Set(e.flatMap(i=>tn(t,i.filePath))),r.filePath);return{code:"browser-commonjs-require",filePath:r.filePath,relatedFilePaths:s,requireSources:n,requireSites:e}}function Bte(t){const e=Ho(t);if(e.size===0)return null;const r=new Map;for(const[c,u]of Object.entries(t))u?.type==="file"&&!u.isBinary&&r.set(Ce(c),String(u.content||""));if(![...e].some(c=>{const u=r.get(c)||"";return/from\s+['"]phaser['"]|\bPhaser\./.test(u)}))return null;const s=[],i=new Set,a=(c,u,d,h,m)=>{const b=`${c}:${m}:${d}`;i.has(b)||(i.add(b),s.push({filePath:c,kind:m,snippet:u.slice(Math.max(0,d-80),Math.min(u.length,d+h+100)).replace(/\s+/g," ").trim()}))};for(const[c,u]of Object.entries(t)){if(!u||u.type!=="file"||u.isBinary)continue;const d=Ce(c);if(!e.has(d)||!d.startsWith("src/")||!Ht.test(d))continue;const h=String(u.content||""),m=[...h.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*this\.(?:add|make)\.graphics\s*\(/g)].map(g=>String(g[1]||"")).filter(Boolean);for(const g of m){const p=new RegExp(String.raw`\b${xn(g)}\s*\.\s*bezierCurveTo\s*\(`,"g");for(const y of h.matchAll(p))a(d,h,y.index??0,String(y[0]||"").length,"graphics-canvas-api")}const b=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*[\s\S]{0,640}?\.addKeys\s*\([\s\S]{0,640}?\)(?:\s+as\s+[^\r\n;]{1,180})?/g;for(const g of h.matchAll(b)){const p=String(g[1]||""),y=String(g[0]||"");(/\bas\s+(?:(?:Phaser\.)?Input\.Keyboard\.)?Key\s*\[\s*\]/.test(y)||/\bas\s+Array\s*<\s*(?:(?:Phaser\.)?Input\.Keyboard\.)?Key\s*>/.test(y)||new RegExp(String.raw`\b${xn(p)}\s*\[\s*\d+\s*\]`).test(h))&&a(d,h,g.index??0,y.length,"add-keys-array-assumption")}for(const g of h.matchAll(/\b(?:const|let|var)\s*\[[^\]]+\]\s*=\s*[^;]{0,640}?\.addKeys\s*\(/g))a(d,h,g.index??0,String(g[0]||"").length,"add-keys-array-assumption")}if(s.length===0)return null;const o=s[0].filePath,l=new Set(s.map(c=>c.filePath));for(const c of s)for(const u of tn(t,c.filePath))l.add(Ce(u));return{code:"phaser-runtime-api-misuse",filePath:o,relatedFilePaths:cr(l,o),violations:s}}function gL(t,e){const r=new Set;for(const n of t.matchAll(new RegExp(Um))){const s=String(n[1]||"");if(String(n[2]||"").trim()!==e)continue;const a=s.split(",").map(o=>o.trim()).filter(Boolean);for(const o of a){if(/^type\b/i.test(o))continue;const l=o.split(/\s+as\s+/i)[1]?.trim()||o.split(/\s+as\s+/i)[0]?.trim();l&&r.add(l)}}return r}function Fte(t){return gL(t,"three")}function bL(t,e){return new RegExp(String.raw`\b(?:const|let|var|function|class)\s+${xn(e)}\b`).test(t)}function Wte(t,e,r){const n=[];for(const s of Aee){if(r.has(s)||bL(t,s))continue;const i=new RegExp(String.raw`\bnew\s+${xn(s)}\b|\binstanceof\s+${xn(s)}\b|\b${xn(s)}\s*(?:\(|\.)`,"g");for(const a of t.matchAll(i)){const o=String(a[0]||""),l=a.index??0,c=o.indexOf(s),u=l+Math.max(c,0),d=u>0?t[u-1]:"";if(d==="."||/[\w$]/.test(d))continue;const h=Math.max(0,u-80),m=Math.min(t.length,u+s.length+80),b=t.slice(h,m).replace(/\s+/g," ").trim();
1781n.push({filePath:e,symbolName:s,snippet:b});break}}return n}function Hte(t){const e=Ho(t),r=[];for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary)continue;const l=Ce(a);if(!e.has(l)||!Ht.test(l))continue;const c=String(o.content||"");if(!XN.test(c))continue;const u=Fte(c);r.push(...Wte(c,l,u))}if(r.length===0)return null;const n=r[0],s=[...new Set(r.map(a=>a.symbolName))].sort(),i=cr(new Set(r.flatMap(a=>tn(t,a.filePath))),n.filePath);return{code:"missing-three-symbol-import",filePath:n.filePath,relatedFilePaths:i,missingSymbols:s,missingSymbolSites:r}}function Ute(t,e,r){const n=[];for(const s of Eee){if(r.has(s)||bL(t,s))continue;const i=s==="Canvas"?/<Canvas\b/g:new RegExp(String.raw`\b${xn(s)}\s*\(`,"g");for(const a of t.matchAll(i)){const o=a.index??0,l=Math.max(0,o-80),c=Math.min(t.length,o+String(a[0]||"").length+80),u=t.slice(l,c).replace(/\s+/g," ").trim();n.push({filePath:e,symbolName:s,snippet:u});break}}return n}function zte(t){const e=Ho(t),r=[];for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary)continue;const l=Ce(a);if(!e.has(l)||!Ht.test(l))continue;const c=String(o.content||"");if(!XN.test(c))continue;const u=gL(c,"@react-three/fiber");r.push(...Ute(c,l,u))}if(r.length===0)return null;const n=r[0],s=[...new Set(r.map(a=>a.symbolName))].sort(),i=cr(new Set(r.flatMap(a=>tn(t,a.filePath))),n.filePath);return{code:"missing-react-three-fiber-symbol-import",filePath:n.filePath,relatedFilePaths:i,missingSymbols:s,missingSymbolSites:r}}function Vte(t){const e=new Map,r=/(?:export\s+default\s+|export\s+)?function\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s*(?::[^{]+)?{/g,n=/(?:export\s+)?const\s+([A-Z][A-Za-z0-9_$]*)\s*(?::[^=]+)?=\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=>\s*{/g;for(const s of[r,n])for(const i of t.matchAll(s)){const a=String(i[1]||"").trim(),o=(i.index??0)+String(i[0]||"").lastIndexOf("{"),l=fu(t,o);!a||!l||e.has(a)||e.set(a,{name:a,body:l.body,startIndex:l.startIndex,endIndex:l.endIndex})}return e}function VA(t,e,r){if(/<Html\b/.test(t))return[];const n=[];for(const s of t.matchAll(new RegExp(Tee))){const i=String(s[1]||"").trim();if(!kee.has(i))continue;const a=s.index??0,o=Math.max(0,a-80),l=Math.min(t.length,a+String(s[0]||"").length+160),c=t.slice(o,l).replace(/\s+/g," ").trim();n.push({filePath:e,componentName:r,tagName:i,snippet:c})}return n}function GA(t){return[...new Set([...t.matchAll(new RegExp(Pee))].map(e=>String(e[1]||"")))]}function Gte(t){const e=Ho(t),r=Sh(t);for(const[n,s]of Object.entries(t)){if(!s||s.type!=="file"||s.isBinary)continue;const i=Ce(n);if(!e.has(i)||!Ht.test(i))continue;const a=String(s.content||"");if(!/<Canvas\b/.test(a))continue;const o=Vte(a),l=[...a.matchAll(new RegExp(Ree))].map(c=>String(c[0]||""));for(const c of l){const u=VA(c,i,"<Canvas>");if(u.length>0){const m=[...new Set(u.map(g=>g.tagName))].sort(),b=cr(new Set([i,r,...tn(t,i).map(g=>Ce(g))].filter(Boolean)),i);return{code:"react-three-dom-element-in-canvas",filePath:i,relatedFilePaths:b,canvasFilePath:i,componentName:"<Canvas>",invalidTags:m,invalidTagSites:u}}const d=GA(c).filter(m=>m!=="Canvas"),h=new Set;for(;d.length>0;){const m=d.shift();if(!m||h.has(m))continue;h.add(m);const b=o.get(m);if(!b)continue;const g=VA(b.body,i,m);if(g.length>0){const p=[...new Set(g.map(v=>v.tagName))].sort(),y=cr(new Set([i,r,...tn(t,i).map(v=>Ce(v))].filter(Boolean)),i);return{code:"react-three-dom-element-in-canvas",filePath:i,relatedFilePaths:y,canvasFilePath:i,componentName:m,invalidTags:p,invalidTagSites:g}}for(const p of GA(b.body))h.has(p)||d.push(p)}}}return null}function qte(t){const e=Ho(t),r=Sh(t);if(e.size===0)return null;const n=[];let s=!1;for(const[o,l]of Object.entries(t)){if(!l||l.type!=="file"||l.isBinary)continue;const c=Ce(o);if(!e.has(c))continue;const u=String(l.content||"");zZ.test(u)&&(VZ.test(u)&&(s=!0),GZ.test(u)&&n.push(c))}if(s||n.length===0)return null;const i=n.find(o=>/(?:^|\/)src\/(?:entities|components)\//.test(o))||n[0],a=cr(new Set([r,...n,...tn(t,i).map(o=>Ce(o))].filter(Boolean)),i);return{code:"missing-react-three-physics-provider",filePath:i,relatedFilePaths:a,physicsConsumerFilePaths:[...new Set(n)].sort()}}function Kte(t){const e=Ho(t),r=Sh(t);if(e.size===0)return null;const n=[];let s=!1;for(const[o,l]of Object.entries(t)){if(!l||l.type!=="file"||l.isBinary)continue;const c=Ce(o);if(!e.has(c))continue;const u=String(l.content||"");KZ.test(u)&&(s=!0),qZ.test(u)&&n.push(c)}if(s||n.length===0)return null;const i=n[0],a=cr(new Set([r,...n,...tn(t,i).map(o=>
1781Ce(o))].filter(Boolean)),i);return{code:"missing-text-geometry-extension",filePath:i,relatedFilePaths:a,textGeometryFilePaths:[...new Set(n)].sort()}}function Yte(t){const e=Ho(t),r=Sh(t);if(e.size===0||!r)return null;const n=Object.entries(t).filter(([s,i])=>{if(!i||i.type!=="file"||i.isBinary)return!1;const a=Ce(s);return!a.startsWith("src/")||!Ht.test(a)||/\.(?:test|spec|stories)\.[cm]?[jt]sx?$/i.test(a)||e.has(a)||!cL.test(nm(a))?!1:ete.test(String(i.content||""))}).map(([s])=>Ce(s)).sort((s,i)=>s.localeCompare(i));return n.length===0?null:{code:"orphaned-navigation-component",filePath:r,relatedFilePaths:cr(new Set([r,...n]),r),componentFilePaths:n,componentNames:n.map(s=>nm(s))}}function Xte(t){const e=Object.entries(t).sort(([c],[u])=>Ce(c).localeCompare(Ce(u))),r=Ho(t);let n="",s="";for(const[c,u]of e){if(!u||u.type!=="file"||u.isBinary||!Ht.test(c))continue;const d=Ce(c).toLowerCase();if(!(d!=="src/app.tsx"&&d!=="src/app.jsx")){n=c,s=String(u.content||"");break}}if(!n)return null;const i=Ce(n),a=Array.from(new Set([...s.matchAll(JN)].map(c=>Vy(String(c[1]||""))).filter(Boolean))),o=new Map;for(const[c,u]of e){if(!u||u.type!=="file"||u.isBinary||!Ht.test(c))continue;const d=Ce(c);if(r.size>0&&!r.has(d))continue;const h=String(u.content||"");for(const m of tee)for(const b of h.matchAll(m)){const g=Vy(String(b[1]||""));if(!g)continue;const p=o.get(g)||new Set;p.add(d),o.set(g,p)}}if(a.length===0){const c=[...o.keys()].filter(m=>m!=="/").sort((m,b)=>m.localeCompare(b));if(c.length===0)return null;const u=c[0],d=new Set;for(const m of c)for(const b of o.get(m)||[])d.add(b);const h=cr(new Set([i,...d]),i);return{code:"unmatched-navigation-route",filePath:i,relatedFilePaths:h,missingPath:u,missingPaths:c,knownRoutePaths:[]}}const l=[...o.entries()].filter(([c])=>!a.some(u=>cte(u,c))).sort(([c],[u])=>c.localeCompare(u));if(l.length>0){const c=l.map(([h])=>h),u=new Set;for(const[,h]of l)for(const m of h)u.add(m);const d=cr(new Set([i,...u]),i);return{code:"unmatched-navigation-route",filePath:i,relatedFilePaths:d,missingPath:c[0],missingPaths:c,knownRoutePaths:[...a].sort((h,m)=>h.localeCompare(m))}}return null}function Jte(t){const e=Object.entries(t).sort(([u],[d])=>Ce(u).localeCompare(Ce(d))),r=Ho(t);let n="",s="";for(const[u,d]of e){if(!d||d.type!=="file"||d.isBinary||!Ht.test(u))continue;const h=Ce(u).toLowerCase();if(!(h!=="src/app.tsx"&&h!=="src/app.jsx")){n=u,s=String(d.content||"");break}}if(!n)return null;const i=Ce(n),a=Array.from(new Set([...s.matchAll(JN)].map(u=>Vy(String(u[1]||""))).filter(Boolean))).sort((u,d)=>u.localeCompare(d));if(a.length===0)return null;const o=[],l=new Set;for(const[u,d]of e){if(!d||d.type!=="file"||d.isBinary||!Ht.test(u))continue;const h=Ce(u);if(r.size>0&&!r.has(h)||!h.startsWith("src/")||h===i||/\.(?:test|spec|stories)\.[cm]?[jt]sx?$/i.test(h))continue;const m=String(d.content||"");if([...m.matchAll(YZ)].length<2||!(cL.test(nm(h))||/<(?:nav|aside)\b/i.test(m)||/\bnavItems\b/.test(m)))continue;const p=[...m.matchAll(JZ),...m.matchAll(XZ)].map(y=>String(y[1]||"").trim()).filter(Boolean);if(p.length!==0){l.add(h);for(const y of p)o.push({filePath:h,label:y})}}if(o.length===0||l.size===0)return null;const c=[...l].sort((u,d)=>u.localeCompare(d))[0];return{code:"placeholder-navigation-link",filePath:c,relatedFilePaths:cr(new Set([i,...l]),c),knownRoutePaths:a,placeholderLinks:o}}function Qte(t){const e=new Map;for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary||!Ht.test(a))continue;const l=Ce(a);if(!l.startsWith("src/")||/\.(?:test|spec|stories)\.[cm]?[jt]sx?$/i.test(l))continue;const c=String(o.content||"");if(!see.test(c))continue;const u=Array.from(new Set([...c.matchAll(nee)].map(h=>String(h[1]||"").trim()).filter(h=>ree.includes(h))));if(u.length===0)continue;const d=e.get(l);if(d){for(const h of u)d.providerComponents.add(h);continue}e.set(l,{filePath:l,providerComponents:new Set(u)})}const r=[...e.values()].map(a=>({filePath:a.filePath,providerComponents:[...a.providerComponents].sort((o,l)=>o.localeCompare(l))}));if(r.length<=1)return null;const n=r.find(a=>!/^src\/(?:main|App)\.[cm]?[jt]sx?$/i.test(a.filePath))?.filePath||r[0].filePath,s=cr(new Set(r.map(a=>a.filePath)),n),i=Array.from(new Set(r.flatMap(a=>a.providerComponents))).sort((a,o)=>a.localeCompare(o));return{code:"nested-router-provider",filePath:n,relatedFilePaths:s,routerProviderFiles:r.map(a=>a.filePath).sort((a,o)=>a.localeCompare(o)),providerComponents:i}}function Zte(t){for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file"||r.isBinary||!Ht.test(e))continue;const n=String(r.content||""),s=[...n.matchAll(/const\s*\[\s*([A-Za-z_$][\w$]*)\s*,\s*([A-Za-z_$][\w$]*)\s*\]\s*=\s*useState(?:<[^>]+>)?\(\s*true\s*\)/g)];if(s.length===0)continue;const i=gte(n);if(i.length!==0)for(const a of s){const o=a[1],l=a[2];if(!/loading/i.test(o)&&!/loading/i.test(l))continue;const c=new RegExp(String.raw`${xn(l)}\s*\(\s*false\s*\)`);for(const u of i){const d=new RegExp(String.raw`useEffect\(\(\)\s*=>\s*{([\s\S]*?)}\s*,\s*\[\s*${xn(u)}\s*\]\s*\)`),h=n.match(d);if(!h)continue;const m=h[1];if(c.test(m))continue;const b=m.match(new RegExp(String.raw`if\s*\(\s*${xn(u)}\s*\)\s*{?\s*([A-Za-z_$][\w$]*)\s*\(`));if(!b)continue;const g=b[1],p=n.search(new RegExp(String.raw`const\s+${xn(g)}\s*=\s*async\s*\(`));if(p===-1)continue;const y=n.slice(p,p+600),v=new RegExp(String.raw`if\s*\(\s*!\s*${xn(u)}\s*\)\s*return\b`),_=new RegExp(String.raw`if\s*\(\s*!\s*${xn(u)}\s*\)\s*{([\s\S]{0,240}?)}`),w=v.test(y),C=y.match(_),A=!!C&&/\breturn\b/.test(C[1])&&!c.test(C[1]);if(!(!w&&!A))return{code:"auth-gated-loading-state",filePath:e,relatedFilePaths:tn(t,e),loadingStateName:o,loadingSetterName:l,authStateName:u,fetchFunctionName:g}}}}return null}function ere(t){for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file"||r.isBinary)continue;const n=Ce(e);if(!I0.test(n))continue;let s;try{s=JSON.parse(String(r.content||"{}"))}catch{continue}if(!s||typeof s!="object")continue;const i="tables"in s?s.tables:null;if(!i||typeof i!="object")continue;const a=[];let o=0;for(const[c,u]of Object.entries(i)){if(!u||typeof u!="object")continue;const d="rows"in u?u.rows:null;if(!Array.isArray(d)||d.length<2)continue;const h=new Map;let m=0;for(const b of d){if(!b||typeof b!="object")continue;const g=hL(b),p=h.get(g)||0;h.set(g,p+1),p>0&&(m+=1)}m<=0||(a.push({tableName:c,duplicateRows:m}),o+=m)}if(o<=0)continue;const l=lte(t);return l.includes(e)||l.unshift(e),{code:"persisted-local-db-duplicate-rows",filePath:e,relatedFilePaths:l,duplicateRowCount:o,duplicateTables:a.sort((c,u)=>u.duplicateRows-c.duplicateRows).slice(0,8)}}return null}function tre(t){const e=Object.entries(t).find(([o,l])=>!!l&&l.type==="file"&&!l.isBinary&&I0.test(Ce(o)));if(!e)return null;const r=e[1];if(!r||r.type!=="file"||r.isBinary)return null;let n;try{n=JSON.parse(String(r.content||"{}"))}catch{return null}if(!n||typeof n!="object")return null;const s="tables"in n?n.tables:null;if(!s||typeof s!="object")return null;const i=Object.entries(s).filter(([o,l])=>{const c=o.replace(/[_./-]+/g," ");
1781if(!th.test(c)||!l||typeof l!="object")return!1;const u="rows"in l?l.rows:null;return Array.isArray(u)&&u.length===0}).map(([o])=>o).sort((o,l)=>o.localeCompare(l));if(i.length===0)return null;const a=Object.entries(t).filter(([o,l])=>{if(!l||l.type!=="file"||l.isBinary||!Ht.test(o))return!1;const c=Ce(o);return!c.startsWith("src/")||/^src\/lib\/(?:appData|appSchema|cloudflareCrud)\.[cm]?[jt]sx?$/i.test(c)?!1:oL.test(String(l.content||""))}).map(([o])=>Ce(o)).sort((o,l)=>o.localeCompare(l));if(a.length===0)return null;for(const[o,l]of Object.entries(t)){if(!l||l.type!=="file"||l.isBinary||!Ht.test(o))continue;const c=Ce(o);if(!Yee.test(c))continue;const d=[...String(l.content||"").matchAll(Xee)].map(b=>String(b[1]||"").trim()).filter(b=>th.test(b));if(d.length===0)continue;const h=new Set;for(const[b,g]of Object.entries(t)){if(b===o||!g||g.type!=="file"||g.isBinary||!Ht.test(b))continue;const p=Ce(b),y=String(g.content||""),v=[...y.matchAll(KN),...y.matchAll(YN)];let _=!1;for(const w of v){const C=String(w[1]||"").trim();if(!C.startsWith("."))continue;if(va(p,C).includes(c)){_=!0;break}}_&&/insertAppEntityRow(?:<[^>]+>)?\s*\(|updateAppEntityRow(?:<[^>]+>)?\s*\(|deleteAppEntityRow(?:<[^>]+>)?\s*\(|\/api\/db\/insert/.test(y)&&h.add(p)}if(h.size>0)continue;const m=cr(new Set([c,Ce(e[0]),...a,...tn(t,c).map(b=>Ce(b))]),c);return{code:"unpersisted-catalog-seed-data",filePath:c,relatedFilePaths:m,sourceNames:[...new Set(d)],consumerFilePaths:a,emptyTables:i}}return null}function rre(t){const e=Object.entries(t).filter(([r,n])=>{if(!n||n.type!=="file"||n.isBinary||!Ht.test(r))return!1;const s=Ce(r);return!s.startsWith("src/")||/^src\/lib\/(?:appData|appSchema|cloudflareCrud)\.[cm]?[jt]sx?$/i.test(s)?!1:oL.test(String(n.content||""))}).map(([r])=>Ce(r)).sort((r,n)=>r.localeCompare(n));if(e.length===0)return null;for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||!Ht.test(r))continue;const s=Ce(r),i=String(n.content||"");if(!/^src\/(?:App|main)\.[cm]?[jt]sx?$/i.test(s)||!/\bensureAppSchema\s*\(/.test(i)||!/(?:<Routes\b|<Route\b)/.test(i))continue;const a=[...i.matchAll(Kee)];if(a.length!==0)for(const o of a){const l=String(o[1]||"").trim(),c=String(o[2]||"").trim();if(!/init|ready|boot|hydrat|load|schema|seed/i.test(l)&&!/init|ready|boot|hydrat|load|schema|seed/i.test(c)||!new RegExp(String.raw`${xn(c)}\s*\(\s*true\s*\)`).test(i)||[new RegExp(String.raw`if\s*\(\s*!\s*${xn(l)}\s*\)\s*return\b`),new RegExp(String.raw`if\s*\(\s*!\s*${xn(l)}\s*\)\s*{[\s\S]{0,240}?\breturn\b`),new RegExp(String.raw`return\s*\([\s\S]{0,240}?!\s*${xn(l)}\s*\?`),new RegExp(String.raw`return\s*\([\s\S]{0,240}?${xn(l)}\s*\?`)].some(m=>m.test(i)))continue;const h=cr(new Set([s,...e,...tn(t,s).map(m=>Ce(m))]),s);return{code:"persisted-data-bootstrap-race",filePath:s,relatedFilePaths:h,bootstrapStateName:l,consumerFilePaths:e}}}return null}function nre(t){const e=Object.keys(t).find(i=>Ce(i)==="src/lib/appSecrets.ts"),r=nL.map(i=>{const a=t[i];return{filePath:i,isPresent:!!(a&&a.type==="file"&&!a.isBinary),content:a&&a.type==="file"&&!a.isBinary?String(a.content||""):""}}),n=new Map;for(const[i,a]of Object.entries(t)){if(!a||a.type!=="file"||a.isBinary||!Ht.test(i))continue;const o=Ce(i);if(!o.startsWith("src/")||o==="src/lib/appSecrets.ts")continue;const l=String(a.content||"");if(zm.test(`${o} 1782${l}`))for(const c of l.matchAll(tL)){const u=uL(c[1]);if(!u||R0.has(u)||!rL.test(u))continue;const d=n.get(u)||new Set;d.add(o),n.set(u,d)}}const s=[...n.entries()].sort((i,a)=>{const o=c=>{let u=0;return/checkout/i.test(c)&&(u-=30),/payment/i.test(c)&&(u-=20),/stripe/i.test(c)&&(u-=10),u},l=o(i[0])-o(a[0]);return l!==0?l:i[0].localeCompare(a[0])});for(const[i,a]of s){const l=r.some(({isPresent:h,content:m})=>h&&m.includes(i))?[]:r.filter(({isPresent:h,content:m})=>!h||!m.includes(i)).map(({filePath:h})=>h);if(l.length===0)continue;const c=[...a].sort((h,m)=>h.localeCompare(m)),u=c[0],d=cr(new Set([u,...c,...l,...e?[Ce(e)]:[],...tn(t,u).map(h=>Ce(h))]),u);return{code:"missing-stripe-checkout-route",filePath:u,relatedFilePaths:d,endpointPath:i,frontendFilePaths:c,missingRu
1782ntimeFilePaths:l}}return null}function sre(t){if(!Vm(t))return null;const e=Object.keys(t).find(a=>Ce(a)==="src/lib/appSecrets.ts"),n=nL.map(a=>{const o=t[a];return{filePath:a,isPresent:!!(o&&o.type==="file"&&!o.isBinary),content:o&&o.type==="file"&&!o.isBinary?String(o.content||""):""}}).find(({filePath:a})=>a==="vite.local-db.ts");if(!n?.isPresent||!n.content)return null;const s=new Map;for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary||!Ht.test(a))continue;const l=Ce(a);if(!l.startsWith("src/")||l==="src/lib/appSecrets.ts")continue;const c=String(o.content||"");if(zm.test(`${l} 1783${c}`))for(const u of c.matchAll(tL)){const d=uL(u[1]);if(!d||R0.has(d)||!rL.test(d))continue;const h=s.get(d)||new Set;h.add(l),s.set(d,h)}}const i=[...s.entries()].sort((a,o)=>a[0].localeCompare(o[0]));for(const[a,o]of i){if(!n.content.includes(a)||!hee.test(n.content)||dee.test(n.content))continue;const l=[...o].sort((d,h)=>d.localeCompare(h)),c=n.filePath,u=cr(new Set([c,...l,"js/worker.js",...e?[Ce(e)]:[],...tn(t,l[0]||c).map(d=>Ce(d))]),c);return{code:"invalid-stripe-preview-secret-access",filePath:c,relatedFilePaths:u,endpointPath:a,runtimeFilePath:n.filePath}}return null}function ire(t){const e=Object.keys(t).find(a=>Ce(a)==="src/lib/appSecrets.ts"),r=a=>{const o=Ce(a);let l=0;return/\/(?:pages|routes)\//i.test(o)&&(l-=40),/\/(?:components|features|sections)\//i.test(o)&&(l-=20),/(?:checkout|payment|billing|stripe|deposit|subscription|cart|order)/i.test(o)&&(l-=30),l},s=Object.entries(t).filter(([a,o])=>{if(!o||o.type!=="file"||o.isBinary||!Ht.test(a))return!1;const l=Ce(a);if(!l.startsWith("src/")||l==="src/lib/appSecrets.ts")return!1;const c=String(o.content||"");return!c.toLowerCase().includes(lee)||!/(stripe|checkout|payment|billing|deposit|subscription|order)/i.test(c)||!cee.test(c)?!1:!uee.test(c)}).map(([a])=>Ce(a)).sort((a,o)=>{const l=r(a)-r(o);return l!==0?l:a.localeCompare(o)})[0];if(!s)return null;const i=cr(new Set([s,...e?[Ce(e)]:[],...tn(t,s).map(a=>Ce(a))]),s);return{code:"static-stripe-setup-banner",filePath:s,relatedFilePaths:i,setupMessage:"To accept payments, connect your Stripe account."}}function ore(t){const e=Object.keys(t).find(a=>Ce(a)==="src/lib/appSecrets.ts"),r=a=>{const o=Ce(a);let l=0;return/\/(?:pages|routes)\//i.test(o)&&(l-=40),/\/(?:components|features|sections)\//i.test(o)&&(l-=20),/(?:checkout|payment|billing|stripe|deposit|subscription|cart|order|buy)/i.test(o)&&(l-=30),l},n=Object.entries(t).map(([a,o])=>{if(!o||o.type!=="file"||o.isBinary||!Ht.test(a))return null;const l=Ce(a);if(!l.startsWith("src/")||l==="src/lib/appSecrets.ts")return null;const c=String(o.content||""),u=pee.find(v=>c.includes(v));if(!u||!zm.test(`${l} 1784${c}`))return null;const d=bee.test(c),h=mee.test(c),m=gee.test(c),b=!(h&&m),g=vee.test(c)&&!h,p=!yee.test(c),y=!_ee.test(c);return!d&&!g?null:{filePath:l,endpointPath:u,hasRawCardCollection:d,missingSessionRedirect:b,simulatesLocalSuccess:g,missingSuccessUrl:p,missingCancelUrl:y}}).filter(Boolean);n.sort((a,o)=>{const l=u=>{let d=r(u.filePath);return u.hasRawCardCollection&&(d-=50),u.simulatesLocalSuccess&&(d-=40),u.missingSessionRedirect&&(d-=20),u.missingSuccessUrl&&(d-=10),u.missingCancelUrl&&(d-=10),d},c=l(a)-l(o);return c!==0?c:a.filePath.localeCompare(o.filePath)});const s=n[0];if(!s)return null;const i=cr(new Set([s.filePath,...e?[Ce(e)]:[],...tn(t,s.filePath).map(a=>Ce(a))]),s.filePath);return{code:"invalid-stripe-checkout-client-flow",filePath:s.filePath,relatedFilePaths:i,endpointPath:s.endpointPath,hasRawCardCollection:s.hasRawCardCollection,missingSessionRedirect:s.missingSessionRedirect,simulatesLocalSuccess:s.simulatesLocalSuccess,missingSuccessUrl:s.missingSuccessUrl,missingCancelUrl:s.missingCancelUrl}}function are(t){const e=i=>{const a=Ce(i);let o=0;return/\/(?:pages|routes)\//i.test(a)&&(o-=40),/\/(?:components|features|sections)\//i.test(a)&&(o-=20),/(?:checkout|payment|billing|stripe|deposit|subscription|cart|order|buy)/i.test(a)&&(o-=30),o},r=Object.entries(t).map(([i,a])=>{if(!a||a.type!=="file"||a.isBinary||!Ht.test(i))return null;const o=Ce(i);if(!o.startsWith("src/")||o==="src/lib/appSecrets.ts")return null;const l=String(a.content||"");if(!zm.test(`${o} 1785${l}`))return null;const c=[...l.matchAll(fee)][0];if(!c)return null;const u=String(c[2]||"").replace(/\s+/g," ").trim();return{filePath:o,alertSnippet:String(c[0]||"").trim(),alertText:u,containsNonEnglishCopy:xee.test(u)}}
1785).filter(Boolean);r.sort((i,a)=>{const o=e(i.filePath)-e(a.filePath);return o!==0?o:i.filePath.localeCompare(a.filePath)});const n=r[0];if(!n)return null;const s=cr(new Set([n.filePath,...tn(t,n.filePath).map(i=>Ce(i))]),n.filePath);return{code:"payment-browser-alert",filePath:n.filePath,relatedFilePaths:s,alertSnippet:n.alertSnippet,alertText:n.alertText,containsNonEnglishCopy:n.containsNonEnglishCopy}}function lre(t){const e=new Map;for(const[l,c]of Object.entries(t)){if(!c||c.type!=="file"||c.isBinary)continue;const u=String(c.content||"");if(!/unsplash/i.test(u))continue;const d=Ce(l),h=e.get(d)||{filePath:d,disallowedHosts:new Set,matchedUrls:new Set};for(const{host:m,pattern:b}of Qee){const g=u.match(b);if(!(!g||g.length===0)){h.disallowedHosts.add(m);for(const p of g)h.matchedUrls.add(p)}}h.matchedUrls.size>0&&e.set(d,h)}if(e.size===0)return null;const r=l=>{const c=Ce(l);return I0.test(c)?120:/(?:^|\/)(?:seed|default|mock|sample)[\w-]*\.[cm]?[jt]sx?$/i.test(c)||/\/data\//i.test(c)?90:/\/(?:pages|hooks|components)\//i.test(c)?40:/\/App\.[cm]?[jt]sx?$/i.test(c)?30:0},n=[...e.values()].sort((l,c)=>{const u=r(c.filePath)-r(l.filePath);return u!==0?u:l.filePath.localeCompare(c.filePath)}),s=n[0],i=new Set([s.filePath,...n.map(l=>l.filePath),...tn(t,s.filePath).map(l=>Ce(l))]),a=n.flatMap(l=>[...l.matchedUrls]),o=[...new Set(n.flatMap(l=>[...l.disallowedHosts]))].sort();return{code:"unsupported-stock-image-host",filePath:s.filePath,relatedFilePaths:cr(i,s.filePath),disallowedHosts:o,matchedUrls:[...new Set(a
1785)].slice(0,12)}}function cre(t){const e=new Map;for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||!o.isBinary)continue;const l=Ce(a),c=l.match(/\/public\/workspace-assets\/([A-Za-z0-9_-]+)-[^/]+\.[a-z0-9]+$/i);c&&e.set(c[1],{workspaceFilePath:l.replace(/^\//,""),localPublicUrl:l.replace(/^.*\/public(?=\/)/,"")})}if(e.size===0)return null;const r=[];for(const[a,o]of Object.entries(t)){if(!o||o.type!=="file"||o.isBinary||!Ht.test(a))continue;const l=String(o.content||"");if(!l.includes("/api/assets/"))continue;const c=new Map,u=Ce(a);for(const d of l.matchAll(WZ)){const h=d[0],m=d[1],b=e.get(m);b&&c.set(h,{assetId:m,remoteUrl:h,localPublicUrl:b.localPublicUrl,workspaceFilePath:b.workspaceFilePath})}c.size!==0&&r.push({filePath:u,assetReplacements:[...c.values()]})}if(r.length===0)return null;const n=a=>{const o=Ce(a);return/\/App\.[cm]?[jt]sx?$/i.test(o)?120:/\/(?:pages|components|sections)\//i.test(o)?80:20};r.sort((a,o)=>{const l=n(o.filePath)-n(a.filePath);return l!==0?l:a.filePath.localeCompare(o.filePath)});const s=r[0],i=new Set([s.filePath,...r.map(a=>a.filePath),...s.assetReplacements.map(a=>a.workspaceFilePath),...tn(t,s.filePath).map(a=>Ce(a))]);return{code:"remote-managed-asset-url",filePath:s.filePath,relatedFilePaths:cr(i,s.filePath),assetReplacements:s.assetReplacements.slice(0,8)}}function ure(t){for(const[e,r]of Object.entries(t)){if(!r||r.type!=="file"||r.isBinary||!Ht.test(e))continue;const n=String(r.content||"");if(!/selectAppEntityRows(?:<[^>]+>)?\s*\(/.test(n)||!/insertAppEntityRow(?:<[^>]+>)?\s*\(/.test(n))continue;const i=[...[...n.matchAll(/const\s+([A-Za-z_$][\w$]*)\s*=\s*async\s*\([^)]*\)\s*=>\s*{/g)].map(l=>({syncFunctionName:l[1],functionStart:l.index??0,openingBraceOffset:l[0].lastIndexOf("{")})),...[...n.matchAll(/(?:export\s+)?async\s+function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*{/g)].map(l=>({syncFunctionName:l[1],functionStart:l.index??0,openingBraceOffset:l[0].lastIndexOf("{")}))].map(l=>{const c=l.functionStart+l.openingBraceOffset,u=fu(n,c);return u?{functionCandidate:l,functionBlock:u}:null}).filter(Boolean),a=new Set(i.filter(({functionCandidate:l,functionBlock:c})=>{if(!/selectAppEntityRows(?:<[^>]+>)?\s*\(/.test(c.body))return!1;const u=`${e} ${l.syncFunctionName} ${c.body.slice(0,240)}`.replace(/[_./-]+/g," ");return th.test(u)}).map(({functionCandidate:l})=>l.syncFunctionName)),o=new Set(i.filter(({functionBlock:l})=>/insertAppEntityRow(?:<[^>]+>)?\s*\(/.test(l.body)).map(({functionCandidate:l})=>l.syncFunctionName));for(const{functionCandidate:l,functionBlock:c}of i){const u=c.body,d=[...u.matchAll(/const\s+([A-Za-z_$][\w$]*)\s*=\s*await\s*selectAppEntityRows(?:<[^>]+>)?\s*\(/g),...[...u.matchAll(/const\s+([A-Za-z_$][\w$]*)\s*=\s*await\s*([A-Za-z_$][\w$]*)\s*\(/g)].filter(h=>a.has(String(h[2]||"").trim())).map(h=>({0:h[0],1:h[1],index:h.index}))];for(const h of d){const m=h[1],b=u.slice(h.index??0,(h.index??0)+240),g=ote(u,m,[...o]);if(!g)continue;const p=ite(g);if(p.length===0)continue;const y=ste(p),v=`${e} ${l.syncFunctionName} ${b} ${p.join(" ")}`.replace(/[_./-]+/g," ");if(!th.test(v))continue;const _=`${n.slice(Math.max(0,l.functionStart-480),l.functionStart)} 1786${u}`;if(!qee.test(_))return{code:"naive-persisted-catalog-seeding",filePath:e,relatedFilePaths:tn(t,e),syncFunctionName:l.syncFunctionName,defaultSourceName:y,selectedRowsName:m}}}}return null}const qA=[Ste,Ate,xte,_te,ire,nre,sre,ore,are,Ote,jte,$te,Bte,Hte,zte,Gte,qte,Kte,yte,tre,rre,vte,Ite,Qte,Yte,Xte,Jte,wte,Dte,Lte,Mte,Ete,kte,Pte,Rte,Tte,Nte,Zte,cre,lre,ere,ure];function Ic(t,e=qA.length){const r=[],n=new Set;for(const s of qA){const i=s(t);if(!i||BZ.has(i.code))continue;const a=[i.code,i.filePath,[...i.relatedFilePaths].sort().join("|")].join("::");if(!n.has(a)&&(n.add(a),r.push(i),r.length>=e))break}return r}function dre(t){return Ic(t,1)[0]??null}const KA={"@react-three/drei":"9.121.4","@react-three/fiber":"8.17.14","lucide-react":"^0.344.0",react:"^18.3.1","react-dom":"^18.3.1","react-router-dom":"^6.30.1",three:"0.159.0"},Ky={"@eslint/js":"^9.9.1","@types/react":"^18.3.5","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",autoprefixer:"^10.4.18",eslint:"^9.9.1","eslint-plugin-react-hooks":"^5.1.0-rc.0","eslint-plugin-react-refresh":"^0.4.11",globals:"^15.9.0",postcss:"^8.4.35",tailwindcss:"^3.4.1",typescript:"^5.5.3","typescript-eslint":"^8.3.0",vite:"^5.4.2",wrangler:"latest"},Yy={"@react-three/cannon":"^6.6.0",recharts:"^2.10.4"},hre={"@react-three/cannon":["@react-three/fiber","three"],"@react-three/drei":["@react-three/fiber","three"],"@react-three/fiber"
1786:["three"]},fre=[/^@types\//,/^eslint(?:$|-)/,/^@eslint\//,/^typescript-eslint$/,/^@typescript-eslint\//,/^vite(?:$|[-/])/,/^@vitejs\//,/^tailwindcss$/,/^postcss$/,/^autoprefixer$/,/^globals$/,/^wrangler$/],pre=/(?:^|\/)(?:eslint\.config\.[cm]?[jt]s|vite\.config\.[cm]?[jt]s|tailwind\.config\.[cm]?[jt]s|postcss\.config\.[cm]?[jt]s|wrangler\.toml)$/i;function YA(t){return Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)))}function mre(t){return t in Yy?{packageName:t,version:Yy[t],dependencyBucket:"dependencies"}:t in KA?{packageName:t,version:KA[t],dependencyBucket:"dependencies"}:t in Ky?{packageName:t,version:Ky[t],dependencyBucket:"devDependencies"}:null}function gre(t){const e=new Set(t),r=[...t];for(;r.length>0;){const n=r.shift();if(n)for(const s of hre[n]||[])e.has(s)||(e.add(s),r.push(s))}return[...e].sort((n,s)=>n.localeCompare(s))}function bre(t,e=[]){return t in Yy?!1:t in Ky||fre.some(r=>r.test(t))?!0:e.length>0&&e.every(r=>pre.test(r))}function vre(t,e){let r;try{r=JSON.parse(t)}catch{return null}const n={...r.dependencies||{}},s={...r.devDependencies||{}},i=[],a=gre([...new Set(e.map(o=>o.packageName))]);for(const o of a){const l=mre(o);if(!l)continue;const c=e.filter(m=>m.packageName===o).map(m=>m.filePath),u=l.dependencyBucket==="devDependencies"||bre(o,c)?"devDependencies":"dependencies",d=u==="devDependencies"?s:n,h=u==="devDependencies"?n:s;d[o]=l.version,delete h[o],i.push(o)}return i.length===0?null:(r.dependencies=YA(n),r.devDependencies=YA(s),{content:`${JSON.stringify(r,null,2)} 1787`,repairedPackageNames:i})}const XA=/<boltAction\b([^>]*)>([\s\S]*?)<\/boltAction>/gi,yre=/\btype=["']file["']/i,_re=/\bfilePath=["']([^"']+)["']/i;function JA(t,e){const r=t.annotations;return Array.isArray(r)?r.some(n=>typeof n=="string"&&n===e):!1}function xre(t){return String(t||"").replace(/^\s*\[Model:[^\]]+\]\s*/i,"").replace(/^\s*\[Provider:[^\]]+\]\s*/i,"").trim()}function wre(t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>{if(!n||typeof n!="object"||!("type"in n)||n.type!=="text")return"";const s=n.text;return typeof s=="string"?s:""}).join(" ").trim();const r=t.parts;return Array.isArray(r)?r.map(n=>{if(!n||typeof n!="object"||!("type"in n)||n.type!=="text")return"";const s=n.text;return typeof s=="string"?s:""}).join(" ").trim():""}function Sre(t){return xre(t).replace(/\s+/g," ").trim()}function kl(t){let e="";for(let r=t.length-1;r>=0;r--){const n=t[r];if(n.role!=="user")continue;const s=Sre(wre(n));if(!(!s||JA(n,"hidden")||JA(n,"no-store"))){if(!E0(s))return s;e||(e=s)}}return e}function Cre(t){const e=new Set;XA.lastIndex=0;let r;for(;(r=XA.exec(t||""))!==null;){const n=String(r[1]||"");if(!yre.test(n))continue;const s=n.match(_re),i=fn(String(s?.[1]||""));i&&e.add(i)}return[...e]}function Are(t){return PD(fn(t))}function Ere(t){const e=Cre(t),r=e.filter(n=>!Are(n));return{filePaths:e,writablePaths:r,protectedOnly:e.length>0&&r.length===0}}const kre=/^(?:node_modules\/lucide-react|lucide-icons)$/i;function Pre(t){const e=String(t||"").trim().split(/[?#]/)[0];return kre.test(e||"")}const Tre=/\.(?:[cm]?[jt]sx?)$/i,Rre=/\.d\.(?:[cm]?ts)$/i,Ire=/\.(?:[cm]?ts|tsx)$/i,Nre=/\.(?:jsx|tsx)$/i,Lre=["node_modules/",".git/",".vite/","build/","dist/","coverage/"];function Xy(t,e){return["decorators-legacy","importAttributes",...Ire.test(t)?["typescript"]:[],...e?["jsx"]:[]]}function QA(t){return t.replace(/\r\n/g,` 1788`).trimEnd()}function Dre(t){if(!t.trim())return!1;try{const e=JSON.parse(t),r={...e.dependencies||{},...e.devDependencies||{}},n=Object.values(e.scripts||{}).filter(s=>typeof s=="string");return"esbuild"in r||"vite"in r||n.some(s=>/(^|\s)vite(?:\s|$)/.test(s))}catch{return/["'](?:esbuild|vite)["']\s*:/.test(t)}}function ZA(t){const e=new Set;for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||typeof n.content!="string")continue;const s=fn(r);!s||!Tre.test(s)||Rre.test(s)||Lre.some(i=>s.startsWith(i))||e.add(s)}return[...e].sort((r,n)=>{const s=r.startsWith("src/")||r.startsWith("app/")?0:1,i=n.startsWith("src/")||n.startsWith("app/")?0:1;return s-i||r.localeCompare(n)})}async function Mre(t,e){const{parse:r}=await H(async()=>{const{parse:s}=await import("./workbench-DVZ8UPcc.js").then(i=>i.i);return{parse:s}},__vite__mapDeps([24,3,8,5,11,9,10,25,7,12,13,14,15,16,17,18,26,6,22,23,27,28,29,30,31,32,33])),n=[];for(const s of e){const i=Kt(t,s);if(!i.trim())continue;const a=Xy(s,Nre.test(s));
1788try{r(i,{sourceType:"unambiguous",allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0,plugins:a})}catch(o){const l=o,c=Math.max(1,l.loc?.line||1),u=Math.max(1,(l.loc?.column||0)+1),d=i.split(/\r?\n/)[c-1]?.trim().slice(0,500)||"";n.push({filePath:s,line:c,column:u,message:l.message||l.reasonCode||"Invalid JavaScript or TypeScript syntax",sourceLine:d})}}return n}async function Ore(t,e){const{parse:r}=await H(async()=>{const{parse:i}=await import("./workbench-DVZ8UPcc.js").then(a=>a.i);return{parse:i}},__vite__mapDeps([24,3,8,5,11,9,10,25,7,12,13,14,15,16,17,18,26,6,22,23,27,28,29,30,31,32,33])),n=[],s=jre(t);for(const i of e){if(!i.match(/\.(ts|js)$/i))continue;const o=Kt(t,i);if(!o.trim()||!/<[A-Za-z][\w$.:-]*(?:\s|\/?>)/.test(o))continue;try{r(o,{sourceType:"unambiguous",allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0,plugins:Xy(i,!1)});continue}catch{}try{r(o,{sourceType:"unambiguous",allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0,plugins:Xy(i,!0)})}catch{continue}const l=i.replace(/\.(ts|js)$/i,(u,d)=>d.toLowerCase()==="ts"?".tsx":".jsx"),c=s.get(l);c!==void 0&&QA(c)!==QA(o)||n.push({sourceFilePath:i,targetFilePath:l,content:o,targetAlreadyExists:c!==void 0})}return n}function jre(t){const e=new Map;for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary||typeof n.content!="string")continue;const s=fn(r);s&&e.set(s,n.content)}return e}function $re(t){return t.map(e=>[`${e.filePath}:${e.line}:${e.column}: ${e.message}`,e.sourceLine].filter(Boolean).join(` 1789`)).join(` 1790 1791`)}const Bre=sm(["ready","needs_clarification","ready_with_defaults"]),Fre=sm(["app","site"]),vL=sm(["READY","NEEDS_CLARIFICATION","INVALID_GIBBERISH"]);Nc({classification:vL,reason:ea().trim(),questions:B1(ea().trim().min(1)).max(3)}).strict();const Ps=ea().optional().transform(t=>typeof t=="string"?t.trim():""),Fa=B1(ea()).optional().transform(t=>Array.from(new Set((t||[]).map(e=>String(e||"").trim()).filter(Boolean)))),Wre=Nc({classification:vL.default("NEEDS_CLARIFICATION"),reason:Ps,status:Bre,understood:Nc({company_name:Ps,location:Ps,business_type:Ps,website_type:Ps,topics:Fa,requested_pages:Fa,target_audience:Ps,tone:Ps,cta:Ps,branding:Ps}),missing_fields:Fa,questions:Fa.transform(t=>t.slice(0,3)),default_plan:Nc({pages:Fa,theme:Ps,tone:Ps,features:Fa}),generation_brief:Nc({site_goal:Ps,audience:Ps,pages:Fa,content_direction:Ps,visual_style:Ps,features:Fa,contact_strategy:Ps,notes:Ps})});Nc({mode:sm(["qualify","finalize"]),prompt:ea().trim().min(1),appId:ea().trim().max(200).optional(),chatId:ea().trim().max(200).optional(),originalPrompt:ea().trim().optional(),answers:ea().trim().optional(),useSmartDefaults:mD().optional(),projectKind:Fre.default("site"),priorQualification:Wre.optional()});function Hre(t){return!t.isNewsletterChat&&t.chatMode==="build"&&t.requestMode==="build"&&!t.isRepairPrompt&&!t.skipPromptQualification}function Ure(t){const{result:e,projectKind:r,rawPrompt:n,defaultsApproved:s=!1}=t,i=r==="site"?"website":"app";return[s?`Build the ${i} now using the approved smart-default brief below.`:`Build the ${i} now using the refined generation brief below.`,"Do not ask more clarification questions. Start generation immediately from this brief.",`Original request reference: ${n.trim()}`,"GENERATION_BRIEF_JSON",JSON.stringify(e.generation_brief,null,2)].join(` 1792 1793`)}function zre(t){return Ure(t)}function Vre(t){const{originalPrompt:e,result:r,projectKind:n="app",answerText:s,usedDefaults:i=!1}=t;if(r){const a=i?`I'm building this ${n} now using smart defaults for the missing details. Here's the plan:`:s&&s.trim()?`I'm building this ${n} now using your request and the details you added. Here's the plan:`:`I'm building this ${n} now. Here's the plan:`,o=n==="site"?"Pages":"Core Screens",l=r.generation_brief.pages.map((h,m)=>`${m+1}. **${h}**`).join(` 1794`),c=r.generation_brief.features.map(h=>`- ${h}`).join(` 1795`),u=[r.generation_brief.visual_style?`- ${r.generation_brief.visual_style}`:"",r.generation_brief.content_direction?`- ${r.generation_brief.content_direction}`:""].filter(Boolean).join(` 1796`),d=[r.generation_brief.audience?`- Audience: ${r.generation_brief.audience}`:"",r.generation_brief.contact_strategy?`- Contact: ${r.generation_brief.contact_strategy}`:"",r.generation_brief.notes?`- Notes: ${r.generation_brief.notes}
1796`:""].filter(Boolean).join(` 1797`);return[a,r.generation_brief.site_goal?`**Goal** 1798 1799- ${r.generation_brief.site_goal}`:"",l?`**${o}** 1800 1801${l}`:"",u?`**Design** 1802 1803${u}`:"",c?`**Key Features** 1804 1805${c}`:"",d?`**Details** 1806 1807${d}`:""].filter(Boolean).join(` 1808 1809`)}return i?`${e.trim()} 1810 1811Using smart defaults to fill in the missing details.`:s&&s.trim()?`${e.trim()} 1812 1813Follow-up details: ${s.trim()}`:e.trim()}function Gre(t){return t.replace(/\s+/g," ").trim().slice(0,500)}function qre(t){return String(t?.error||t?.message||"").trim()||null}async function Kre(t){const e=await t.clone().text().catch(()=>""),r=Gre(e);if(!r)return{payload:null,responseText:""};try{const n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return{payload:n,responseText:r}}catch{}return{payload:null,responseText:r}}function Yre(t,e,r){const n=qre(e);return n||(r&&!r.startsWith("<")?r:`Unable to verify your AI token balance (${t.status} ${t.statusText||"Error"}). Please refresh and try again before creating an app.`)}function Xre(t){const e=t.trim().toLowerCase();return e==="image/jpeg"||e==="image/jpg"?"jpg":e==="image/png"?"png":e==="image/webp"?"webp":e==="image/gif"?"gif":e.startsWith("video/")?e.includes("webm")?"webm":"mp4":e.startsWith("audio/")?e.includes("wav")?"wav":"mp3":"bin"}function Jre(t,e){const r=String(t.mimeType||"").trim().toLowerCase();if(r.startsWith("image/")||r.startsWith("video/")||r.startsWith("audio/"))return r;const n=[t.filename,t.publicUrl,t.url,t.optimizedUrl,t.thumbnailUrl].filter(Boolean).join(" ").toLowerCase(),s=String(e||"").trim();return s==="video"?/\.(?:webm)(?:[?#]|$)/i.test(n)?"video/webm":/\.(?:mov|qt)(?:[?#]|$)/i.test(n)?"video/quicktime":/\.(?:mpeg|mpg)(?:[?#]|$)/i.test(n)?"video/mpeg":"video/mp4":s==="audio"?/\.(?:wav)(?:[?#]|$)/i.test(n)?"audio/wav":/\.(?:ogg|opus)(?:[?#]|$)/i.test(n)?"audio/ogg":/\.(?:m4a|aac)(?:[?#]|$)/i.test(n)?"audio/aac":"audio/mpeg":s==="image"?"image/png":"application/octet-stream"}async function Qre(t,e){const r=t.match(/^data:([^;,]+)?(;base64)?,([\s\S]*)$/);if(!r)return null;const n=r[1]||"application/octet-stream",s=r[3]||"";let i;try{if(r[2]){const o=globalThis.atob(s);i=new Uint8Array(o.length);for(let l=0;l<o.length;l++)i[l]=o.charCodeAt(l)}else i=new TextEncoder().encode(decodeURIComponent(s))}catch{return null}const a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),new File([a],`prompt-asset-${e+1}.${Xre(n)}`,{type:n})}function Zre(t){const e=Array.isArray(t?.annotations)?t.annotations:[];for(let r=e.length-1;r>=0;r--){const n=e[r];if(!(!n||typeof n!="object"||!("type"in n))&&n.type==="usageSummary")return n}return null}function e1(t){return t.map(e=>!e||typeof e!="object"||!("type"in e)?"":e.type==="text"&&"text"in e?String(e.text||""):"").join("")}function t1(t){const e=[];for(const r of t)if(!(!r||typeof r!="object"||!("type"in r))){if(r.type==="text"&&"text"in r){const n=String(r.text||"").trim();n&&e.push(n);continue}if(r.type==="reasoning"){const s=("reasoning"in r?String(r.reasoning||""):"text"in r?String(r.text||""):"").trim();s&&e.push(s);continue}if(r.type==="file"&&"data"in r){const n=String(r.data||"");(n.includes("<<<FILE:")||n.includes("<<<FIND>>>")||n.includes("<<<REPLACE>>>"))&&e.push(n.trim())}}return e.join(` 1814 1815`).trim()}function Nf(t,e){const r=wd(e).trim();if(!r)return;t.some(s=>wd(s).trim()===r)||t.push(e.trim())}function ene(t){const e=[],r=t.content,n=Gi(t),s=typeof t.reasoning=="string"?t.reasoning:"",i=Array.isArray(t.parts)?t1(t.parts):"",a=Array.isArray(r)?t1(r):"";return Nf(e,n),Nf(e,s),Nf(e,a),Nf(e,i),e.join(` 1816 1817`).trim()}const tne=vD({enter:"animated fadeInRight",exit:"animated fadeOutRight"}),Yo="*Auto-repair this project error now.*",Xo="You are repairing the generated project from the full batched diagnostics. You may rewrite generated app files completely when that is the fastest reliable fix, and you should stream complete corrected file contents for every affected file. Do not replace real persistence with mock data, no-op CRUD, or local-only sample data. Preserve published data storage behavior; if preview needs a fallback, keep the same API contract. For repeated content collections such as menus, products, services, locations, galleries, FAQs, destinations, or similar item lists, fix the persisted source of truth and its sync logic, not just the page copy. Fix all aggregated root-cause issues in one pass whenever possible. Preserve standard lucide-react imports when the package is already declared; replace only invalid lucide-icons or node_modules/lucide-react import paths. Do not import Phaser or add a phaser dependency unless the original user request explicitly asked for Phaser; for HTML5 Canvas, Canvas and JavaScript, vanilla JavaScript, plain HTML/CSS/JS, or single HTML file game requests, repair toward plain Canvas/browser APIs instead. Do not require Stripe setup or CloudMySite Forms setup for build success. Keep checkout and forms flows admin-configurable and safe when integrations are not configured yet. Do not rewrite CloudMySite platform template files (src
1817/lib/cloudMySiteForms.ts, src/components/forms/CloudMySiteContactForm.tsx) unless the failure explicitly requires a platform migration. Do not convert generic user-facing forms into CloudMySite-specific forms. Keep generated forms generic unless CloudMySite Forms integration was explicitly requested by the user.",rne=6,nne=2,Jy=9e4,sne=Jy*4,ine=128,Gb=1800,one=12,Zo=8,ane=4e3,ao="Qwen",Jo="qwen3.6-plus",qb=1,r1="workspace-auth-required",lne=1500,n1=2,s1=2,ep=5,rh=8,cne=1600,une=20,dne=400,hne=2500,fne=1500,Lf=1400,i1=12e4,pne=150,mne=1200,gne=350,vi=ld,o1=/<boltAction\b([^>]*)>([\s\S]*?)<\/boltAction>/gi,bne=/\btype=["']file["']/i,vne=/\bfilePath=["']([^"']+)["']/i,a1=/(?:\bexport\s+(?:async\s+)?function\s+createLocalDbApiPlugin\b|\bexport\s+const\s+createLocalDbApiPlugin\b|\bexport\s*\{\s*createLocalDbApiPlugin\b)/,l1=/from\s+['"]\.\/vite\.local-db(?:\.[cm]?[jt]s)?['"]/,c1=/\bcreateLocalDbApiPlugin\s*\(/,yne=/\b(?:auth|authentication|login|logout|log out|sign ?in|sign ?up|signup|protected|guest|anonymous)\b/i,_ne={"/api/check-auth":"/api/auth/me","/api/check-session":"/api/auth/me","/api/me":"/api/auth/me","/api/auth/check-auth":"/api/auth/me","/api/auth/check-session":"/api/auth/me","/api/login":"/api/auth/login","/api/signin":"/api/auth/login","/api/sign-in":"/api/auth/login","/api/signup":"/api/auth/signup","/api/sign-up":"/api/auth/signup","/api/register":"/api/auth/signup","/api/logout":"/api/auth/logout","/api/signout":"/api/auth/logout","/api/sign-out":"/api/auth/logout"},xne=new Set(["/","/*","/login","/signin","/sign-in","/signup","/sign-up","/register"]),tp="src/components/icons/AppIcons.tsx",Yu=new Set(["persisted-local-db-duplicate-rows","protected-runtime-syntax-corruption","invalid-protected-app-schema-import","protected-runtime-export-contract"]),wne=new Set(["missing-local-import","missing-package-dependency","browser-commonjs-require","phaser-runtime-api-misuse","missing-three-symbol-import","missing-react-three-fiber-symbol-import","react-three-dom-element-in-canvas","duplicate-import-declaration","missing-react-three-physics-provider","missing-text-geometry-extension","missing-local-db-api-plugin","missing-vite-react-plugin","invalid-local-api-endpoint","direct-auth-screen-mount","invalid-protected-app-schema-import","protected-runtime-export-contract"]),Sne=20,Cne=40,u1=1200,Ane=5,d1=10,N0=12,Ene=12e3,kne=/\.(?:[cm]?[jt]sx?|css|scss|sass|html|json|mjs|cjs)$/i,Pne=["package.json","index.html","main.js","main.jsx","main.ts","main.tsx","game.js","style.css","src/main.js","src/main.jsx","src/main.ts","src/main.tsx","src/App.js","src/App.jsx","src/App.ts","src/App.tsx","src/game.js","src/game.ts","src/style.css"],Tne=/(?:^|[^\w.-])((?:src|app|js|vite|public)\/[^?\s):#]+?\.(?:[cm]?[jt]sx?|css|scss|sass|html|json|mjs|cjs))(?:\?[^:\s)]*)?(?::(\d+)(?::(\d+))?)?/g,Rne=/(?:^|[^\w/.-])([A-Za-z_$][\w$.-]*\.(?:[cm]?[jt]sx?|css|scss|sass|html|json|mjs|cjs))(?::(\d+)(?::(\d+))?)?/g;function Ine(t){const e=new Map;for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary)continue;const s=fn(r);!s||!kne.test(s)||e.set(s,String(n.content||""))}return e}function Nne(t,e){const r=String(t||"").replace(/\\/g,"/").replace(/^\/home\/project\//,"").replace(/^home\/project\//,"").replace(/^\.\//,"").replace(/^\/+/,"").split(/[?#]/)[0],n=r.match(/(?:^|\/)((?:src|app|js|vite|public)\/.+)$/),s=fn(n?.[1]||r);if(s&&e.has(s))return s;const i=r.split("/").pop();if(!i)return"";const a=[...e.keys()].filter(o=>o===i||o.endsWith(`/${i}`));return a.length===1?a[0]:""}function h1(t){const e=Number(t);return Number.isInteger(e)&&e>0?e:null}function Lne(t,e){const r=[],n=new Set,s=(i,a,o)=>{const l=Nne(i,e);if(!l)return;const c=h1(a),u=h1(o),d=`${l}:${c||0}:${u||0}`;n.has(d)||(n.add(d),r.push({filePath:l,lineNumber:c,columnNumber:u}))};for(const i of t){const a=[i.title,i.description,i.content].filter(
1817Boolean).join(` 1818`);for(const o of a.matchAll(new RegExp(Tne)))s(String(o[1]||""),o[2],o[3]);for(const o of a.matchAll(new RegExp(Rne)))s(String(o[1]||""),o[2],o[3])}return r.slice(0,N0)}function Dne(t,e){if(e.length===0)return[];const r=Ine(t),n=Lne(e,r),s=[],i=new Set,a=l=>{if(s.length>=N0||i.has(l.filePath))return;const c=r.get(l.filePath);if(!c)return;const u=c.replace(/\r\n/g,` 1819`).split(` 1820`),d=l.lineNumber&&l.lineNumber<=u.length?l.lineNumber:Math.min(u.length,1),h=l.lineNumber?Math.max(1,d-d1):1,m=l.lineNumber?Math.min(u.length,d+d1):u.length,b=u.slice(h-1,m).map((g,p)=>`${String(h+p).padStart(4," ")} | ${g}`).join(` 1821`).slice(0,Ene);s.push({filePath:l.filePath,lineNumber:l.lineNumber,columnNumber:l.columnNumber,startLine:h,endLine:m,content:b}),i.add(l.filePath)};for(const l of n)a(l);const o=[...Pne,...[...r.keys()].filter(l=>/^(?:src\/)?(?:game|app|main|index|canvas|script|style)\.(?:[cm]?[jt]sx?|css|html)$/i.test(l))];for(const l of o)a({filePath:l,lineNumber:null,columnNumber:null});return s}function Mne(t,e,r=[]){const n=t.map(a=>a.key),s=e.map(a=>Sd(a)),i=r.map(a=>`${a.code}:${a.sourceFile}:${a.importSource}:${a.missingExportNames.join(",")}`);return`batched-auto-repair::${Tt([...s,...i,...n].join("||")).slice(0,900)}`}function One(t,e,r=[]){const n=t.length,s=e.length,i=r.length;return`${n} runtime build error(s), ${s} validation issue(s), and ${i} import issue(s) queued for batched ${ao} repair`}function Kb(t){return t.slice(0,5).map(e=>({source:e.source,title:e.title,description:e.description.slice(0,300),contentPreview:e.content.slice(0,600),key:e.key.slice(0,180)}))}function yL(t){if(t.source!=="preview")return!1;const e=`${t.title} 1822${t.description} 1823${t.content}`.toLowerCase();return/turnstileerror|cloudflare turnstile|challenges\.cloudflare\.com\/turnstile|error:\s*110200/.test(e)?!0:/\b(?:uncaught|referenceerror|typeerror|syntaxerror|rangeerror|failed to resolve import|does not provide an export|module not found|cannot read properties|is not defined|vite\s+error|rollup|esbuild)\b/.test(e)?!1:/preview startup failed|preview failed to load|preview command finished without a ready preview|no ready preview|did not become ready|finished without a ready preview|serviceworker intercepted|credentialless|cors header|opaque browser response|preview root probe timed out|exit code 130|exit code 143|responsive-check-failed|ready-preview-timeout/.test(e)}function jne(t){if(t.source!=="preview"&&t.source!=="terminal")return!1;const e=`${t.title} 1824${t.description} 1825${t.content}`.toLowerCase();return/dependency setup command\b[\s\S]*\btimed out\b/.test(e)||/\bnpm install\b[\s\S]*\btimed out\b/.test(e)||/\bdepen
1825dencies unavailable\b/.test(e)||/\bjsh:\s*command not found:\s*(?:vite|next|astro|react-scripts|webpack|parcel|nuxt|expo)\b/.test(e)||/\b(?:vite|next|astro|react-scripts|webpack|parcel|nuxt|expo):\s*not found\b/.test(e)||/\bpreview startup failed\b/.test(e)&&/\bexit code 127\b/.test(e)&&/\bcommand not found\b/.test(e)}function $ne(t){if(t.source!=="preview")return!1;const e=`${t.title} 1826${t.description} 1827${t.content}`.toLowerCase();return yL({...t,source:"preview"})?!1:e.includes("/src/")||e.includes("/app/")||e.includes("/main.")||e.includes("[plugin:vite")||e.includes("vite:import-analysis")||e.includes("failed to resolve import")||e.includes("failed to load module script")||e.includes("does not provide an export")||e.includes("module not found")||e.includes("uncaught")||e.includes("referenceerror")||e.includes("typeerror")||e.includes("syntaxerror")}function pu(t,e=0){if(t==null)return t;if(typeof t=="string")return t.length>u1?`${t.slice(0,u1)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.slice(0,Sne).map(n=>pu(n,e+1));if(typeof t!="object")return String(t);if(e>=Ane)return"[truncated]";const r=Object.entries(t).slice(0,Cne).map(([n,s])=>[n,pu(s,e+1)]).filter(([,n])=>n!==void 0);return Object.fromEntries(r)}function _L(t){const e=pu(t);return e&&typeof e=="object"&&!Array.isArray(e)?{summary:nh(t),...e}:{summary:nh(t),issue:e}}function xL(t){const e=pu(t);return e&&typeof e=="object"&&!Array.isArray(e)?{summary:t.message,importerFile:t.sourceFile,...e}:{summary:t.message,importerFile:t.sourceFile,issue:e}}function Bne(t){const e=t.originalRequest.trim().slice(0,6e3),r=t.runtimeAlerts.slice(0,one),n=t.validationIssues.slice(0,Zo),s=(t.importIssues||[]).slice(0,Zo*2),i=(t.runtimeSourceSnippets||[]).slice(0,N0),a=n.map(b=>_L(b)),o=s.map(b=>xL(b)),l=(t.importGraphReport?.missingDependencies||[]).slice(0,Zo*2).map(b=>pu(b)),c=a.length?`\`\`\`json 1828${JSON.stringify(a,null,2)} 1829\`\`\``:"No additional workspace validation issues were detected.",u=o.length?`\`\`\`json 1830${JSON.stringify(o,null,2)} 1831\`\`\``:"No additional dependency-graph import issues were detected.",d=l.length?`\`\`\`json 1832${JSON.stringify(l,null,2)} 1833\`\`\``:"No missing local dependency edges were detected.",h=r.length?r.map((b,g)=>{const p=(b.content||b.description||b.title||"Unknown build error").trim().slice(0,ane);return[`${g+1}. [${b.source}] ${b.title||"Preview Build Failed"}`,b.description?`Summary: ${b.description}`:"","```text",p,"```"].filter(Boolean).join(` 1834`)}).join(` 1835 1836`):"No additional terminal or preview errors were captured.",m=i.length?i.map((b,g)=>{const p=b.lineNumber?`:${b.lineNumber}${b.columnNumber?`:${b.columnNumber}`:""}`:`:${b.startLine}-${b.endLine}`;return[`${g+1}. ${b.filePath}${p}`,"```text",b.content,"```"].join(` 1837`)}).join(` 1838 1839`):"No matching source snippets could be extracted from the runtime stack. Use the stack paths and current workspace files.";return`${Yo} 1840${Xo} 1841Use ${ao} (${Jo}) to repair the CURRENT project in place. 1842Use the full diagnostic payload below as context, then inspect the current workspace and choose the repair strategy that resolves the root cause. 1843Address the complete failure state in one response rather than one file at a time. 1844Emit real <boltAction type="file"> updates with the complete corrected contents for every affected file in this same response so the app can compile cleanly immediately. 1845Do not use find/replace patch blocks for this repair pass. 1846 1847Current user goal: 1848\`\`\`text 1849${e||"Repair the current generated project so the preview loads without build errors."} 1850\`\`\` 1851 1852Current workspace validation issues: 1853${c} 1854 1855Current dependency-graph import issues: 1856${u} 1857 1858Missing dependency graph: 1859${d} 1860 1861Current terminal and preview errors: 1862${h} 1863 1864Source context extracted from runtime stack traces: 1865${m} 1866 1867Requirements: 1868- use the listed errors as diagnostic evidence, not as a command to only edit the first mentioned file 1869- fix the root cause even when it is in a different generated file than the first reported stack/build location 1870- for runtime exceptions, inspect the source context above and fix the root cause in code, not just the symptom or a surrounding try/catch 1871- if multiple files have JSX, import, routing, or build errors, fix all of them in the SAME response
1872- do not stop after repairing the first file 1873- do not leave unresolved imports 1874- for every import in emitted code, either create the target file in this repair cycle or remove the import 1875- do not reference pages/components/hooks/utils/assets/routes that are not included in the response 1876- stream full file contents for every changed or created file 1877- do not rewrite protected generated infrastructure files unless preserving their existing contract is absolutely required 1878- for \`src/lib/appSchema.ts\`, \`src/lib/appData.ts\`, and \`src/lib/cloudflareCrud.ts\`, prefer fixing app-side imports/usages and app-specific schema files instead of rewriting protected helpers 1879- preserve standard \`lucide-react\` imports when the package is declared; replace only invalid \`lucide-icons\` or \`node_modules/lucide-react\` import paths 1880- in JSX/TSX text nodes, never leave raw angle-bracket characters; use words, HTML entities, or JSX expressions instead 1881- keep Stripe and CloudMySite Forms optional until the user enables them from Admin 1882- return a self-contained, buildable project delta 1883- finish only when the project should compile and preview should load without the currently listed errors`}function Yb(t){return Pre(t)}function L0(t,e){const r=fn(t)||t,n=fn(e)||e,s=ta.dirname(r||".")||".",i=ta.relative(s,n).replace(/\\/g,"/");return i?i.startsWith(".")?i:`./${i}`:"./AppIcons"}function Fne(t){const e=new Set;for(const r of t.matchAll(/\bexport\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s+(?:const|let|var|class|interface|type|enum)\s+([A-Za-z_$][\w$]*)\b/g)){const n=String(r[1]||"").trim();n&&e.add(n)}for(const r of t.matchAll(/\bexport\s*\{\s*([^}]+)\s*\}/g)){const n=String(r[1]||"").split(",").map(s=>s.trim()).filter(Boolean);for(const s of n){const i=s.match(/^([A-Za-z_$][\w$]*|default)\s+as\s+([A-Za-z_$][\w$]*|default)$/);if(i){i[2]!=="default"&&e.add(i[2]);continue}s!=="default"&&e.add(s)}}return{hasDefaultExport:/\bexport\s+default\b/.test(t)||/\bexport\s*\{[^}]*\bdefault\b[^}]*\}/.test(t),namedExports:e}}function Wne(t){return Tt(t.map(e=>[e.code,e.sourceFile,e.importSource,e.resolvedPath||"",e.missingExportNames.join(",")].join(":")).join("||")).slice(0,1200)}function Hne(t,e,r){const n=new RegExp(`(^|\\n)([ \\t]*import\\s+)([\\s\\S]*?)(\\s+from\\s+)(['"])${mu(e.importSource)}\\5(\\s*;?)`,"m");if(e.code==="import-path-mismatch"&&e.resolvedPath){const d=L0(e.sourceFile,e.resolvedPath);let h=!1;const m=t.replace(n,(b,g,p,y,v,_,w)=>d===e.importSource?b:(h=!0,`${g}${p}${y}${v}${_}${d}${_}${w}`));return h?{content:m,kind:"import-path-mismatch"}:null}if(e.code!=="missing-export"||e.isDynamic||e.importedBindings.length!==1||e.missingExportNames.length!==1)return null;const s=e.importedBindings[0],i=e.missingExportNames[0],a=Fne(r);let o=null,l=null;if(s.kind==="default"&&i==="default"){if(a.namedExports.has(s.localName))o=`{ ${s.localName} }`,l="default-to-named-export";else if(a.namedExports.size===1){const[d]=[...a.namedExports];o=d===s.localName?`{ ${d} }`:`{ ${d} as ${s.localName} }`,l="default-to-named-export"}}else s.kind==="named"&&i===s.importedName&&a.hasDefaultExport&&(o=s.localName,l="named-to-default-export");if(!o||!l)return null;let c=!1;const u=t.replace(n,(d,h,m,b,g,p,y)=>(c=!0,`${h}${m}${o}${g}${p}${e.importSource}${p}${y}`));return c?{content:u,kind:l}:null}function Une(t){return JSON.stringify(String(t||"").trim())}function zne(t){const e=Kt(t,"app.config.json")||Kt(t,"public/app.config.json");if(!e)return"generated_app";try{const r=JSON.parse(e),n=String(r?.app?.slug||"").trim();if(n)return n;const s=String(r?.app?.name||"").trim();if(s)return s.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}catch{}return"generated_app"}function Vne(t,e){const r=t.indexOf("(",e);if(r===-1)return"";let n=0,s=-1,i=0,a=null,o=!1;for(let l=r;l<t.length;l+=1){const c=t[l];if(a){o?o=!1:c==="\\"?o=!0:c===a&&(a=null);continue}if(c==='"'||c==="'"||c==="`"){a=c;continue}if(c==="("){n+=1;continue}if(c===")"){if(n-=1,n<=0)return"";continue}if(n===1){if(c==="{"){s===-1&&(s=l),i+=1;continue}if(c==="}"&&s!==-1&&(i-=1,i===0))return t.slice(s+1,l)}}return""}function Gne(t){const e=t.trim();return/^(?:true|false)\b/.test(e)?"boolean":/^-?\d+\.\d+\b/.test(e)?"real":/^-?\d+\b/.test(e)?"integer":/^[\[{]/.test(e)?"json":"text"}function qne(t){const e=[],r=new Set,n=/(?:^|[,{]\s*)(?:['"]([^'"]+)['"]|([A-Za-z_$][\w$]*))\s*:\s*([^,\n}]+)/g;for(const s of t.matchAll(n)){const i=String(s[1]||s[2]||"").trim();!i||r.has(i)||i==="id"||(r.add(i),e.push({name:i,type:Gne(String(s[3]||""))}))}return e}function Kne(t,e=["appSchema"]){const r=new Map,n=e.map(i=>i.trim()).filter(i=>/^[A-Za-z_$][\w$]*$/.test(i)).map(mu).join("|")||"appSchema",s=i=>{const a=String(i||"").trim();if(!a)return null;const o=r.get(a);if(o)return o;const l=new Map;return r.set(a,l),l};for(const[i,a]of Object.entries(t||{})){if(!a||a.type!=="file"||a.isBinary||typeof a.content!="string")continue;const o=fn(i);if(!o||!o.startsWith("src/")||/^src\/lib\/(?:appData|appSchema|cloudflareCrud)\.[cm]?[jt]sx?$/i.test(o))continue;const l=a.content,c=new RegExp(`\\b(?:selectAppEntityRows|insertAppEntityRow|updateAppEntityRow|deleteAppEntityRow)(?:<[^>]*>)?\\s*\\(\\s*(?:${n})\\s*,\\s*['"]([^'"]+)['"]`,"g");for(const h of l.matchAll(c))s(String(h[1]||""));const u=new RegExp(`\\binsertAppEntityRow(?:<[^>]*>)?\\s*\\(\\s*(?:${n})\\s*,\\s*['"]([^'"]+)['"]`,"g");for(const h of l.matchAll(u)){const m=s(String(h[1]||""));if(!m||h.index===void 0)continue;const b=Vne(l,h.index);for(const g of qne(b))m.has(g.name)||m.set(g.name,g)}const d=/interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g;for(const h of l.matchAll(d)){const m=String(h[1]||"").trim(),b=[...r.keys()].find(p=>{const y=p.replace(/s$/i,"");return new RegExp(`^${mu(y)}s?$`,"i").test(m)});if(!b)continue;const g=s(b);if(g)for(const p of String(h[2]||"").matchAll(/^\s*([A-Za-z_$][\w$]*)\??\s*:\s*([^\n]+)/gm)){const y=String(p[1]||"").trim(),v=String(p[2]||"").trim();!y||y==="id"||g.has(y)||g.set(y,{name:y,type:/\bnumber\b/.test(v)?"integer":/\bboolean\b/.test(v)?"boolean":"text"})}}}return r.size===0&&r.set("items",new Map([["name",{name:"name",type:"text"}]])),[...r.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>({entityName:i,fields:a.size>0?[...a.values()].sort((o,l)=>o.name.localeCompare(l.name)):[{name:"name",type:"text"}]}))}
1883function Yne(t,e){const r=zne(t),n=[...new Set([...e.invalidIdentifiers,"appSchema"])].map(l=>l.trim()).filter(l=>/^[A-Za-z_$][\w$]*$/.test(l)),s=n.includes("appSchema")?"appSchema":n[0]||"appSchema",a=Kne(t,n).map(({entityName:l,fields:c})=>{const u=c.map(d=>` ${JSON.stringify(d.name)}: ${JSON.stringify(d.type)},`).join(` 1884`);return` ${JSON.stringify(l)}: { 1885 fields: { 1886${u} 1887 }, 1888 },`}).join(` 1889`),o=n.filter(l=>l!==s).map(l=>`export const ${l} = ${s};`).join(` 1890`);return`import { defineAppSchema } from './lib/appSchema'; 1891export { defineAppSchema } from './lib/appSchema'; 1892export type { 1893 AppDatabaseSchema, 1894 AppEntityFieldInput, 1895 AppEntityInput, 1896 DefineAppSchemaInput, 1897} from './lib/appSchema'; 1898 1899export const ${s} = defineAppSchema({ 1900 app: ${Une(r)}, 1901 entities: { 1902${a} 1903 }, 1904}); 1905${o?` 1906${o} 1907`:""}`}const Xne="src/lib/appSchema.ts",wL=/((?:import|export)\s+(?:type\s+)?(?:\{[\s\S]*?\}|[A-Za-z_$][\w$]*(?:\s*,\s*(?:type\s+)?\{[\s\S]*?\})?|\*\s+as\s+[A-Za-z_$][\w$]*)\s+from\s+)(['"])([^'"\n]*appSchema(?:\.[cm]?[jt]sx?)?)(\2)/g;function Jne(t,e){const r=String(e||"").trim().split(/[?#]/)[0]||"";if(!/^\.\.?(?:\/|$)/.test(r))return[];const n=ta.dirname(fn(t)||t),s=fn(ta.join(n,r))||"",i=/\.[A-Za-z0-9]+$/.test(r),a=[".tsx",".ts",".jsx",".js",".mjs",".cjs"];return i?[s]:[...a.map(o=>`${s}${o}`),...a.map(o=>`${s}/index${o}`)]}function SL(t,e){const r=String(e||"").trim().split(/[?#]/)[0]||"";if(!r)return!1;if(Jne(t,r).some(s=>fn(s)===Xne))return!0;const n=fn(r.replace(/^~\//,"src/"))||"";return/^src\/lib\/appSchema(?:\.[cm]?[jt]sx?)?$/i.test(n)}function Qne(t,e){for(const r of t.matchAll(new RegExp(wL))){const n=String(r[3]||"").trim();if(SL(e,n))return!0}return!1}function Zne(t,e){const r=L0(e,"src/appSchema.ts").replace(/\.[cm]?[jt]sx?$/i,"");let n=0;const s=t.replace(wL,(i,a,o,l,c)=>SL(e,String(l||""))?(n+=1,`${a}${o}${r}${c}`):i);return n>0?{content:s,replacementCount:n}:null}function ese(t,e){const r=[],n=hn(t,"src/appSchema.ts")||"src/appSchema.ts",s=Yne(t,e);Kt(t,n)!==s&&r.push({filePath:n,content:s});const a=[],o=new Set(e.relatedFilePaths);for(const[l,c]of Object.entries(t||{})){if(!c||c.type!=="file"||c.isBinary||typeof c.content!="string")continue;const u=fn(l);!u||!u.startsWith("src/")||/^src\/lib\/(?:appData|appSchema|cloudflareCrud)\.[cm]?[jt]sx?$/i.test(u)||(o.has(u)||Qne(c.content,u))&&o.add(u)}for(const l of[...o].sort((c,u)=>c.localeCompare(u))){const c=hn(t,l)||l,u=Kt(t,c),d=Zne(u,l);!d||d.content===u||(r.push({filePath:c,content:d.content}),a.push(c))}return r.length>0?{writes:r,rewrittenFiles:a,schemaPath:n}:null}function f1(t){return String(t||"").split(",").map(e=>e.trim()).filter(Boolean).filter(e=>!/^type\b/i.test(e)).map(e=>e.split(/\s+as\s+/i)[0]?.trim()||"").filter(e=>/^[A-Z][A-Za-z0-9_$]*$/.test(e))}function tse(t,e){const r=new Set,n=new RegExp(`\\b${mu(e)}\\.([A-Z][A-Za-z0-9_$]*)\\b`,"g");for(const s of t.matchAll(n)){const i=String(s[1]||"").trim();i&&r.add(i)}return r}function CL(t){const e=[...new Set(t.filter(i=>/^[A-Z][A-Za-z0-9_$]*$/.test(i)))].sort((i,a)=>i.localeCompare(a)),r=e.length>0?e:["Circle"],n=r.map(i=>`export const ${i} = createIcon('${i}');`).join(` 1908`),s=r.map(i=>` ${i},`).join(` 1909`);return`import type { ReactElement, ReactNode, SVGProps } from 'react'; 1910 1911export interface IconProps extends SVGProps<SVGSVGElement> { 1912 size?: number | string; 1913 absoluteStrokeWidth?: boolean; 1914 title?: string; 1915} 1916 1917export type LucideProps = IconProps; 1918export type IconNode = ReactNode; 1919export type LucideIcon = (props: IconProps) => ReactElement; 1920 1921const DEFAULT_SIZE = 20; 1922const DEFAULT_STROKE_WIDTH = 1.75; 1923 1924function GenericGlyph() { 1925 return ( 1926 <> 1927 <circle cx="12" cy="12" r="8.5" /> 1928 <path d="M9.5 12.5 11 14l3.5-4" /> 1929 </> 1930 ); 1931} 1932 1933function BaseIcon({ 1934 size = DEFAULT_SIZE, 1935 strokeWidth = DEFAULT_STROKE_WIDTH, 1936 absoluteStrokeWidth, 1937 color = 'currentColor', 1938 title, 1939 children, 1940 ...props 1941}: IconProps & { children?: ReactNode }) { 1942 const resolvedStrokeWidth = 1943 absoluteStrokeWidth && typeof size === 'number' ? (Number(strokeWidth) * 24) / size : strokeWidth; 1944 1945 return ( 1946 <svg 1947 width={size} 1948 height={size}
1949 viewBox="0 0 24 24" 1950 fill="none" 1951 xmlns="http://www.w3.org/2000/svg" 1952 stroke={color} 1953 strokeWidth={resolvedStrokeWidth} 1954 strokeLinecap="round" 1955 strokeLinejoin="round" 1956 aria-hidden={title ? undefined : true} 1957 role={title ? 'img' : 'presentation'} 1958 {...props} 1959 > 1960 {title ? <title>{title}</title> : null} 1961 {children || <GenericGlyph />} 1962 </svg> 1963 ); 1964} 1965 1966function createIcon(iconName: string): LucideIcon { 1967 return function GeneratedIcon(props: IconProps) { 1968 return <BaseIcon title={props.title || iconName} {...props} />; 1969 }; 1970} 1971 1972${n} 1973 1974const iconMap = { 1975${s} 1976}; 1977 1978export default iconMap; 1979`}function rse(t){const e=new Set;for(const r of t.matchAll(/\bexport\s+const\s+([A-Z][A-Za-z0-9_$]*)\s*=\s*createIcon\(/g)){const n=String(r[1]||"").trim();n&&e.add(n)}return[...e]}function nse(t,e){const r=rse(t),n=[...new Set([...r,...e])].filter(i=>/^[A-Z][A-Za-z0-9_$]*$/.test(i)).sort((i,a)=>i.localeCompare(a)),s=n.filter(i=>!r.includes(i));return s.length===0?null:{content:CL(n),addedIconNames:s}}function sse(t){const e=[],r=[],n=new Set(["Circle"]);for(const[i,a]of Object.entries(t||{})){if(!a||a.type!=="file"||a.isBinary||typeof a.content!="string")continue;const o=fn(i);if(!o||!/\.(?:[cm]?[jt]sx?)$/i.test(o))continue;let l=a.content,c=!1;const u=L0(o,tp),d=new Set;l=l.replace(/import\s+([\s\S]*?)\s+from\s+['"]((?:node_modules\/)?lucide-react|lucide-icons)['"]\s*;?/g,(h,m,b)=>{if(!Yb(b))return h;c=!0,r.push({filePath:o,importSource:b});const g=String(m||"").trim(),p=g.match(/\{([\s\S]*?)\}/);if(p&&!/^type\b/i.test(g))for(const v of f1(p[1]||""))n.add(v);const y=g.match(/\*\s+as\s+([A-Za-z_$][\w$]*)/);return y?.[1]&&d.add(y[1]),`import ${g} from '${u}';`}),l=l.replace(/export\s+\{([\s\S]*?)\}\s+from\s+['"]((?:node_modules\/)?lucide-react|lucide-icons)['"]\s*;?/g,(h,m,b)=>{if(!Yb(b))return h;c=!0,r.push({filePath:o,importSource:b});for(const g of f1(m||""))n.add(g);return`export {${m}} from '${u}';`}),l=l.replace(/\bimport\s*\(\s*['"]((?:node_modules\/)?lucide-react|lucide-icons)['"]\s*\)/g,(h,m)=>Yb(m)?(c=!0,r.push({filePath:o,importSource:m}),`import('${u}')`):h);for(const h of d)for(const m of tse(l,h))n.add(m);c&&l!==a.content&&e.push({filePath:o,content:l})}if(r.length===0&&e.length===0)return null;if(r.length>0){const i=CL([...n]),a=hn(t,tp);(a?Kt(t,a):"")!==i&&e.push({filePath:a||tp,content:i,create:!a})}const s=new Map;for(const i of e)s.set(fn(i.filePath)||i.filePath,i);return{detectedImports:r,iconNames:[...n].sort((i,a)=>i.localeCompare(a)),rewrites:[...s.values()]}}const ise="package-lock.json";function p1(){return eM(tv())}function Ch(t){return String(t||"").replace(/\u001b\[[0-9;]*[A-Za-z]/g,"")}function da(t){return Ch(t).replace(/\r/g,"").replace(/\u0000/g,"").replace(/\s+/g," ").trim()}function AL(t){return/\[builder\]\s+.+\s+timed out after \d+ms and was terminated\.?$/i.test(da(t))}function $l(t){return t.timedOut?!0:t.exitCode===124&&Ch(t.output).split(/\n/).some(AL)}function ose(t){return fn(String(t||"").trim())||String(t||"").trim()||null}function EL(t){const e=da(t).toLowerCase();return e?e==="failed to load"||AL(t)||e.includes("serviceworker intercepted the request")||e.includes("loading failed for the module with source")||e.includes("[vite] connecting")||e.includes("[vite] connected"):!0}function ase(t){const e=String(t||"").trim();return e?/^.+\(\d+,\d+\): error [A-Z0-9]+:/i.test(e)||/^\[plugin:[^\]]+\]\s+.+:\s+.+\(\d+:\d+\)$/i.test(e)||/^.+\.(?:[cm]?[jt]sx?|vue|astro|svelte|css|scss|sass|less|html):\d+:\d+:/i.test(e)||/(failed to resolve import|cannot find module|could not resolve)\s+["'][^"']+["']/i.test(e):!1}function Df(t,e){const r=[];for(let n=e+1;n<t.length&&r.length<rh;n+=1){const i=String(t[n]||"").trimEnd().trim();if(!i){if(r.length>0)break;continue}if(!EL(i)){if(ase(i))break;r.push(i)}}return r}function lse(t){const e=da(t.message.replace(/\(\d+:\d+\)/g,"").replace(/\bline\s+\d+\b/gi,"line").replace(/\bcolumn\s+\d+\b/gi,"column"));return t.moduleName?`module:${t.moduleName}:${t.type}`:t.filePath&&t.code?`${t.filePath}:${t.code}:${e}`:t.filePath?`${t.filePath}:${t.type}:${e}`:`${t.source}:${t.type}:${e}`}function cse(t){const e=Ch(t.output),r=t.stage==="typecheck"?"typecheck":"build";if(!e.trim())return[];const n=e.split(/\n/),s=[],i=o=>{const l=da(o.message);l&&s.push({...o,filePath:ose(o.filePath),message:l,details:o.details.map(c=>
1979da(c)).filter(Boolean).slice(0,rh)})};for(let o=0;o<n.length;o+=1){const c=String(n[o]||"").trimEnd().trim();if(!c||EL(c))continue;const u=c.match(/^(.+?)\((\d+),\s*(\d+)\): error ([A-Z]+\d+): (.+)$/i);if(u){i({source:r,filePath:u[1],line:Number.parseInt(u[2],10),column:Number.parseInt(u[3],10),code:u[4],type:"typescript",message:u[5],details:Df(n,o)});continue}const d=c.match(/^\[plugin:([^\]]+)\]\s+(.+?):\s+(.+?)\s+\((\d+):(\d+)\)$/i);if(d){i({source:"build",filePath:d[2],line:Number.parseInt(d[4],10),column:Number.parseInt(d[5],10),code:d[1],type:d[1].toLowerCase().includes("react-babel")?"syntax":"build-plugin",message:d[3],details:Df(n,o)});continue}const h=c.match(/^(.+?\.(?:[cm]?[jt]sx?|vue|astro|svelte|css|scss|sass|less|html)):(\d+):(\d+):\s*(.+)$/i);if(h){i({source:r,filePath:h[1],line:Number.parseInt(h[2],10),column:Number.parseInt(h[3],10),code:null,type:"compile",message:h[4],details:Df(n,o)});continue}const m=c.match(/(?:failed to resolve import|cannot find module|could not resolve)\s+["']([^"']+)["'](?:\s+from\s+["']([^"']+)["'])?/i);if(m){i({source:r,filePath:m[2]||null,line:null,column:null,code:null,type:"missing-module",message:c,details:Df(n,o)});continue}}if(s.length>0)return s;if(t.exitCode===0)return[];if($l(t))return[];const a=n.map(o=>da(o)).find(o=>o&&!/^(npm|vite v|\u2713|x build failed|build failed in|\>)/i.test(o))||`${t.command} failed`;return[{source:r,filePath:null,line:null,column:null,code:null,type:t.stage==="install"?"install":"command",message:a,details:n.map(o=>da(o)).filter(Boolean).slice(0,rh)}]}function use(t){const e=new Map,r=new Set;for(const n of t)for(const s of cse(n)){const a=s.message.match(/(?:failed to resolve import|cannot find module|could not resolve)\s+["']([^"']+)["']/i)?.[1]||null,o=[s.source,s.filePath||"",s.line??"",s.column??"",s.code||"",s.type,da(s.message)].join("::");if(r.has(o))continue;r.add(o);const l=lse({...s,moduleName:a}),c=e.get(l);if(!c){e.set(l,{rootCauseKey:l,source:s.source,filePath:s.filePath,line:s.line,column:s.column,code:s.code,type:s.type,message:s.message,details:s.details,moduleName:a,occurrences:[s]});continue}c.occurrences.push(s),c.details.length<rh&&(c.details=[...c.details,...s.details].map(u=>da(u)).filter(Boolean).slice(0,rh))}return[...e.values()].sort((n,s)=>{const i=o=>o.type==="syntax"||o.type==="missing-module"?0:o.source==="build"?1:o.type==="typescript"?2:3,a=i(n)-i(s);return a!==0?a:`${n.filePath||""}:${n.message}`.localeCompare(`${s.filePath||""}:${s.message}`)}).slice(0,une)}function dse(t){return t.length>0&&t.every(e=>e.source==="typecheck"&&e.occurrences.every(r=>r.source==="typecheck"))}function hse(t,e,r=[]){const n=t.map(a=>a.rootCauseKey),s=e.map(a=>Sd(a)),i=r.map(a=>`${a.code}:${a.sourceFile}:${a.importSource}:${a.missingExportNames.join(",")}`);return`post-stream-build-validation::${Tt([...n,...s,...i].join("||")).slice(0,1200)}`}function m1(t,e,r=[]){return`${t.length} build issue(s), ${e.length} validation issue(s), and ${r.length} import issue(s) queued for batched ${ao} repair`}function kL(t,e=24,r=2400){const n=Ch(t).replace(/\r/g,"").split(` 1980`).map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(n.length===0)return"";const s=n.slice(-e).join(` 1981`);return s.length>r?s.slice(s.length-r):s}function Pl(t){return t.map(e=>({stage:e.stage,command:e.command,timeoutMs:e.timeoutMs??null,outputPreview:kL(e.output,8,800)}))}function fse(t){const e=Math.max(0,...t.map(s=>s.timeoutMs||0)),r=Math.max(1,Math.round(e/6e4));if(t.some(s=>s.stage==="install"))return`App files are saved, but required preview packages did not finish downloading within ${r} minutes. Slow connections are supported; retry when the connection is steadier and the cached download can continue.`;const n=t.map(s=>s.stage).join(", ");return`Workspace validation exceeded ${r} minutes while running ${n}. This is not a generated-code failure. Syntax-clean files will continue to preview; if preview still cannot start, continue the project with smaller follow-up prompts so each validation pass has less work.`}function g1(t){return t.slice(0,5).map(e=>({source:e.source,type:e.type,filePath:e.filePath,line:e.line,column:e.column,code:e.code,message:e.message,details:e.details.slice(0,3)}))}function Xb(t){return t.slice(0,5).map(e=>({code:e.code,filePath:e.filePath,summary:nh(e)}))}function Jb(t){return t.slice(0,5).map(e=>
1981({code:e.code,sourceFile:e.sourceFile,importSource:e.importSource,message:e.message,missingExportNames:e.missingExportNames.slice(0,5)}))}function pse(t){const e=t.buildIssues.map(a=>({source:a.source,type:a.type,filePath:a.filePath,line:a.line,column:a.column,code:a.code,moduleName:a.moduleName,message:a.message,details:a.details,relatedOccurrences:a.occurrences.slice(1).map(o=>({source:o.source,filePath:o.filePath,line:o.line,column:o.column,code:o.code,message:o.message}))})),r=t.validationIssues.map(a=>_L(a)),n=(t.importIssues||[]).map(a=>xL(a)),s=(t.importGraphReport?.missingDependencies||[]).map(a=>pu(a)),i=t.commandResults.filter(a=>!$l(a)).map(a=>({stage:a.stage,command:a.command,exitCode:a.exitCode,outputPreview:Ch(a.output).slice(0,cne)}));return`${Yo} 1982${Xo} 1983Use ${ao} (${Jo}) to repair the CURRENT project in place. 1984The full generation stream is already complete. This is a consolidated validation pass after streaming. Build or typecheck may have been skipped if blocking validation issues were detected first. 1985Use the consolidated diagnostics below as evidence, then inspect the current workspace and repair whichever generated files are needed for a clean build. 1986Do not treat the first reported file, line, or parser message as the only repair target. 1987Stream complete corrected file contents for every affected file using normal Bolt file actions. 1988Do not use find/replace patch blocks for this repair pass. 1989Use this format for every changed or created file: 1990 1991<boltAction type="file" filePath="src/App.tsx"> 1992// full corrected file content here 1993</boltAction> 1994 1995Current user goal: 1996\`\`\`text 1997${t.originalRequest.trim().slice(0,6e3)||"Repair the generated project so it builds cleanly and preview can start."} 1998\`\`\` 1999 2000Repair loop iteration: ${t.repairIteration} of ${ep} 2001 2002Post-stream command results: 2003\`\`\`json 2004${JSON.stringify(i,null,2)} 2005\`\`\` 2006 2007Aggregated build diagnostics: 2008\`\`\`json 2009${JSON.stringify(e,null,2)} 2010\`\`\` 2011 2012Additional generated-app validation issues: 2013\`\`\`json 2014${JSON.stringify(r,null,2)} 2015\`\`\` 2016 2017Import dependency graph issues: 2018\`\`\`json 2019${JSON.stringify(n,null,2)} 2020\`\`\` 2021 2022Missing dependency graph: 2023\`\`\`json 2024${JSON.stringify(s,null,2)} 2025\`\`\` 2026 2027Requirements: 2028- use the consolidated diagnostics as evidence, but choose the repair path from the actual code 2029- fix the root cause even if it is outside the first reported file/error 2030- do not send a partial repair for only the first failing file 2031- do not leave unresolved imports 2032- emit full <boltAction type="file"> contents for all changed or created files 2033- include every file needed to make imports, routes, and preview startup coherent 2034- return only actionable full-file <boltAction type="file"> updates with no commentary 2035- preserve standard \`lucide-react\` imports when the package is declared; replace only invalid \`lucide-icons\` or \`node_modules/lucide-react\` import paths 2036- keep Stripe and CloudMySite Forms optional unless already configured or explicitly requested to be live now 2037- checkout and forms must remain safe placeholder/admin-configurable flows when integration is not configured 2038- return a self-contained, buildable repair delta 2039- finish only when the project should pass post-stream validation and \`npm run build\``}function mse(t){const e=` 2040 2041### CRITICAL: Previous repair attempt did NOT resolve these issues 2042The exact same issue signature was detected after the previous repair pass. 2043Your previous fix failed to resolve the root cause. Do NOT repeat the same approach. 2044 2045Previous issue signature (unchanged): 2046\`\`\` 2047${t.previousSignature.slice(0,800)} 2048\`\`\` 2049 2050Current issue signature: 2051\`\`\` 2052${t.currentSignature.slice(0,800)} 2053\`\`\` 2054 2055Affected files: 2056${t.affectedFiles.length>0?t.affectedFiles.map(r=>`- ${r}`).join(` 2057`):"(none listed)"} 2058 2059Remaining unresolved issues: 2060\`\`\`json 2061${JSON.stringify(t.remainingIssues.slice(0,15),null,2)} 2062\`\`\` 2063 2064Instructions: 2065- Analyze WHY the previous fix did not work 2066- Stream full corrected \`<boltAction type="file">\` contents for every generated file required by the root-cause fix 2067- Do not use find/replace patch blocks 2068- Do not rewrite unrelated files or regenerate the whole project 2069- Verify every imported file exists before referencing it 2070- Verify exact path/casing matches for all imports
2071- Do not leave unresolved imports 2072- Do NOT introduce new issues while fixing these 2073- The project MUST pass \`npm run build\` and typecheck after this fix 2074`;return t.basePrompt+e}function gse(t){const e=` 2075 2076### CRITICAL: The missing dependency graph is still unresolved 2077The previous repair attempt failed to close the same missing local dependency graph. 2078Do not send another partial architecture patch. 2079 2080Unchanged missing dependencies: 2081\`\`\`json 2082${JSON.stringify(t.importGraphReport.missingDependencies.slice(0,15),null,2)} 2083\`\`\` 2084 2085Instructions: 2086- Resolve the missing dependency graph with actionable file updates 2087- Stream full corrected \`<boltAction type="file">\` contents for every affected file 2088- Do not use find/replace patch blocks 2089- Prefer fixing or removing the broken import from the importer instead of inventing new files 2090- If a simple site can fit in \`src/App.tsx\`, collapse the implementation there instead of creating more missing modules 2091- Return a self-contained, buildable project delta with zero unresolved imports 2092`;return t.basePrompt+e}const mr=ya("Chat"),b1=4500;async function v1(t,e,r){let n;try{return await Promise.race([t,new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`${r} timed out after ${e}ms`)),e)})])}finally{n&&clearTimeout(n)}}function bse(){gu.trace("Chat");const{ready:t,routeChatId:e,workspaceId:r,initialMessages:n,restoredFromSnapshot:s,storeMessageHistory:i,importChat:a,exportChat:o,updateChatMestaData:l,ensureWorkspaceIdentity:c}=W1({loadRouteHistory:!0}),u=We(sp),d=We(ip);return f.jsxs(f.Fragment,{children:[t?f.jsx(LL,{description:u,conversationId:e,workspaceId:r,initialMessages:n,restoredFromSnapshot:s,exportChat:o,storeMessageHistory:i,importChat:a,metadata:d,updateChatMestaData:l,ensureWorkspaceIdentity:c}):f.jsx(DO,{restoringSavedApp:!!e}),f.jsx(bD,{closeButton:({closeToast:h})=>f.jsx("button",{className:"Toastify__close-button",onClick:h,children:f.jsx("div",{className:"i-ph:x text-lg"})}),icon:({type:h})=>{switch(h){case"success":return f.jsx("div",{className:"i-ph:check-bold text-bolt-elements-icon-success text-2xl"});case"error":return f.jsx("div",{className:"i-ph:warning-circle-bold text-bolt-elements-icon-error text-2xl"})}},position:"bottom-right",pauseOnFocusLoss:!0,transition:tne,autoClose:3e3})]})}const vse=ID(t=>{const{messages:e,initialMessages:r,isLoading:n,parseMessages:s,storeMessageHistory:i}=t;s(e,n),!n&&e.length>r.length&&i(e,{persistSnapshot:!1}).catch(a=>Se.error(a.message))},50),PL=/\.(html?|tsx?|jsx|vue|astro|svelte|mdx?)$/i,TL=["/components/","/component/","/css/","/styles/","/js/","/scripts/","/assets/"],yse=["imported-files","starter-template-files"];function y1(t){return!t||t.type==="runtime"?!1:!yse.some(e=>String(t.id||"").toLowerCase().startsWith(e))}function _se(t){if(t.type==="file"){const e=t.filePath.replace(/\\/g,"/"),r=e.split("/").pop()||e;return PL.test(r)&&!TL.some(n=>e.toLowerCase().includes(n))?`Generating ${r}`:`Updating ${r}`}return t.type==="start"?"Starting live preview":t.type==="shell"?String(t.content||"").toLowerCase().includes("install")?"Preparing dependencies":"Running workspace command":t.type==="build"?"Finalizing workspace":null}function xse(t,e){return t==="GENERATING"?e==="repair"?"Applying Qwen fixes":e==="update"?"Applying requested updates":"Generating app files":t==="STREAM_COMPLETE"?"Validating generated app":t==="INSTALLING_DEPENDENCIES"?"Installing dependencies":t==="BUILDING"?"Building app":t==="BUILD_VERIFICATION"?"Verifying repaired app":t==="BUILD_FAILED_AGGREGATED"||t==="REPAIRING"?"Fixing build issues":t==="READY_FOR_PREVIEW"?"Opening live preview":t==="PREVIEW_RUNNING"?"Live preview ready":t==="FAILED"?"Build failed":null}function wse(t,e){const r=t[t.length-1];return{chatIndex:r?.id||`workspace-build-${Date.now().toString(36)}`,files:jM(e),messageSignature:r?`${r.id}:${r.role}:${Gi(r).length}`:""}}function Sse(t){switch(t){case"running":return"Building your app";case"ready":return"Build ready";case"failed":return"Build failed";case"canceled":return"Build canceled";case"queued":default:return"Preparing build"}}function Qy(t){return t?t.status==="ready"&&t.previewReady:!0}function Cse(t,e){const r=e?.historyStatusOverride;return t?t.requestMode==="build"?t.status==="failed"||t.status==="canceled"?"failed":Qy(t)?"draft":"processing":Qy(t)?r==="published"||r==="running"?r:"draft":r==="published"||r==="running"||r==="draft"?r:"draft":r??"draft"}function Gi(t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e1(e);const r=t.parts;return Array.isArray(r)?e1(r):""}function Tl(t,e){return[e?"loading":"idle",...t.map(r=>{const n=Gi(r);return[r.id,r.role,n.length,n.slice(0,40),n.slice(-40),Array.isArray(r.parts)?r.parts.length:0].join(":")})].join("||")}function Tt(t){const e=t.replace(/([?&]t=)\d+/g,"$1<ts>").replace(/\b\d+:\d+\b/g,"<loc>").replace(/\s+/g," ").trim();if(e.length<=800)return e;const r=e.slice(0,440),n=e.slice(-340);return`${r} ... ${n}`}function _1(t,e,r){const n=fn(e);if(!n)return"";let s="";for(const i of t){if(i.role!=="assistant")continue;const a=Gi(i);if(!a.includes("<boltAction"))continue;o1.lastIndex=0;let o;for(;(o=o1.exec(a))!==null;){const l=String(o[1]||"");if(!bne.test(l))continue;const c=l.match(vne);
2092if(fn(String(c?.[1]||""))!==n)continue;const d=String(o[2]||"");r&&!r(d)||(s=d)}}return s}function kc(t){return E0(t)}const x1=/<<<FILE:([^\n>]+)>>>\s*\r?\n<<<FIND>>>\s*\r?\n([\s\S]*?)\r?\n<<<REPLACE>>>\s*\r?\n([\s\S]*?)\r?\n<<<END>>>/g;function RL(t){const e=[];if(!t)return e;let r;for(;(r=x1.exec(t))!==null;)e.push({filePath:fn(r[1]||""),findText:r[2]||"",replaceText:r[3]||""});return x1.lastIndex=0,e}function wd(t){return String(t||"").replace(/\r\n/g,` 2093`).replace(/\r/g,` 2094`)}function w1(t,e){if(!t||!e)return 0;let r=0,n=0;for(;n<=t.length;){const s=t.indexOf(e,n);if(s===-1)break;r+=1,n=s+e.length}return r}function S1(t,e,r){const n=t.indexOf(e);return n===-1?t:`${t.slice(0,n)}${r}${t.slice(n+e.length)}`}function Ase(t,e){if(!e.findText)return{applied:!1,reason:"empty-find"};const r=w1(t,e.findText);if(r===1)return{applied:!0,content:S1(t,e.findText,e.replaceText),matchMode:"exact"};if(r>1)return{applied:!1,reason:"ambiguous-match"};const n=wd(t),s=wd(e.findText),i=wd(e.replaceText),a=w1(n,s);if(a!==1)return{applied:!1,reason:a>1?"ambiguous-match":"not-found"};const o=S1(n,s,i);return{applied:!0,content:t.includes(`\r 2095`)?o.replace(/\n/g,`\r 2096`):o,matchMode:"normalized-line-endings"}}function C1(t){const e=t||"",r=RL(e).length,n=(e.match(/<boltArtifact\b/gi)||[]).length,s=(e.match(/<boltAction\b/gi)||[]).length,i=(e.match(/<boltAction\b[^>]*\btype="file"/gi)||[]).length,a=(e.match(/<boltAction\b[^>]*\btype="shell"/gi)||[]).length,o=(e.match(/<boltAction\b[^>]*\btype="start"/gi)||[]).length,l=(e.match(/^\s*(?:[-*]\s*)?(?:Create|Update|Delete|Run command|Start Application|Install Dependencies|Install project dependencies)\b/gim)||[]).length,c=(e.match(/^\s*(?:import\s.+from\s+['"][^'"]+['"];?|export\s+default\b|export\s+(?:const|function|interface|type)\b|function\s+[A-Z]\w*\s*\(|const\s+[A-Z]\w*\s*[:=]|interface\s+\w+\s*\{|type\s+\w+\s*=|return\s*\(|<Route\b|<Link\b|<div\b|<section\b)/gim)||[]).length,u=/```(?:[a-z0-9_-]+)?/i.test(e);return{contentLength:e.length,hasBoltArtifact:n>0,hasBoltAction:s>0,hasTargetedRepairBlocks:r>0,boltArtifactCount:n,boltActionCount:s,fileActionCount:i,shellActionCount:a,startActionCount:o,targetedRepairBlockCount:r,actionLikeLineCount:l,codeLikeLineCount:c,containsCodeFence:u,containsTemplatePlaceholder:/Start prompting \(or editing\) to see magic happen/i.test(e),previewHead:e.slice(0,220),previewTail:e.slice(-220)}}function Qb(t){return String(t||"").toLowerCase().replace(/&/g,"and").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function A1(t,e){const r=Qb(t);return r?e.includes("/")&&/^(?:home|dashboard)$/.test(r)?"/":e.filter(s=>{if(!s.startsWith("/")||s==="/")return!1;const i=s.split("/").filter(Boolean).filter(c=>!c.startsWith(":"));if(i.length===0)return!1;const a=i[i.length-1],o=Qb(a),l=Qb(i.join("-"));return r===o||r===l}).sort((s,i)=>s.length-i.length)[0]:void 0}function Ese(t,e){let r=t;const n=new Set,s=new Set;return r=r.replace(/\blabel\s*:\s*["'`]([^"'`]+)["'`]([\s\S]{0,160}?)\b(href|to)\s*:\s*(["'`])#\4/g,(i,a,o,l,c)=>{const u=String(a||"").trim(),d=A1(u,e);return d?(n.add(u),`label: ${c}${u}${c}${o}${l}: ${c}${d}${c}`):(s.add(u),i)}),r=r.replace(/<(a|Link|NavLink)\b([^>]*?)\b(href|to)\s*=\s*(["'`])#\4([^>]*)>\s*([^<]{1,80}?)\s*<\/\1>/g,(i,a,o,l,c,u,d)=>{const h=String(d||"").trim(),m=A1(h,e);return m?(n.add(h),`<${a}${o}${l}=${c}${m}${c}${u}>${h}</${a}>`):(s.add(h),i)}),n.size===0?null:{content:r,repairedLabels:[...n],unresolvedLabels:[...s]}}function mu(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kse(t,e,r){const n=_ne[e]||r[0];if(!n||n===e)return null;const s=new RegExp(`(["'\`])${mu(e)}\\1`,"g");let i=0;const a=t.replace(s,(o,l)=>(i+=1,`${l}${n}${l}`));return i===0||a===t?null:{content:a,replacementCount:i,replacementPath:n}}function Pse(t){try{const e=JSON.parse(t);if(!e||typeof e!="object"||!e.auth||typeof e.auth!="object"||e.auth.enabled!==!0)return null;const r={...e.auth},n=[];let s=!1;if(r.requireLogin===!0&&(r.requireLogin=!1,s=!0),Array.isArray(r.protectedPaths)){const i=r.protectedPaths.filter(a=>{const o=String(a||"").trim().toLowerCase(),l=xne.has(o);return l&&n.push(String(a)),!l});i.length!==r.protectedPaths.length&&(r.protectedPaths=i,s=!0)}return s?{content:`${JSON.stringify({...e,auth:r},null,2)} 2097`,disabledRequireLogin:e.auth.requireLogin===!0,removedProtectedPaths:n}:null}catch{return null}}function Tse(t){try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;const r=e.auth&&typeof e.auth=="object"&&!Array.isArray(e.auth)?{...e.auth}:{};return r.enabled===!0?null:(r.enabled=!0,{content:`${JSON.stringify({...e,auth:r},null,2)} 2098`})}catch{return null}}function Rse(t,e){if(!yne.test(t))return null;const r=hn(e,"src/lib/appAuth.tsx"),n=hn(e,"src/App.tsx")||hn(e,"src/App.jsx");return!r||!n?null:"<!-- system:auth-routing-rules -->\nAUTH ROUTING FOLLOW-UP RULES:\n- If the user wants the app, game, dashboard, landing page, or other main experience visible before sign-in, keep that public experience reachable at `/` and do not make `/login` the default landing route unless the user explicitly asked for a login-first app.\n- When changing auth UX, update the whole route shell together: `src/App.tsx`, redirects, wildcard/fallback routes, CTA links/buttons, and logout destinations. Do not only edit the leaf component mentioned in the prompt.\n- Qwen must generate only auth-screen presentation. Either theme `src/components/
2098auth/AuthScreens.tsx` directly or keep it as the builder mount point while composing presentation-only subcomponents from it. Do not create parallel auth route files, auth API consumers, Google OAuth logic, or auth runtime logic; the builder owns `/login`, `/signup`, `/account`, `/logout`, `/auth/complete`, `/api/auth/me`, `/api/auth/logout`, `/api/auth/google/start`, and `/api/auth/cloudmysite/exchange`.\n- If the header/nav needs auth controls, render the builder-owned `AuthNav` from `src/lib/appAuth.tsx` instead of static Sign in / Sign up links.\n- If logout should return the user to the public app experience, navigate to that public route instead of forcing `/login` unless the user explicitly asked for a logged-out login landing page.\n<!-- /system:auth-routing-rules -->"}const E1=240,Ise=240,k1=500;function Rl(t,e){const r=String(t??"").replace(/\s+/g," ").trim();return r.length<=e?r:`${r.slice(0,Math.max(0,e-3))}...`}function Nse(t){return{tagName:Rl(t.tagName,80),id:Rl(t.id,120),className:Rl(t.className,Ise),selector:Rl(t.selector,k1),elementPath:Rl(t.elementPath,k1),displayText:Rl(t.displayText,E1),textContent:Rl(t.textContent,E1),styles:t.styles||{},rect:t.rect}}function Lse(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function Dse(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Mse(t){const e=Nse(t),r=JSON.stringify(e),n=Lse(r),s=Dse(e.displayText);return`<!-- system:selected-element-scope --> 2099SELECTED ELEMENT SCOPED EDIT MODE: 2100- The user selected one element in the live preview before sending this request. Treat the selected element as the target scope for the requested change. 2101- First locate the matching mounted component/section using the selected element metadata below: selector, element path, tag, id, classes, visible text, and nearby structure. 2102- Change only the selected element, its direct descendants, or the smallest containing section/component required to satisfy the user's instruction. 2103- Do not redesign unrelated sections, routes, navigation, data models, auth/runtime files, or global styles unless the selected target cannot work without that minimal supporting change.
2104- If a shared CSS class or component is reused elsewhere, prefer adding a target-specific wrapper/class or changing the local JSX so unrelated repeated elements keep their current appearance. 2105- Still emit full updated file contents in bolt file actions, and include only files that are needed for this scoped edit to compile and render. 2106 2107Selected element metadata: 2108${[`- tag: ${e.tagName||"unknown"}`,e.selector?`- selector: ${e.selector}`:null,e.elementPath?`- DOM path: ${e.elementPath}`:null,e.id?`- id: ${e.id}`:null,e.className?`- classes: ${e.className}`:null,e.textContent?`- text: ${e.textContent}`:null,e.displayText?`- display: ${e.displayText}`:null].filter(Boolean).join(` 2109`)} 2110<!-- /system:selected-element-scope --> 2111<div class="__boltSelectedElement__" data-element='${n}'>${s}</div>`}const Ose=/\b((?:1|one|single)[- ]section|(?:1|one|single)[- ]page|single html|single[- ]file html|single html file|one html file|landing page|hero section|simple site|simple website|brochure site|portfolio site)\b/i,jse=/\b(dashboard|admin|login|signup|auth|authentication|checkout|payments?|cms|blog|api|database|crud|inventory|marketplace|multi[- ]page|multiple pages|router|routes)\b/i;function $se(t,e){const r=t.trim();return e==="build"&&Ose.test(r)?jse.test(r)?"complete-dependency-set":"single-file-preferred":"complete-dependency-set"}function Bse(t){return t==="single-file-preferred"?"<!-- system:self-contained-generation -->\nSELF-CONTAINED GENERATION MODE:\n- Prefer a minimal self-contained implementation in the active entry file for this request.\n- For React templates, that usually means `src/App.tsx`.\n- For Vanilla Vite or static HTML single-file game requests, prefer `index.html` with inline CSS and JavaScript unless the selected template requires `main.js` or `src/main.js`.\n- Only split into additional pages/components/hooks/utils/assets/routes if you also emit every referenced file in the SAME response.\n- Do not finish with unresolved local imports.\n<!-- /system:self-contained-generation -->":`<!-- system:self-contained-generation --> 2112SELF-CONTAINED GENERATION RULES: 2113- If you add any local import, emit every referenced local file in the SAME response. 2114- Do not invent pages/components/hooks/utils/assets/routes unless you also include those files now. 2115- For every import in emitted code, either create the target file in this response or remove the import. 2116- Return a self-contained, buildable project delta with zero unresolved imports. 2117<!-- /system:self-contained-generation -->`}const Fse=/Start prompting \(or editing\) to see magic happen/i,IL=[{id:"genie-placeholder",regex:/Start prompting \(or editing\) to see magic happen/i},{id:"vite-react-header",regex:/<h1>\s*Vite \+ React\s*<\/h1>/i},{id:"vite-vanilla-header",regex:/<h1>\s*Vite \+ Vanilla\s*<\/h1>/i},{id:"hello-vite",regex:/Hello Vite!/i},{id:"vite-counter",regex:/count is 0/i},{id:"vite-logo-copy",regex:/Click on the Vite logo to learn more/i},{id:"vite-vanilla-setup-counter",regex:/\bsetupCounter\s*\(\s*document\.querySelector\(\s*['"]#counter['"]\s*\)\s*\)/i},{id:"vite-vue-header",regex:/<h1>\s*Vite \+ Vue\s*<\/h1>/i},{id:"vite-vue-success",regex:/You did it!/i},{id:"vite-hmr-copy",regex:/edit\s+<code>src\/App\.(?:vue|tsx?|jsx?)<\/code>\s+to test hmr/i}],Wse=["index.html","main.js","main.ts","main.jsx","main.tsx","counter.js","style.css","src/App.tsx","src/App.jsx","src/App.ts","src/App.js","src/App.vue","src/components/HelloWorld.vue","src/main.tsx","src/main.ts","src/main.js","src/app.js"],Hse=Wse.map(t=>t.toLowerCase()),Use=["",".js",".jsx",".ts",".tsx",".mjs",".cjs",".css",".json"],zse=["/index.js","/index.jsx","/index.ts","/index.tsx","/index.mjs","/index.cjs","/index.css"];function Qi(t){return String(t||"").replace(/\\/g,"/").replace(/^\/+/,"").replace(/^\.\/+/,"").replace(/[?#].*$/,"").toLowerCase()}function Vse(t){return/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t)}function Gse(t,e){const r=String(e||"").trim().replace(/[?#].*$/,"");if(!r||Vse(r))return null;if(r.startsWith("/"))return Qi(r);if(!r.startsWith("."))return null;const n=Qi(t).split("/");n.pop();for(const s of r.split("/"))if(!(!s||s===".")){if(s===".."){n.pop();continue}n.push(s)}return Qi(n.join("/"))}function qse(t,e){if(!e)return null;if(t.has(e))return e;for(const r of Use){const n=`${e}${r}`;if(t.has(n))return n}for(const r of zse){const n=`${e}${r}`;if(t.has(n))return n}return null}function Kse(t,e){const r=[],n=s=>{const i=Gse(t,s);i&&r.push(i)};for(const s of e.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi))n(String(s[1]||""));for(const s of e.matchAll(/<link\b[^>]*\bhref=["']([^"']+)["'][^>]*>/gi)){const i=String(s[0]||"").match(/\brel=["']([^"']+)["']/i),a=String(i?.[1]||"").toLowerCase();(!a||a.includes("stylesheet")||a.includes("modulepreload"))&&n(String(s[1]||""))}for(const s of e.matchAll(/\bimport\s+(?:[^'"]*?\s+from\s*)?["']([^"']+)["']/g))n(String(s[1]||""));for(const s of e.matchAll(/\bexport\s+[^'"]*?\s+from\s*["']([^"']+)["']/g))n(String(s[1]||""));for(const s of e.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g))n(String(s[1]||""));for(const s of e.matchAll(/@import\s+(?:url\()?\s*["']([^"']+)["']/g))n(String(s[1]||""));return r}function NL(t){const e=new Map;for(const[i,a]of Object.entries(t))!a||a.type!=="file"||a.isBinary||typeof a.content!="string"||e.set(Qi(i),i);const r=[...e.keys()].filter(i=>i.startsWith("public/")?!1:i==="index.html"||i.endsWith("/index.html"));if(r.length===0)return null;const n=new Set,s=[...r];for(;s.length>0;){const i=s.shift();if(n.has(i))continue;n.add(i);const a=e.get(i),o=a?t[a]:null,l=o&&o.type==="file"&&typeof o.content=="string"?o.content:"";for(const c of Kse(i,l)){const u=qse(e,c);u&&!n.has(u)&&s.push(u)}}return n}function P1(t){const e=NL(t);for(const[r,n]of Object.entries(t)){if(!n||n.type!=="file"||n.isBinary)continue;const s=Qi(r);if(!(e?e.has(s):Hse.some(l=>s===l||s.endsWith(`/${l}`))))continue;const a=String(n.content||""),o=IL.find(l=>l.regex.test(a));if(o)return{detected:!0,filePath:r,patternId:o.id}}return{detected:!1}}function nh(t){if(t.code==="phaser-runtime-api-misuse")return`${t.violations.length} Phaser API misuse${t.violations.length===1?"":"s"} can crash the game at runtime in ${t.filePath}`;if(t.code==="orphaned-navigation-component")return`${t.componentNames.join(", ")} exist but are not mounted from ${t.filePath}`;if(t.code==="unsupported-stock-image-host")return`${t.filePath} uses unsupported image hosts (${t.disallowedHosts.join(", ")}) that can leave blank cards`;if(t.code==="remote-managed-asset-url")return`${t.filePath} still points selected workspace images at remote /api/assets URLs instead of local project files`;if(t.code==="persisted-local-db-duplicate-rows")return`${t.filePath} has ${t.duplicateRowCount} duplicate persisted rows across ${t.duplicateTables.length} table(s)`;if(t.code==="nested-router-provider")return`${t.routerProviderFiles.length} files render router providers (${t.providerComponents.join(", ")})`;if(t.code==="auth-global-lockout")return`${t.filePath} routes auth through the template gate while custom login/signup entry points exist`;if(t.code==="direct-auth-screen-mount")return`${t.filePath} mounts template auth screen component(s) directly instead of rendering the app`;if(t.code==="static-stripe-setup-banner")return`${t.filePath} hardcodes Stripe setup-required UI instead of reading live integration status`;if(t.code==="missing-stripe-checkout-route")return`${t.filePath} calls ${t.endpointPath} but the Stripe runtime route is missing`;if(t.code==="invalid-stripe-preview-secret-access")return`${t.runtimeFilePath} reads Stripe preview secrets through the wrong runtime source for ${t.endpointPath}`;if(t.code==="invalid-stripe-checkout-client-flow")return`${t.filePath} uses a broken hosted Stripe Checkout client flow for ${t.endpointPath}`;if(t.code==="payment-browser-alert")return`${t.filePath} uses a browser alert for payment feedback instead of in-app English status UI`;if(t.code==="app-schema-slug-mismatch")return`${t.filePath} uses schema slug ${t.actualAppSlug} instead of runtime app slug ${t.expectedAppSlug}`;if(t.code==="unmatched-navigation-route")return t.missingPaths.length===1?`${t.filePath} has no route for navigation target ${t.missingPath}`:`${t.filePath} has no routes for ${t.missingPaths.length} navigation targets (for example ${t.missingPaths.slice(0,3).join(", ")})`;if(t.code==="placeholder-navigation-link"){const e=t.placeholderLinks.slice(0,3).map(r=>r.label).join(", ");return`${t.filePath} keeps mounted navigation on placeholder # links (for example ${e})`}if(t.code==="duplicate-import-declaration"){const e=t.duplicateBindings[0];return`${e?.filePath||t.filePath} redeclares imported identifier ${e?.identifier||""}`.trim()}if(t.code==="missing-local-import"){const e=t.missingImports.length,r=e===1?"":"s";return`${t.filePath} has ${e} missing local import${r} (for example ${t.importSource})`}if(t.code==="missing-package-dependency"){const e=t.packageNames.length,r=e===1?"y":"ies";return`${t.packageJsonPath} is missing ${e} package dependenc${r} (for example ${t.missingPackage})`}if(t.code==="browser-commonjs-require")return`${t.filePath} uses browser-side CommonJS require(${t.requireSources[0]||""}) instead of ESM imports`;if(t.code==="missing-three-symbol-import")return`${t.filePath} uses Three.js runtime symbol ${t.missingSymbols[0]||""} without importing it from three`;if(t.code==="missing-react-three-fiber-symbol-import")return`${t.filePath} uses React Three Fiber runtime symbol ${t.missingSymbols[0]||""} without importing it from @react-three/fiber`;if(t.code==="react-three-dom-element-in-canvas")return`${t.filePath} renders DOM tag <${t.invalidTags[0]||"div"}> through React Three Fiber Canvas`;if(t.code==="missing-react-three-physics-provider")return`${t.filePath} uses @react-three/cannon consumers without a reachable <Physics> provider`;if(t.code==="missing-text-geometry-extension")return`${t.filePath} renders raw <textGeometry> without registering TextGeometry for React Three Fiber`;if(t.code==="invalid-protected-app-schema-import"){const e=t.invali
2117dIdentifiers.slice(0,3).join(", ")||"app-specific schema identifiers";return`${t.relatedFilePaths.length} files still import ${e} from protected infrastructure`}return t.code==="missing-local-db-api-plugin"?`${t.filePath} is missing working createLocalDbApiPlugin() wiring/export for /api/auth and /api/db`:t.code==="missing-vite-react-plugin"?`${t.filePath} is missing @vitejs/plugin-react wiring for a React Vite app`:t.code==="protected-runtime-export-contract"?`${t.filePath} imports missing protected runtime export${t.missingExports.length===1?"":"s"} (${t.missingExports.join(", ")}) from ${t.runtimeFilePath}`:t.code==="invalid-local-api-endpoint"?`${t.filePath} calls unsupported local API endpoint ${t.endpointPath}`:t.code==="auth-runtime-disabled"?`${t.filePath} disables auth while live app files still use ${t.builtInAuthModulePath}`:t.code==="hardcoded-auth-shortcut"?`${t.filePath} hardcodes ${t.authAction} credentials instead of routing users through real auth pages`:t.code==="signup-profile-fields-dropped"?`${t.filePath} renders extra signup fields (${t.profileFieldNames.join(", ")}) but the live signup call still drops them`:t.code==="unpersisted-profile-form"?`${t.filePath} renders profile fields (${t.profileFieldNames.join(", ")}) but the page only simulates saving them`:t.code==="auth-shell-loading-gate"?`${t.filePath} hides public auth pages behind a full-app ${t.loadingBindingName} gate`:t.code==="placeholder-route-shell"?`${t.filePath} still contains placeholder route copy (${t.placeholderCopy})`:t.code==="protected-runtime-syntax-corruption"?`${t.filePath} contains a known protected runtime syntax corruption that will fail worker checks`:t.code==="custom-auth-runtime-bypass"?`${t.customAuthModulePath} bypasses built-in auth from ${t.builtInAuthModulePath}`:t.code==="unpersisted-catalog-seed-data"?`${t.filePath} adds starter catalog arrays (${t.sourceNames.join(", ")}) but persisted tables remain empty`:t.code==="persisted-data-bootstrap-race"?`${t.filePath} renders persisted data consumers before ${t.bootstrapStateName} finishes bootstrapping schema`:t.code==="auth-gated-loading-state"?`${t.filePath} keeps ${t.loadingStateName} true when ${t.authStateName} is missing`:`${t.filePath} can duplicate persisted catalog rows from ${t.defaultSourceName}`}function Yse(t){return t.code!=="unmatched-navigation-route"}function T1(t){return wne.has(t.code)}function Xse(t){return t.code==="static-stripe-setup-banner"||t.code==="missing-stripe-checkout-route"||t.code==="invalid-stripe-preview-secret-access"||t.code==="invalid-stripe-checkout-client-flow"||t.code==="payment-browser-alert"}function Jse(t){return t.needsStripe||t.needsForms?"Your app draft is ready. Finish Forms, Payment and other settings setup from Admin.":""}function Sd(t){if(t.code==="phaser-runtime-api-misuse"){const r=t.violations.slice(0,24).map(n=>`${n.filePath}:${n.kind}:${n.snippet}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="orphaned-navigation-component"){const r=`${t.filePath}|${t.componentFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="unsupported-stock-image-host"){const r=`${t.filePath}|${t.disallowedHosts.join("|")}|${t.matchedUrls.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="remote-managed-asset-url"){const r=t.assetReplacements.map(n=>`${n.assetId}:${n.remoteUrl}:${n.localPublicUrl}`).join("|");return`generated-project-validation::${t.code}::${Tt(`${t.filePath}|${r}`).slice(0,900)}`}if(t.code==="persisted-local-db-duplicate-rows"){const r=t.duplicateTables.map(n=>`${n.tableName}:${n.duplicateRows}`).join("|");return`generated-project-validation::${t.code}::${Tt(`${t.filePath}|${t.duplicateRowCount}|${r}`).slice(0,900)}`}if(t.code==="duplicate-import-declaration"){const r=t.duplicateBindings.map(n=>`${n.filePath}:${n.identifier}:${n.importSource}:${n.declarationKind}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="unmatched-navigation-route"){const r=`${t.filePath}|${t.missingPaths.join("|")}|${t.knownRoutePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="placeholder-navigation-link"){const r=`${t.filePath}|${t.knownRoutePaths.join("|")}|${t.placeholderLinks.map(n=>`${n.filePath}:${n.label}`).join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="nested-router-provider"){const r=`${t.filePath}|${t.routerProviderFiles.join("|")}|${t.providerComponents.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="auth-global-lockout"){const r=`${t.filePath}|${t.requireLoginEnabled?"requireLogin":"protectedPaths"}|${t.protectedPaths.join("|")}|${t.hasLoginEntryPoint?"login":""}|${t.hasSignupEntryPoint?"signup":""}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="direct-auth-screen-mount"){const r=`${t.filePath}|${t.authScreensFilePath}|${t.authScreenNames.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="static-stripe-setup-banner"){const r=`${t.filePath}|${t.setupMessage}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-stripe-checkout-route"){const r=`${t.filePath}|${t.endpointPath}|${t.frontendFilePaths.join("|")}
2117|${t.missingRuntimeFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="invalid-stripe-preview-secret-access"){const r=`${t.filePath}|${t.runtimeFilePath}|${t.endpointPath}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="invalid-stripe-checkout-client-flow"){const r=`${t.filePath}|${t.endpointPath}|${t.hasRawCardCollection?"raw-card-ui":"no-raw-card-ui"}|${t.missingSessionRedirect?"missing-redirect":"has-redirect"}|${t.simulatesLocalSuccess?"simulated-success":"no-simulated-success"}|${t.missingSuccessUrl?"missing-success-url":"has-success-url"}|${t.missingCancelUrl?"missing-cancel-url":"has-cancel-url"}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="payment-browser-alert"){const r=`${t.filePath}|${t.alertText}|${t.containsNonEnglishCopy?"non-english":"english"}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="invalid-protected-app-schema-import"){const r=[...t.relatedFilePaths,t.importSource,...t.invalidIdentifiers].join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="app-schema-slug-mismatch"){const r=`${t.filePath}|${t.runtimeConfigPath}|${t.actualAppSlug}|${t.expectedAppSlug}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="unpersisted-catalog-seed-data"){const r=`${t.filePath}|${t.sourceNames.join("|")}|${t.emptyTables.join("|")}|${t.consumerFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="persisted-data-bootstrap-race"){const r=`${t.filePath}|${t.bootstrapStateName}|${t.consumerFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-package-dependency"){const r=t.missingPackages.slice(0,24).map(n=>`${n.filePath}:${n.packageName}:${n.importSource}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="browser-commonjs-require"){const r=t.requireSites.slice(0,24).map(n=>`${n.filePath}:${n.requireSource}:${n.snippet}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-three-symbol-import"){const r=t.missingSymbolSites.slice(0,24).map(n=>`${n.filePath}:${n.symbolName}:${n.snippet}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-react-three-fiber-symbol-import"){const r=t.missingSymbolSites.slice(0,24).map(n=>`${n.filePath}:${n.symbolName}:${n.snippet}`).join("|");return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="react-three-dom-element-in-canvas"){const r=`${t.canvasFilePath}|${t.componentName}|${t.invalidTagSites.slice(0,24).map(n=>`${n.tagName}:${n.snippet}`).join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-react-three-physics-provider"){const r=`${t.filePath}|${t.physicsConsumerFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-text-geometry-extension"){const r=`${t.filePath}|${t.textGeometryFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="missing-vite-react-plugin"){const r=`${t.filePath}|${t.packageJsonPath}|${t.hasReactPluginDependency?"dependency-present":"dependency-missing"}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="auth-runtime-disabled"){const r=`${t.filePath}|${t.builtInAuthModulePath}|${t.consumerFilePaths.join("|")}|${t.hasLoginEntryPoint?"login":""}|${t.hasSignupEntryPoint?"signup":""}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="hardcoded-auth-shortcut"){const r=`${t.filePath}|${t.authAction}|${t.matchedSnippet}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="signup-profile-fields-dropped"){const r=`${t.filePath}|${t.profileFieldNames.join("|")}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="unpersisted-profile-form"){const r=`${t.filePath}|${t.profileFieldNames.join("|")}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="placeholder-route-shell"){const r=`${t.filePath}|${t.placeholderCopy}|${t.relatedFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="protected-runtime-syntax-corruption"){const r=`${t.filePath}|${t.brokenFragment}|${t.fixedFragment}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}
2117if(t.code==="protected-runtime-export-contract"){const r=`${t.filePath}|${t.runtimeFilePath}|${t.importSource}|${t.missingExports.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code==="custom-auth-runtime-bypass"){const r=`${t.customAuthModulePath}|${t.builtInAuthModulePath}|${t.consumerFilePaths.join("|")}`;return`generated-project-validation::${t.code}::${Tt(r).slice(0,900)}`}if(t.code!=="missing-local-import")return`generated-project-validation::${t.code}::${t.filePath}`;const e=t.missingImports.slice(0,24).map(r=>`${r.filePath}:${r.importSource}`).join("|");return`generated-project-validation::${t.code}::${Tt(e).slice(0,900)}`}function Qse(t){const r=(t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(tsx|jsx)$/i,"")||"GeneratedComponent").replace(/[^a-zA-Z0-9_$]/g,"");return/^[A-Za-z_$]/.test(r)?r:`Generated${r}`}function Zse(t){return!t||!/[<>]/.test(t)?!1:/<[A-Za-z][\w:-]*[\s/>]/.test(t)||/\breturn\s*\(\s*</.test(t)||/\bReact\.createElement\s*\(/.test(t)}function eie(t){const e=t.match(/\bexport\s+(?:const|function|class)\s+([A-Z][A-Za-z0-9_$]*)\b/);if(e?.[1])return e[1];const r=t.match(/\bexport\s*{\s*([^}]+)\s*}/);return r?.[1]&&r[1].split(",").map(s=>s.trim()).map(s=>{const i=s.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(!i)return null;const a=i[2]||i[1];return/^[A-Z][A-Za-z0-9_$]*$/.test(a)?a:null}).filter(s=>!!s)[0]||null}function tie(t,e){const r=t.replace(/\\/g,"/");if(!/^src\/.+\.(tsx|jsx)$/i.test(r)||/\.(test|spec|stories)\.(tsx|jsx)$/i.test(r)||/\/(?:__tests__|hooks|utils|lib|stores?|contexts?|types)\//i.test(r)||/\/components\/auth\//i.test(r)||/\/(?:forms|form)\//i.test(r)||/\/main\.(tsx|jsx)$/i.test(r)||/\/App\.(tsx|jsx)$/i.test(r)||!Zse(e))return null;const n=Qse(r),s=`./${r.replace(/^src\//,"").replace(/\.(tsx|jsx)$/i,"")}`;if(/\bexport\s+default\b/.test(e))return{filePath:r,componentName:n,importPath:s,importStatement:`import ${n} from '${s}';`,renderName:n};const i=eie(e);return i?{filePath:r,componentName:i,importPath:s,importStatement:`import { ${i} } from '${s}';`,renderName:i}:null}function R1(t){const r=["Header","Navbar","NavBar","Hero","HeroSection","About","AboutSection","Skills","SkillsSection","Projects","ProjectsSection","Testimonials","TestimonialsSection","Contact","ContactSection","Footer"].indexOf(t);return r===-1?Number.MAX_SAFE_INTEGER:r}function I1(t,e){const r=String(t||"").toLowerCase(),n=String(e||"");return/\/(?:pages|screens|views)\//.test(r)||/(Page|Screen|View)$/.test(n)?-40:/\/(?:sections|features|layouts?|widgets)\//.test(r)||/(Section|Layout)$/.test(n)?-20:["AppShell","Home","HomePage","LandingPage","Hero","HeroSection"].includes(n)?-10:0}function rie(t,e){const r=String(e||"").replace(/\\/g,"/"),n=Object.entries(t).filter(([g,p])=>{if(!p||p.type!=="file"||p.isBinary)return!1;const y=g.replace(/\\/g,"/"),v=r&&y===r,_=y==="src/App.tsx"||y==="src/App.jsx"||y.endsWith("/src/App.tsx")||y.endsWith("/src/App.jsx");return(v||_)&&Fse.test(String(p.content||""))});if(n.length===0)return null;const s=Object.entries(t).map(([g,p])=>!p||p.type!=="file"||p.isBinary||typeof p.content!="string"?null:tie(g,p.content)).filter(g=>!!g);if(s.length===0)return null;const i=s.filter(({filePath:g,componentName:p})=>p.endsWith("Section")||p.endsWith("Page")||p.endsWith("Screen")||p.endsWith("View")||p.endsWith("Layout")||p==="Header"||p==="Footer"||p==="Hero"||p==="Navbar"||p==="NavBar"||/\/(?:pages|screens|views|sections|features|layouts?)\//i.test(g)),a=(i.length>0?i:s).sort((g,p)=>{const y=I1(g.filePath,g.componentName)-I1(p.filePath,p.componentName);if(y!==0)return y;const v=R1(g.componentName)-R1(p.componentName);return v!==0?v:g.componentName.localeCompare(p.componentName)}).filter((g,p,y)=>y.findIndex(v=>v.componentName===g.componentName)===p);if(a.length===0)return null;const o=a.filter(({componentName:g})=>["Header","Navbar","NavBar"].includes(g)),l=a.filter(({componentName:g})=>g==="Footer"),c=a.filter(({componentName:g})=>!["Header","Navbar","NavBar","Footer"].includes(g)),u=c.length>0?c:a,d=a.map(({importStatement:g})=>g),h=(g,p)=>`${p}<${g} />`,m=[];for(const g of o)m.push(h(g.componentName," "));if(u.length>0){m.push(" <main>");for(const g of u)m.push(h(g.componentName," "));m.push(" </main>")}for(const g of l)m.push(h(g.componentName," "));const b=["import React from 'react';",...d,"","function App() {"," return (",' <div className="min-h-screen">
2117',...m," </div>"," );","}","","export default App;",""].join(` 2118`);return{filePath:n[0][0].replace(/\\/g,"/"),content:b,componentNames:a.map(({componentName:g})=>g),repairKind:"react-entry"}}function N1(t){return IL.some(e=>e.regex.test(t))}function nie(t,e){const r=Qi(t).split("/");r.pop();const n=Qi(e).split("/");for(;r.length>0&&n.length>0&&r[0]===n[0];)r.shift(),n.shift();const s=[...r.map(()=>".."),...n].join("/");return!s||s.startsWith(".")?s||"./":`./${s}`}function sie(t,e){const r=Qi(e||""),n=NL(t),s=Object.entries(t).map(([c,u])=>{if(!u||u.type!=="file"||u.isBinary||typeof u.content!="string")return null;const d=Qi(c),h=r&&d===r,m=n?.has(d),b=/^(?:main|app|game|canvas|script)\.(?:[cm]?[jt]sx?)$/.test(d);return!h&&!m&&!b||!N1(u.content)?null:{filePath:c.replace(/\\/g,"/"),normalizedPath:d}}).filter(c=>!!c);if(s.length===0)return null;const i=Object.entries(t).map(([c,u])=>{if(!u||u.type!=="file"||u.isBinary||typeof u.content!="string")return null;const d=Qi(c);if(d.startsWith("public/")||d.includes("/node_modules/")||!/^(?:src\/|app\/).+\.(?:[cm]?[jt]sx?)$/.test(d)||/\.(test|spec|stories)\.(?:[cm]?[jt]sx?)$/i.test(d)||N1(u.content))return null;const h=u.content.trim(),m=(/^src\/main\.(?:[cm]?[jt]sx?)$/i.test(d)?100:0)+(/^src\/(?:app|game|canvas|scene)\.(?:[cm]?[jt]sx?)$/i.test(d)?60:0)+(/^src\/game\//i.test(d)?40:0)+(/\b(?:document|canvas|requestAnimationFrame|addEventListener|new\s+[A-Z]|export\s+|import\s+)/.test(h)?20:0)+Math.min(20,Math.floor(h.length/500));return{filePath:c.replace(/\\/g,"/"),normalizedPath:d,score:m}}).filter(c=>!!c).sort((c,u)=>u.score-c.score||c.normalizedPath.localeCompare(u.normalizedPath)),a=s.find(c=>c.normalizedPath===r)||s[0],o=i.find(c=>c.normalizedPath!==a.normalizedPath);if(!o)return null;const l=nie(a.filePath,o.filePath);return!l||l==="./"?null:{filePath:a.filePath,content:`import '${l}'; 2119`,componentNames:[o.filePath],repairKind:"plain-entry-bridge"}}const L1=/(?:document\.)?(?:getElementById\(\s*['"`]([A-Za-z][\w:.-]*)['"`]\s*\)|querySelector\(\s*['"`]#([A-Za-z][\w:.-]*)['"`]\s*\))/g;function iie(t,e){return new RegExp(`\\bid\\s*=\\s*(["'])${mu(e)}\\1`,"i").test(t)}function D1(t,e){const r=t.toLowerCase();return r.includes("canvas")||r.includes("game")||/\bgetContext\s*\(\s*['"`]2d['"`]\s*\)|\bCanvasRenderingContext2D\b/i.test(e)?`<canvas id="${t}" width="960" height="540"></canvas>`:`<div id="${t}"></div>`}function oie(t,e){const r=e.map(n=>` ${n}`).join(` 2120`);return/<\/body\s*>/i.test(t)?t.replace(/<\/body\s*>/i,`${r} 2121</body>`):/<\/html\s*>/i.test(t)?t.replace(/<\/html\s*>/i,`<body> 2122${r} 2123</body> 2124</html>`):`${t.trimEnd()} 2125${r} 2126`}function aie(t){const e=hn(t,"index.html");if(!e)return null;const r=Kt(t,e);if(!r.trim())return null;const n=new Map;for(const[s,i]of Object.entries(t)){if(!i||i.type!=="file"||i.isBinary||typeof i.content!="string")continue;const a=Qi(s);if(a.startsWith("node_modules/")||a.startsWith("dist/")||a.startsWith("build/")||!/\.(?:[cm]?[jt]sx?)$/i.test(a))continue;L1.lastIndex=0;let o;for(;o=L1.exec(i.content);){const c=String(o[1]||o[2]||"").trim();!c||iie(r,c)||n.has(c)||n.set(c,{element:D1(c,i.content),sourceFile:a})}/querySelector\(\s*['"`]canvas['"`]\s*\)|getElementsByTagName\(\s*['"`]canvas['"`]\s*\)/i.test(i.content)&&!/<canvas\b/i.test(r)&&!n.has("gameCanvas")&&n.set("gameCanvas",{element:D1("gameCanvas",i.content),sourceFile:a})}return n.size===0?null:{filePath:e,content:oie(r,[...n.values()].map(s=>s.element)),targets:[...n.entries()].map(([s,i])=>({id:s,sourceFile:i.sourceFile}))}}const M1={background:"#f8fafc",foreground:"#0f172a",border:"#e2e8f0",input:"#cbd5e1",ring:"#6366f1",card:"#ffffff","card-foreground":"#0f172a",popover:"#ffffff","popover-foreground":"#0f172a",primary:"#4f46e5","primary-foreground":"#ffffff",secondary:"#e2e8f0","secondary-foreground":"#0f172a",muted:"#f1f5f9","muted-foreground":"#64748b",accent:"#eef2ff","accent-foreground":"#312e81",destructive:"#ef4444","destructive-foreground":"#ffffff",text:"#0f172a"},O1=/\b(?:bg|text|border|ring|outline|divide|placeholder|from|via|to|accent|caret|decoration)-([a-z][a-z0-9-]*)\b/g,lie=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","tailwind.config.cjs"];function cie(t){const e=Kt(t,"package.json"),r=/["']tailwindcss["']\s*:/.test(e),n=lie.find(u=>Kt(t,u).trim());if(!r&&!n)return null;const s=new Set;for(const[u,d]of Object.entries(t)){const h=Qi(u);if(!d||d.type!=="file"||d.isBinary||typeof d.content!="string"||h.startsWith("node_modules/")||h.startsWith("dist/")||!/\.(?:css|html|[jt]sx?)$/i.test(h))continue;let m;
2126for(O1.lastIndex=0;m=O1.exec(d.content);){const b=m[1];b in M1&&s.add(b)}}if(s.size===0)return null;const i=n||"tailwind.config.js",a=[...s].sort(),l=`{ 2127 content: ['./index.html', './src/**/*.{js,jsx,ts,tsx}', './app/**/*.{js,jsx,ts,tsx}'], 2128 theme: { 2129 extend: { 2130 colors: { 2131${a.map(u=>` ${JSON.stringify(u)}: ${JSON.stringify(M1[u])},`).join(` 2132`)} 2133 }, 2134 }, 2135 }, 2136 plugins: [], 2137}`,c=i.endsWith(".cjs")?`module.exports = ${l}; 2138`:`export default ${l}; 2139`;return{filePath:i,content:c,tokenNames:a}}const LL=x.memo(({conversationId:t,workspaceId:e,description:r,initialMessages:n,restoredFromSnapshot:s,storeMessageHistory:i,importChat:a,exportChat:o,metadata:l,updateChatMestaData:c,ensureWorkspaceIdentity:u})=>{Mj();const d=x.useRef(null),[h,m]=x.useState(n.length>0),[b,g]=x.useState([]),[p,y]=x.useState([]),[v,_]=x.useState([]),w=x.useRef([]),C=x.useRef([]),A=x.useRef([]),E=x.useRef(null),[S]=x.useState(()=>`draft-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`);x.useEffect(()=>{w.current=b},[b]),x.useEffect(()=>{C.current=p},[p]),x.useEffect(()=>{A.current=v},[v]);const[k,O]=jO(),[T,R]=x.useState(!1),[N,M]=x.useState("build"),[B,U]=x.useState(!1),[X,oe]=x.useState(0),L=We(j.files),F=x.useMemo(()=>Kt(L,fg),[L]),V=x.useMemo(()=>Kt(L,OM),[L]),Z=x.useMemo(()=>wM(F),[F]),K=x.useMemo(()=>SM(F),[F]),ie=x.useMemo(()=>CM(V),[V]),se=x.useMemo(()=>AM({config:Z,localSecretValue:ie.secretKey,localWebhookSecretValue:ie.webhookSecret}),[ie.secretKey,ie.webhookSecret,Z]),fe=!se.connected&&Z?.setupRequired===!0,Y=x.useCallback(P=>!se.connected&&Xse(P)?!1:Yse(P),[se.connected]),I=x.useMemo(()=>fx(K),[K]),z=We(j.previewStarting),q=We(j.restoreProgress),ae=We(j.workspacePersistenceRequest),ee=We(j.artifacts),le=We(j.activeProgressMessageId),ve=We(j.ignoredProgressMessageIds),ye=We(j.lastFileActionActivityAt),[Ae,we]=x.useState(void 0),pe=We(j.alert),Ye=We(j.deployAlert),{promptId:ft,autoSelectTemplate:pt,contextOptimizationEnabled:Lt}=JD(),[nt,xt]=x.useState(void 0),[ct,_r]=x.useState(()=>"qwen3.6-plus"),[ht,Pe]=x.useState(()=>({name:"Qwen",label:"Qwen",staticModels:[{name:"qwen3.6-plus",label:"Qwen 3.6 Plus",provider:"Qwen",maxTokenAllowed:32768},{name:"qwen3-coder-plus",label:"Qwen Max",provider:"Qwen",maxTokenAllowed:32768}]})),{showChat:be,previewLocked:Te,historyRestoring:Ne,backgroundHomeActive:Fe}=We(Ve),Fr=We(j.showWorkbench),Jr=We(j.previews),Dt=We(On),Yt=We(fO),[Os,ci]=BO(),[Yn,$n]=x.useState({}),[lt,bs]=x.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/newsletter")?"discuss":"build"),[wn,Bn]=x.useState(null),[an,vs]=x.useState(!1),[ys,Fn]=x.useState(0),[Ir,Wn]=x.useState(null),[Hn,is]=x.useState(!1),[rn,Jt]=x.useState(null);We(TD);const xr=x.useRef(0),Mt=x.useRef(null),Gs=x.useRef(0),ir=x.useRef(0),[Ai,Xn]=x.useState(null),os=x.useRef(null),[Ur,ui]=x.useState(null),nn=x.useRef(null),St=x.useRef("idle"),Ei=x.useRef(new Map),Tn=x.useRef(null),fr=x.useRef(0),Sn=x.useRef(null),kr=x.useRef(null),Ot=x.useRef(0),Or=x.useRef(!1),zr=x.useRef(!1),Pr=x.useRef(0),as=x.useRef(null),$i=x.useRef(null),jt=x.useRef(null),_s=x.useRef(null),Rn=x.useRef(null),jr=x.useRef(null),wr=x.useRef(null),In=x.useRef(null),Xt=x.useRef(null),ur=x.useRef(null),di=x.useRef(null),ls=x.useRef(null),ln=x.useRef(""),Gr=x.useRef(""),Bi=x.useRef(""),br=x.useRef(null),Tr=x.useRef(""),Vt=x.useRef(null),Qr=x.useRef(null),Ar=x.useRef(null),cs=x.useRef(null),Ut=x.useRef(""),xs=x.useRef(new Set),Nr=x.useRef(null),js=x.useRef(null),pn=x.useRef(0),te=x.useRef(null),De=x.useRef(0),je=x.useRef(null);x.useRef(null);const Ge=x.useRef(Ne),$t=x.useRef(Fe),qe=x.useRef(null),Bt=x.useRef(null),Lr=x.useRef(new Map),Nn=x.useRef(!1),Ln=x.useRef(null),qs=x.useRef(new Map),Sr=x.useRef(!1),or=x.useRef(null),Ks=x.useRef(null),Ys=x.useRef(null),Vr=x.useRef(null),Xs=x.useRef(null),ki=x.useRef(null),ws=x.useRef(null),Dn=x.useRef(0),Fi=x.useRef(0),G=x.useRef(!1),ce=x.useRef(null),xe=x.useRef(null),Je=x.useRef(null),It=x.useRef(null),wt=x.useRef(""),Gt=x.useRef(""),[Qt,Nt]=x.useState(!1),[pr,Ft]=x.useState(!1),[ot,qt]=x.useState(null),Zt=x.useRef(!1),mn=x.useRef(!1),cn=x.useRef(null),Ss=x.useRef(""),Js=x.useRef(""),ro=x.useRef(!0),Wi=x.useRef(""),rr=typeof window<"u"?window.location.pathname:"",Dr=rr.startsWith("/newsletter"),wa=k.toString(),Sa=x.useMemo(()=>({pathname:rr,search:wa?`?${wa}`:""}),[rr,wa]),Ca=x.useMemo(()=>Dr?lp(Sa,l?.newsletterContext):null,[Dr,l?.newsletterContext,Sa]),Qs=x.useMemo(()=>Dr?lp(Sa):null,[Dr,Sa]),Aa=typeof window<"u"?new URLSearchParams(window.location.search).get("chat")?.trim():"",pl=!!(k.get("chat")?.trim()||Aa),dc=rr==="/"&&!t&&!pl,us=Ve.get().started,Uo=us===!0||us!==!1&&h||n.length>0||!!t||pr,zo=T||B||Ne||Te||Hn||ot?.status==="running"||Fr&&us===!0,_o=dc&&!zo&&!Uo,$r=e||t||S,Su=void 0,ds=x.useMemo(()=>{const P=k.get("chat")?.trim()||Aa;return P?`${rr||"/"}?chat=${P}`:rr||"/"},[rr,k,Aa]),Pi=x.useMemo(()=>EM(L)||rr.startsWith("/app")||rr.startsWith("/apps"),[rr,L]),no=x.useMemo(()=>kM(L),[L]),xo=x.useMemo(()=>PM(L),[L]);x.useEffect(()=>{const P=_o?!1:Uo||zo;m(D=>D===P?D:P),Ve.setKey("started",P),_o&&Ve.get().showChat===!1&&Ve.setKey("showChat",!0),console.debug("[chat.history] conversation state synchronized",{conversationId:t??null,initialMessageCount:n.length,hasConversationState:Uo,hasPendingConversationSeed:pr,started:P,forcedLandingPrompt:_o})},[t,zo,Uo,pr,n.length,_o]);const mt=rr.startsWith("/builder")||rr.startsWith("/builder-app"),Pt=rr==="/"||rr==="/app"||rr==="/apps"||rr.startsWith("/app/")||rr.startsWith("/apps/")||rr.startsWith("/chat/"),ge=Ve.get().backgroundHomeReturnPath||rr||"/",Ue=ap(ge)==="site"?"genie-builder":"genie ai",Ct=!!Yt&&Yt.canWriteProjects===!1&<==="build"&&(Pt||mt)?"Viewer access can open this workspace, but cannot create or edit apps.":void 0;x.useEffect(()=>{Dr&<!=="discuss"&&bs("discuss")},[lt,Dr]),x.useEffect(()=>{if(!Dr||!Qs?.workspace_id||!Qs.publication_id||!Qs.return_url)return;const P=l?.newsletterContext;if(P?.workspace_id===Qs.workspace_id&&P?.publication_id===Qs.publication_id&&P?.workspace_name===Qs.workspace_name&&P?.publication_name===Qs.publication_name&&P?.return_url===Qs.return_url&&P?.handoff_token===Qs.handoff_token)return;const D={...l||{},newsletterContext:Qs.newsletterContext};ip.set(D),c?.(D).catch($=>
2139{mr.warn("Failed to persist newsletter Studio context",$)})},[Dr,l,Qs,c]);const nr=x.useCallback(()=>{if(typeof window<"u"&&(Pt||mt)){window.dispatchEvent(new CustomEvent("cms:open-workspace-upgrade"));return}typeof window<"u"&&(window.location.href="/pricing")},[mt,Pt]);x.useEffect(()=>{!h||Ne||!Pt&&!mt||(j.showWorkbench.get()||j.showWorkbench.set(!0),j.currentView.get()==="preview"&&j.previews.get().length===0&&j.currentView.set("code"))},[h,Ne,mt,Pt,t,n.length]),x.useEffect(()=>{const P=Dt?.email||Dt?.username||null;It.current!==P&&(It.current=P,w.current=[],C.current=[],A.current=[],g([]),y([]),_([]))},[Dt?.email,Dt?.username]);const Cn=P=>typeof P=="string"?P:P instanceof URL?P.toString():typeof Request<"u"&&P instanceof Request?P.url:"[unknown-request-target]",Ti=P=>{const D=P instanceof Error?P.message:String(P??"");return/authentication required|sign in|not authenticated|not authorized/i.test(D)},Un=P=>P.replace(/\s+/g," ").trim().slice(0,140),so=x.useCallback((P,D,$)=>{const W=D==="repair"&&$?.resumeExisting,J=D==="repair"?"REPAIRING":"GENERATING";W||(Sn.current=null,kr.current=null,St.current="idle",Ot.current=0,j.frozenProgress.set(null)),j.setBuilderLifecyclePhase(J),qt(re=>$?.resumeExisting&&re&&re.status!=="canceled"?{...re,requestMode:D,promptPreview:Un(P),status:"running",phase:J,maxProgressPercent:re.maxProgressPercent??0,error:null,completedAt:null}:{jobId:`build-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,startedAt:Date.now(),requestMode:D,promptPreview:Un(P),maxProgressPercent:0,status:"running",phase:J,repairIteration:0,error:null,completedAt:null})},[]),gn=x.useCallback((P,D)=>{qt($=>$&&{...$,phase:P,status:RD(P),repairIteration:D?.incrementRepairIteration?$.repairIteration+1:$.repairIteration,error:D&&"errorMessage"in D?D.errorMessage??null:$.error,completedAt:P==="FAILED"||P==="CANCELED"||P==="PREVIEW_RUNNING"?Date.now():null})},[]),hi=x.useCallback((P,D)=>{qt($=>$&&{...$,status:P,phase:P==="failed"?"FAILED":P==="canceled"?"CANCELED":P==="ready"?"READY_FOR_PREVIEW":$.phase,error:D??null,completedAt:P==="running"?null:Date.now()})},[]);x.useEffect(()=>{j.setBuilderLifecyclePhase(ot?.phase||"IDLE")},[ot?.phase]),x.useEffect(()=>{(ot?.phase==="GENERATING"||ot?.phase==="STREAM_COMPLETE")&&(ki.current=null)},[ot?.phase]);const ml=x.useCallback(()=>{w.current=[],C.current=[],A.current=[],g([]),y([]),_([])},[]),Cu=x.useCallback(P=>{g(D=>{const $=D.filter((W,J)=>J!==P);return w.current=$,$}),y(D=>{const $=D.filter((W,J)=>J!==P);return C.current=$,$}),_(D=>{const $=D.filter((W,J)=>J!==P);return A.current=$,$})},[]),Ea=x.useCallback(async(P,D={})=>{const $=await e2(P.id,{appId:$r,workspaceId:$r}),W=$.asset||P,J=$.publicUrl||W.publicUrl;if(!J)throw new Error("The selected asset could not be published to a public R2 URL.");const re=W.assetType||P.assetType||Lx(W.mimeType),de=!D.displayFile&&re==="image"?await t2(W):null,_e=Jre(W,re),Re=D.displayFile||de?.file||new File([new Blob([])],W.filename||`${W.id}`,{type:_e}),Le={...xO(W),mediaKind:re,workspaceFilePath:null,workspacePublicUrl:null,publicUrl:J,signedUrl:null,signedUrlStrategy:"public-r2-url"};return{file:Re,previewUrl:r2(W,D.previewUrl||de?.previewUrl),reference:Le}},[$r]),Gm=x.useCallback(async P=>{const D=P.filter(J=>J.type.startsWith("image/")||J.type.startsWith("video/")||J.type.startsWith("audio/"));if(D.length===0)return;const $=E.current,W=(async()=>{$&&await $;const J=Math.max(0,vi-A.current.length);if(J<=0)return Se.info(`You can attach up to ${vi} assets to a prompt right now.`),[];const re=D.slice(0,J);D.length>re.length&&Se.info(`Only the first ${J} asset${J===1?"":"s"} will be attached.`);const de=t?"uploads":"temp",_e=await Promise.all(re.map(He=>nv(He,{workspaceId:$r,category:de,source:"upload"}))),Re=await Promise.all(_e.map(He=>Ea(He.asset,{previewUrl:He.previewUrl,displayFile:He.composerFile}))),Le=Re.map(He=>He.file),at=Re.map(He=>He.previewUrl),bt=Re.map(He=>He.reference),Xe=[...w.current,...Le],vt=[...C.current,...at],vr=[...A.current,...bt];return w.current=Xe,C.current=vt,A.current=vr,g(Xe),y(vt),_(vr),bt})();E.current=W;try{await W}finally{E.current===W&&(E.current=null)}},[$r,t,Ea]),qm=x.useCallback(async P=>{if(A.current.length>=vi){Se.info(`You can attach up to ${vi} assets to a prompt right now.`);return}const D=await Ea(P),$=[...w.current,D.file],W=[...C.current,D.previewUrl],J=[...A.current,D.reference];w.current=$,C.current=W,A.current=J,g($),y(W),_(J)},[Ea]),ne=x.useCallback(async P=>{const D=E.current;D&&await D;const $=P?.uploadedFiles??w.current,W=P?.imageDataList??C.current,J=P?.assetReferences??A.current,re=Math.min(vi,Math.max($.length,W.length,J.length));if(re===0)return[];const de=J.slice(0,vi);if(de.length>=re)return de.slice(0,re);const _e=[];for(let vt=de.length;vt<re;vt++){const vr=$[vt],He=W[vt]||null,At=vr||(He?.startsWith("data:")?await Qre(He,vt):null);At&&_e.push({file:At,previewUrl:He})}if(_e.length===0)return de;const Re=t?"uploads":"temp",Le=await Promise.all(_e.map(vt=>nv(vt.file,{workspaceId:$r,category:Re,source:"upload"}))),bt=(await Promise.all(Le.map((vt,vr)=>Ea(vt.asset,{previewUrl:_e[vr]?.previewUrl||vt.previewUrl,displayFile:vt.composerFile})))).map(vt=>vt.reference),Xe=[...A.current,...bt].slice(0,vi);return A.current=Xe,_(Xe),Xe.slice(0,re)},[$r,t,Ea]),me=x.useCallback((P,D)=>wO(P,D??A.current),[]),Ee=x.useCallback(async P=>{const D=P?.uploadedFiles??w.current,$=P?.imageDataList??C.current,W=P?.assetReferences??A.current,J=D.slice(0,vi),re=$.slice(0,vi),de=W.slice(0,vi);return{uploadedFileCount:J.length,imageDataCount:re.length,assetReferenceCount:de.length,attachmentCount:0,attachmentContentTypes:[],attachments:void 0}},[]),Ie=x.useCallback(P=>{const D=P.trim();if(!D)return;const $=yg();sv($),kO({route:$,prompt:D,timestamp:Date.now()})},[]),$e=x.useCallback(()=>{Se.dismiss(r1),Ve.get().previewAuthNotice!==null&&Ve.setKey("previewAuthNotice",null)},[]),Be=x.useCallback(async()=>{let P=On.get(),D=String(P?.email||"").trim();if(!D){try{await rv()}catch{}P=On.get(),D=String(P?.email||"").trim()}const $=D?await wx({tokenType:"id"})||await wx({forceRefresh:!0,tokenType:"id"}):null;return!D||!$?(On.set(null),{currentUser:null,email:null}):{currentUser:P,email:D}},[]),ze=x.useCallback((P,D)=>{const $=P.trim();$&&(Ie($),wt.current=$),Ve.setKey("previewAuthNotice",{title:"Sign in to continue",description:D?.description||"Your session has ended. Sign in to continue this workspace request. Your last prompt is saved and will resume automatically after you log in."}),Ve.setKey("previewLocked",!1),j.abortActiveGenerationProgress(),R(!1),U(!1),oe(0),Ft(!1),is(!1),hi("failed","Sign in required to continue."),vs(!0),D?.showToast!==!1&&Se.info("Please sign in to continue.",{toastId:r1})},[hi,Ie]),Qe=x.useCallback(async()=>{let P=On.get(),D=P?.email;if(!D){try{await rv()}catch{}P=On.get(),D=P?.email}return{currentUser:P,email:D}},[]),gt=x.useCallback(async P=>{if(Ti(P))return!0;const D=P instanceof Error?P.message:String(P??"");if(!D||!/<!doctype html|<html|unexpected token '<'|invalid workers preview configuration|workers preview configuration|cloudflare/i.test(D))return!1;const{email:W}=await Be();return!W},[Be]);x.useEffect(()=>{Dt&&($e(),xt(P=>P&&(P.errorType==="authentication"||/sign in|authentication required/i.test(P.de
2139scription||"")?void 0:P)))},[Dt,$e]),x.useEffect(()=>()=>{te.current!==null&&(window.clearTimeout(te.current),te.current=null)},[]);const Q=x.useCallback((P,D)=>{const $=Mt.current,W=new Date().toISOString();if(!$){if(D){console.log(`[chat.client][${W}] ${P}`,D);return}console.log(`[chat.client][${W}] ${P}`);return}const J=Date.now()-$.startedAt;if(D){console.log(`[chat.client][${W}][req:${$.id}][+${J}ms] ${P}`,D);return}console.log(`[chat.client][${W}][req:${$.id}][+${J}ms] ${P}`)},[]),dt=x.useCallback(P=>{if(!Ve.get().previewLocked)return;const $=j.builderLifecyclePhase.get();if($==="GENERATING"||$==="STREAM_COMPLETE"||$==="INSTALLING_DEPENDENCIES"||$==="BUILDING"||$==="BUILD_FAILED_AGGREGATED"||$==="REPAIRING"||$==="BUILD_VERIFICATION"||$==="FAILED"){const J=$==="REPAIRING",re=j.previews.get().filter(de=>de.ready).length;Q(J?hs.PREVIEW_LOCK_RETAINED_ACTIVE_REPAIR:"preview_lock_blocked_active_build_phase",{reason:P,phase:$,readyPreviewCount:re,previewCount:j.previews.get().length,message:J?"Preview lock retained: active repair cycle in progress - preview must stay locked":"Preview remains locked: build/repair/validation cycle in progress"});return}Ve.setKey("previewLocked",!1),Q("preview_lock_released",{reason:P})},[Q,j.builderLifecyclePhase]),rt=x.useCallback((P,D)=>{Q(P,D),console.log(`[chat.attachments] ${P} uploadedFiles=${D.uploadedFileCount} imageData=${D.imageDataCount} assetReferences=${D.assetReferenceCount??0} attachments=${D.attachmentCount} contentTypes=${D.attachmentContentTypes.join(",")||"none"}`)},[Q]),Br=x.useCallback(async P=>{const D=new URLSearchParams({product_type:P,sync:"1"});try{const $=await Fl(`/api/runtime/usage?${D.toString()}`,{method:"GET"}),{payload:W,responseText:J}=await Kre($);if(!$.ok){const de=Yre($,W,J);return console.warn("[Chat] Runtime capacity verification failed.",{status:$.status,statusText:$.statusText,code:W?.code,message:de}),{allowed:!1,message:de,summary:W?.report?.summary||null,code:W?.code||"runtime_usage_failed"}}Array.isArray(W?.availableProducts)&&v2(W.availableProducts),W?.report&&y2(W.report);const re=W?.report?.summary||null;return Px(re)?{allowed:!1,message:Tx(re),summary:re,code:"token_limit_reached"}:{allowed:!0,message:null,summary:re,code:null}}catch($){return Ti($)?{allowed:!1,message:"Please sign in to continue.",summary:null,code:"auth_required"}:(console.warn("[Chat] Failed to verify runtime capacity before workspace request.",$),{allowed:!1,message:"Unable to verify your AI token balance. Please refresh and try again before creating an app.",summary:null,code:"runtime_usage_failed"})}},[]),sn=x.useCallback((P,D)=>{const $=xr.current+1;xr.current=$;const W=Gs.current,J=ir.current;return Vt.current=null,Ar.current=null,Qr.current=null,cs.current=null,Ut.current="",Mt.current={id:$,startedAt:Date.now(),promptPreview:Un(P),isFollowUp:D,baselineAssistantCount:W,baselineProgressCount:J,firstProgressLogged:!1,firstAssistantLogged:!1},Q("request_started",{isFollowUp:D,promptPreview:Un(P),baselineAssistantCount:W,baselineProgressCount:J}),$},[Q]),{messages:Me,isLoading:yt,input:ka,handleInputChange:Km,setInput:Pa,stop:Au,append:Ym,setMessages:Ta,reload:Eu,error:DL,data:Zs,setData:ku,addToolResult:ML}=xj({api:"/api/chat",id:t,fetch:async(P,D)=>{Q("api_fetch_dispatch",{url:Cn(P),method:D?.method||"POST",productType:Ue});try{const $=await tZ(Fl,P,D,{onRetry:({attempt:W,delayMs:J,status:re,message:de})=>{Q("api_fetch_retry_scheduled",{attempt:W,delayMs:J,status:re,message:de})}});return Q("api_response_headers_received",{status:$.status,ok:$.ok}),Wa.logProvider("Chat API request dispatched",{component:"Chat",action:"request_dispatch",model:ct,provider:ht.name,status:$.status}),$}catch($){throw $}},body:{apiKeys:Yn,files:L,promptId:ft,contextOptimization:Lt,chatMode:lt,promptMode:Dr?n2:void 0,newsletterContext:Dr?Ca?.newsletterContext:void 0,productType:Ue,appId:e||t||$r,chatId:e||t||$r,designScheme:Ae,maxLLMSteps:5},sendExtraMessageFields:!0,onError:P=>{if(G.current){mr.debug("Ignoring stale chat error callback after history sync");return}const D=rw(P?.message);D?.type==="generation_provider_unavailable"&&console.error("Generation request failed",D.diagnostics||{stage:"unknown"}),Q("request_error",{message:D?.message||P?.message||"Unknown error",type:D?.type||void 0}),!(D?.type===pv&&zL(D))&&(or.current=null,Vt.current=null,Ar.current=null,Ut.current="",Ks.current=null,io(),R(!1),U(!1),oe(0),hi("failed",D?.message||P?.message||"Build failed."),Mt.current=null,Ve.get().previewLocked&&Ve.setKey("previewLocked",!1),(async()=>
2139{if(await gt(P)){ze(wt.current,{description:"Your session expired while Genie was processing this workspace request. Sign in to continue, and your last prompt will resume automatically."});return}VL(P,"chat")})())},onFinish:async(P,D)=>{if(G.current){mr.debug("Ignoring stale chat finish callback after history sync");return}const $=D.usage,W=Gi(P),J=N==="repair"?ene(P):W,re=Mt.current?.id??xr.current;let de=null;if(N==="repair"){const He=P,At=Array.isArray(He.parts)?He.parts:[],Wt=At.map(qr=>qr&&typeof qr=="object"&&"type"in qr?String(qr.type):"unknown"),Wr=At.map(qr=>qr&&typeof qr=="object"&&"type"in qr&&qr.type==="text"&&"text"in qr?String(qr.text||"").length:0),Rt=typeof He.content=="string"?"string":Array.isArray(He.content)?"array":He.content==null?"null":typeof He.content,kt=typeof He.content=="string"?He.content.length:0;de={assistantTextLength:W.length,assistantPayloadLength:J.length,assistantTextPreview:W.slice(0,500),assistantTextTail:W.length>500?W.slice(-200):void 0,assistantPayloadPreview:J.slice(0,500),assistantPayloadTail:J.length>500?J.slice(-200):void 0,messageContentType:Rt,messageContentLength:kt,messagePartCount:At.length,messagePartTypes:Wt,messagePartTextLengths:Wr,messageReasoningLength:typeof He.reasoning=="string"?He.reasoning.length:0,messageAnnotationCount:Array.isArray(He.annotations)?He.annotations.length:0,finishReasonFromUsage:D?.finishReason??void 0,usage:$||void 0},Q("qwen_repair_response_received",{requestId:re,...de})}let _e=!1;(N==="repair"||N==="update")&&(_e=await HL(J,re),Q("qwen_repair_fixes_applied_result",{requestId:re,targetedRepairsApplied:_e,assistantPayloadLength:J.length,activeRequestMode:N})),Q("request_finished",{usage:$||void 0,assistantMessageChars:J.length});const Re=C1(J),Le=Re.contentLength===0&&Re.fileActionCount===0&&Re.targetedRepairBlockCount===0&&Re.shellActionCount===0&&Re.startActionCount===0;let at=St.current,bt=!1;if(Q("assistant_payload_diagnostics",Re),lt==="build"&&(Pt||mt)&&Le){const He=kl(Me),At=Mt.current?.promptPreview||"",Wt=kc(At),Wr=N==="repair"||Wt?"repair":ot?.requestMode??N,Rt=Bt.current,kt=Gt.current||(kc(wt.current)?"":wt.current)||He||(Wt?"":At)||`${Wr}-empty-response`,qr=Wt||N==="repair"||Wr==="repair"||kc(wt.current)||!!Rt,Ri=Wr==="build"&&N==="build"&&!qr,$s=`empty-initial-build::${Tt(kt).slice(0,700)}`,Ma=qs.current.get($s)??0;if(Ri){if(Ma<qb){const bn=Ma+1;qs.current.set($s,bn),St.current="idle",qe.current=null,Bt.current=null,Or.current=!1,zr.current=!1,Nt(!1),M("build"),R(!0),U(!0),oe(0),so(kt,"build",{resumeExisting:!0});const Ui=sn(kt,!0);or.current={requestId:Ui},Dn.current+=1,G.current=!1,Ve.setKey("aborted",!1),j.resumeIncomingProgress(),Q("assistant_payload_empty_build_retrying_generation",{requestId:re,retryRequestId:Ui,retryAttempt:bn,maxRetries:qb,signature:$s.slice(0,240),message:"Initial build returned no files. Retrying the original generation request as build mode, not repair mode."}),window.setTimeout(()=>{Eu().catch(zn=>{const fi=zn instanceof Error?zn.message:"Retry after empty generation response failed.";mr.warn("Failed to retry empty initial build response",zn),hi("failed",fi),j.abortActiveGenerationProgress(),j.setBuilderLifecyclePhase("FAILED"),or.current=null,Mt.current=null,Ve.setKey("previewLocked",!1),R(!1),U(!1),oe(0)})},0);return}St.current="suppressed_depth",qe.current=null,or.current=null;const As="The model returned an empty initial generation response twice, so no app files were created. Please retry the prompt.";hi("failed",As),j.abortActiveGenerationProgress(),j.setBuilderLifecyclePhase("FAILED"),Ve.setKey("previewLocked",!1),R(!1),U(!1),oe(0),xt({type:"error",title:"Ap
2139p generation did not start",description:As,provider:ht.name,errorType:"network"}),Mt.current=null,Q("assistant_payload_empty_build_retry_limit_reached",{requestId:re,retryCount:Ma,maxRetries:qb,signature:$s.slice(0,240),message:"Initial build kept returning no files. Stopped instead of converting the request into an automatic repair loop."});return}const Jn=qr?Ot.current+1:0,Go=qr&&Jn>=s1,on=Wr==="repair"&&!!Rt?.prompt&&!!Rt?.signature,vl=on&&Rt?FL({originalRequest:He,previousRepairPrompt:Rt.prompt,previousRepairSource:Rt.source}):BL(He,Wr),ti=on&&Rt?`empty-assistant-response-fallback::${Tt(Rt.signature).slice(0,900)}`:`empty-assistant-response::${Wr}::${Tt(kt).slice(0,700)}`,yl=on?`Empty ${Wr} repair response - retrying with retained diagnostics and full-file instructions`:He.slice(0,160)||`Empty ${Wr} response`;let Ii=!1;Go?(St.current="suppressed_depth",Q("assistant_payload_empty_response_limit_reached",{requestId:re,requestMode:Wr,emptyRepairResponseCount:Jn,maxEmptyRepairResponses:s1,provider:ao,model:Jo})):Ii=ws.current?.({prompt:vl,signature:ti,source:"assistant_payload:empty_response",messagePreview:yl,maxAttempts:1})??!1,Ii&&(or.current=null),at=St.current,bt=at==="queued"||at==="sent",Q("assistant_payload_empty_response_detected",{requestId:re,requestMode:Wr,queuedAutoRepair:Ii,autoRepairDispatchStatus:at,autoRepairScheduled:bt,hasLatestUserPrompt:!!He,escalatedFromPreviousRepair:on,emptyRepairResponseCount:Jn,provider:ao,model:Jo,stoppedAfterEmptyResponses:Go})}Re.targetedRepairBlockCount===0&&!Re.hasBoltAction&&(Re.actionLikeLineCount>0||Re.codeLikeLineCount>=4||Re.containsCodeFence&&Re.codeLikeLineCount>=2)&&Q("assistant_payload_missing_bolt_actions",{reason:"Model returned action-like text but no <boltAction> tags",...Re}),lt==="build"&&(Pt||mt)&&Re.fileActionCount===0&&Re.targetedRepairBlockCount===0&&Q("assistant_payload_no_file_actions_final",{...Re,repairResponseDebug:de?{assistantTextLength:de.assistantTextLength,assistantPayloadLength:de.assistantPayloadLength,assistantTextPreview:de.assistantTextPreview,assistantTextTail:de.assistantTextTail,assistantPayloadPreview:de.assistantPayloadPreview,assistantPayloadTail:de.assistantPayloadTail,messageContentType:de.messageContentType,messageContentLength:de.messageContentLength,messagePartCount:de.messagePartCount,messagePartTypes:de.messagePartTypes,messagePartTextLengths:de.messagePartTextLengths,messageReasoningLength:de.messageReasoningLength,messageAnnotationCount:de.messageAnnotationCount,finishReasonFromUsage:de.finishReasonFromUsage}:null});const Xe=N==="repair"||kc(Mt.current?.promptPreview||"")||kc(wt.current)||!!Bt.current;Xe&&(Re.boltActionCount===0&&!(Re.targetedRepairBlockCount>0&&_e)?Ot.current+=1:Ot.current=0);const vt=Or.current||Xe;br.current={requestId:re},ku(void 0),Mt.current=null,(Le&&j.builderLifecyclePhase.get()==="REPAIRING"&&!bt?Vo({requestId:re,source:"assistant_empty_response",repairIteration:ot?.repairIteration??0,summary:"Automatic repair returned no content and no file changes, so preview has been unlocked with the current workspace state instead of staying stuck in repair mode.",buildIssueCount:0,validationIssueCount:0,importIssueCount:0}):!1)?Q("repair_empty_response_recovered",{requestId:re,requestMode:N,autoRepairDispatchStatus:at}):vt?WL():(R(!1),U(!1),oe(0),(lt!=="build"||!Pt&&!mt)&&dt("request_finished_non_build")),$&&(console.log("Token usage:",$),Wa.logProvider("Chat response completed",{component:"Chat",action:"response",model:ct,provider:ht.name,usage:$,messageLength:W.length})),mr.debug("Finished streaming")},initialMessages:n,initialInput:wc.get(ju)||""});x.useEffect(()=>{if(mn.current||rr!=="/")return;mn.current=!0;const P=hO();P&&(Pa(P),window.requestAnimationFrame(()=>{d.current?.focus({preventScroll:!0}),d.current?.setSelectionRange(P.length,P.length)}))},[rr,Pa]),x.useEffect(()=>{const P=[...Me].reverse().find(W=>W.role==="assistant"),D=Zre(P);if(!D)return;const $=`${D.requestId||"none"}:${D.createdAt}:${D.tokensUsed}`;Bi.current!==$&&(Bi.current=$,Rx(D))},[Me]),x.useMemo(()=>new Set(xd(Me||[]).filter(P=>P.annotations?.includes("hidden")).map(P=>P.id)),[Me]),x.useEffect(()=>{Gs.current=Me.filter(P=>P.role==="assistant").length},[Me]),x.useEffect(()=>{if(t||n.length>0){Ft(!1);return}!T&&!B&&!Ne&&Me.length===0&&Ft(!1)},[B,t,T,Ne,n.length,Me.length]),x.useEffect(()=>{if(!Zs||Zs.length===0){ir.current=0;return}ir.current=Zs.filter(P=>typeof P=="object"&&P!==null&&"type"in P&&P.type==="progress").length},[Zs]),x.useEffect(()=>{const P=Mt.current;if(!P||!Zs||Zs.length===0)return;const D=Zs.filter(J=>typeof J=="object"&&J!==null&&"type"in J&&J.type==="progress");if(D.length<=P.baselineProgressCount)return;const $=D[D.length-1],W=`${$.label}:${$.status}:${$.order??""}`;if(P.lastProgressKey!==W){if(P.lastProgressKey=W,!P.firstProgressLogged){P.f
2139irstProgressLogged=!0,Q("first_progress_event",{label:$.label,status:$.status,message:$.message||""});return}Q("progress_event",{label:$.label,status:$.status,message:$.message||""})}},[Zs,Q]),x.useEffect(()=>{const P=Mt.current;if(!P||P.firstAssistantLogged)return;const D=Me.filter(J=>J.role==="assistant");if(D.length<=P.baselineAssistantCount)return;const $=D[D.length-1],W=Gi($).length;W!==0&&(P.firstAssistantLogged=!0,Q("first_assistant_content",{assistantMessages:D.length,assistantContentLength:W}))},[Me,Q]),x.useEffect(()=>{const P=k.get("prompt")?.trim();if(!P||yt||T||B||!nn.current)return;const D=`${rr||"/"}::${P}`;if(xe.current===D)return;xe.current=D,lt==="build"&&(Pt||mt)&&(Ft(!0),m(!0),Ve.setKey("backgroundHomeActive",!1),Ve.setKey("backgroundHomeReturnPath",""),Ve.setKey("showChat",!0),Ve.setKey("started",!0),j.showWorkbench.set(!0),j.currentView.set("code"),j.setPreviewDevice("responsive"));const $=new URLSearchParams(k);$.delete("prompt"),O($,{replace:!0}),h||j.setGeneratedProjectKind(sw(P,"app")),G.current=!1;const J=QD().map(de=>de.dataUrl),re=J.length>0?{imageDataList:J}:void 0;nn.current(void 0,P,re).catch(de=>{mr.error("Failed to dispatch initial route prompt",de),xe.current=null})},[B,lt,h,rr,T,mt,yt,Pt,k,O]);const{enhancingPrompt:OL,promptEnhanced:jL,enhancePrompt:$L,resetEnhancer:Xm}=$D(),{parsedMessages:D0,parseMessages:Jm,resetParsedMessages:Pu}=Nj(),Qm=x.useRef(Promise.resolve());x.useEffect(()=>{if(!_o){Zt.current=!1;return}Zt.current||(Zt.current=!0,Ta([]),Pu())},[n.length,Pu,Ta,_o]);const ei=x.useCallback((P,D)=>{const $=xd(P),W=D?{...D}:void 0;return W?.flushRemote&&!ro.current&&(W.flushRemote=!1,W.deferRemoteSync=!0),Qm.current=Qm.current.catch(()=>{}).then(()=>i($,W)),Qm.current},[i]),Ah=!!(Ir?.result&&Ir.result.status!=="ready")?48:96,M0=x.useMemo(()=>Me.some(P=>P.role!=="assistant"?!1:Gi(P).trim().length>0?!0:Array.isArray(P.parts)?P.parts.some(D=>!D||typeof D!="object"||!("type"in D)?!1:D.type==="text"&&"text"in D?(D.text||"").trim().length>0:D.type==="tool-invocation"||D.type==="source"):!1),[Me]),O0=x.useMemo(()=>!Zs||Zs.length===0?!1:Zs.some(P=>typeof P=="object"&&P!==null&&"type"in P&&P.type==="progress"),[Zs]),Cs=x.useMemo(()=>{if(yt||T||B||s&&l?.historyStatusOverride!=="processing"&&Object.values(L).some(re=>re?.type==="file"))return!1;const P=Me.filter(re=>re.role==="assistant");if(P.length===0)return!1;const D=P[P.length-1],$=String(Gi(D)||"").toLowerCase(),W=P.some(re=>Gi(re).includes("<boltArtifact")),J=$.includes("initializing your project")||$.includes("analyze the current project structure");return mt||Pt?J&&!W:!1},[B,T,L,mt,yt,Pt,Me,l?.historyStatusOverride,s]),j0=x.useMemo(()=>{const P=le?ee[le]:void 0;return!!P&&!ve.has(le||"")&&y1(P)?P:Object.entries(ee).filter(([$,W])=>!ve.has($)&&y1(W)).map(([,$])=>$).slice(-1)[0]||void 0},[le,ve,ee]),gl=x.useMemo(()=>Object.values(j0?.runner.actions.get()||{}),[j0,ee]),$0=x.useMemo(()=>(Zs||[]).filter(P=>typeof P=="object"&&P!==null&&"type"in P&&P.type==="progress"),[Zs]);x.useMemo(()=>gl.filter(P=>P.status==="pending"||P.status==="running"),[gl]);const B0=x.useMemo(()=>Jr.some(P=>P.ready),[Jr]),Ra=x.useMemo(()=>{const P=[];for(const D of $0){const $=String(D.label||"").trim();if(!$)continue;const W=P.findIndex(re=>re.label===$),J={id:`${$}:${D.order??P.length}`,kind:"progress",label:$,status:D.status==="complete"?"complete":D.status==="failed"?"failed":D.status==="running"?"running":"pending",filePath:null};W>=0?P[W]=J:P.push(J)}for(const D of gl){const $=_se(D);if(!$)continue;const W=P.findIndex(de=>de.label===$),J=D.type==="file"?D.filePath:null,re={id:`${D.type}:${J||$}`,kind:D.type==="file"?"file":D.type==="start"?"preview":"shell",label:$,status:D.status==="complete"?"complete":D.status==="failed"||D.status==="aborted"?"failed":D.status==="running"?"running":"pending",filePath:J};W>=0?P[W]=re:P.push(re)}return z&&!P.some(D=>D.kind==="preview")&&P.push({id:"preview-starting",kind:"preview",label:"Starting live preview",status:"running",filePath:null}),ot?.status==="failed"?P.map(D=>D.status==="running"||D.status==="pending"?{...D,status:"failed"}:D):P},[z,gl,ot?.status,$0]),Ia=x.useMemo(()=>
2139{if(Ra.length===0)return null;const P=Ra.filter(D=>D.status==="complete").length;return Math.max(0,Math.min(100,Math.round(P/Ra.length*100)))},[Ra]),wo=x.useMemo(()=>ot?ot.status==="failed"?"failed":ot.status==="canceled"?"canceled":ot.status==="ready"?"ready":"running":null,[ot]),bl=ot?.phase||"IDLE";x.useEffect(()=>{if(!ot)return;const P=wo==="ready"?100:Ia??ot.maxProgressPercent;P===null||P<=(ot.maxProgressPercent??0)||qt(D=>D&&D.jobId===ot.jobId?{...D,maxProgressPercent:P}:D)},[wo,Ia,ot]);const un=x.useMemo(()=>{if(!ot||!wo||lt!=="build"||!Pt&&!mt)return null;const P=Object.keys(L||{}).filter(Le=>L[Le]?.type==="file").sort((Le,at)=>Le.localeCompare(at)),D=P.filter(Le=>{const at=Le.replace(/\\/g,"/"),bt=at.split("/").pop()||at;return PL.test(bt)&&!TL.some(Xe=>at.toLowerCase().includes(Xe))}),$=Ra.find(Le=>Le.status==="running")||Ra.slice(-1)[0],W=xse(ot.phase,ot.requestMode),J=wo==="running"&&(ot.maxProgressPercent??0)>=100?Ia&&Ia>0?Ia:99:ot.maxProgressPercent,re=wo==="ready"?100:Ia!==null?Math.min(99,Math.max(J??0,Ia)):J!==null?Math.min(99,J):J,de=gl.flatMap(Le=>Le.type==="file"&&(Le.status==="pending"||Le.status==="running")?[Le.filePath]:[]),_e=gl.flatMap(Le=>Le.type==="file"&&Le.status==="complete"?[Le.filePath]:[]),Re=[...new Set([..._e.slice(-6),...P.slice(-6)])].slice(-6);return{workspaceId:$r,jobId:ot.jobId,status:wo,requestMode:ot.requestMode,title:ot.promptPreview||"Build",statusLabel:Sse(wo),currentStep:W||$?.label||null,progressPercent:re,startedAt:ot.startedAt,updatedAt:Date.now(),completedAt:wo==="running"?null:ot.completedAt??Date.now(),error:ot.error,runningInBackground:!0,previewReady:B0,canCancel:wo==="running",canResume:Cs,availableFilePaths:P,availablePagePaths:D,recentFilePaths:Re,pendingFilePaths:de,completedFilePaths:_e,steps:Ra}},[$r,lt,wo,L,mt,Pt,B0,Ia,Cs,gl,ot,Ra]),hc=x.useMemo(()=>Qy(un),[un]),fc=x.useMemo(()=>Cse(un,l),[l,un]);x.useEffect(()=>{ro.current=hc},[hc]),x.useEffect(()=>{if(!un||!$r||Me.length===0)return;const P=[$r,un.status,un.currentStep||"",un.progressPercent??"",un.pendingFilePaths.join("|"),un.completedFilePaths.join("|"),ye,Me[Me.length-1]?.id||"",Gi(Me[Me.length-1]).length].join("::");if(Ss.current!==P)return cn.current&&window.clearTimeout(cn.current),cn.current=window.setTimeout(()=>{const $=gD({chat:{id:t||e||$r,urlId:e||t||$r,description:r||void 0,messages:SO(Me),timestamp:new Date().toISOString(),metadata:{...l||{},historyStatusOverride:fc},userEmail:Dt?.email,mode:mt?"site":"app"},snapshot:wse(Me,L),buildJob:un});Bj($r,$).catch(W=>{mr.warn("Failed to persist workspace build state",W)}),Ss.current=P},600),()=>{cn.current&&(window.clearTimeout(cn.current),cn.current=null)}},[$r,Dt?.email,t,r,L,mt,ye,Me,l,fc,un,e]),x.useEffect(()=>{un&&Ve.setKey("backgroundBuildJob",un)},[un]),x.useEffect(()=>{const P=Fe&&!$t.current;$t.current=Fe,P&&(!e||Me.length===0||ei(Me,{persistSnapshot:!0,flushRemote:!0,deferRemoteSync:!1}).catch(D=>{mr.warn("Failed to persist workspace snapshot when entering Home background mode",D)}))},[Fe,Me,ei,e]),x.useEffect(()=>{if(!Fe||!e)return;const P=Ve.get().backgroundHomeReturnPath,D=ap(P||rr||"/"),$=ih(D,e);P!==$&&Ve.setKey("backgroundHomeReturnPath",$)},[Fe,rr,e]),x.useEffect(()=>{if(!un||Js.current===fc)return;Js.current=fc;const P={...l||{},historyStatusOverride:fc};
2139ip.set(P),!(!c||!e||!hc)&&c(P).catch(D=>{mr.warn("Failed to persist workspace history status override",D)})},[hc,l,fc,c,un,e]),x.useEffect(()=>{const P=e||$r;if(!un||!P||Me.length===0||!hc)return;const D=Me[Me.length-1],$=[P,un.jobId,un.status,un.previewReady?"preview-ready":"preview-pending",D?.id||"",Gi(D).length].join("::");Wi.current!==$&&(Wi.current=$,ei(Me,{persistSnapshot:!0,flushRemote:!0,deferRemoteSync:!1}).catch(W=>{mr.warn("Failed to persist workspace history after successful preview startup",W)}))},[$r,hc,Me,ei,un,e]),x.useEffect(()=>{const P=Vt.current;if(!P)return;const D=P.requestId,$=P.forceRestart===!0,W=P.dependenciesAlreadyInstalled===!0,J=Jr.filter(He=>He.ready).length,re=!!q?.some(He=>He.status==="failed"),de=!!q?.some(He=>He.status==="running"||He.status==="pending"&&!re),_e=de&&(z||Ne),Re=(He,At={})=>{const Wt=JSON.stringify({requestId:D,reason:He,phase:ot?.phase||null,chatMode:lt,isRegularAppChat:Pt,isBuilderChat:mt,isLoading:yt,awaitingResponse:B,fakeLoading:T,showResumeGeneration:Cs,previewLocked:Te,runtimeRepairSettling:Qt,previewStarting:z,readyPreviewCount:J,restoreBlocking:_e,rawRestoreBlocking:de,historyRestoring:Ne,...At});Ut.current!==Wt&&(Ut.current=Wt,Q("auto_preview_skipped",{requestId:D,reason:He,phase:ot?.phase||null,chatMode:lt,isRegularAppChat:Pt,isBuilderChat:mt,isLoading:yt,awaitingResponse:B,fakeLoading:T,showResumeGeneration:Cs,previewLocked:Te,runtimeRepairSettling:Qt,previewStarting:z,readyPreviewCount:J,restoreBlocking:_e,rawRestoreBlocking:de,historyRestoring:Ne,...At}))};if(lt!=="build"||!Pt&&!mt){Vt.current=null,Re("non_build_chat_mode");return}if(yt||B||T||Cs){Re("request_still_running");return}const Le=ot?.phase||null;if(Le==="GENERATING"||Le==="STREAM_COMPLETE"||Le==="INSTALLING_DEPENDENCIES"||Le==="BUILDING"||Le==="BUILD_FAILED_AGGREGATED"||Le==="REPAIRING"||Le==="BUILD_VERIFICATION"){Re("preview_blocked_active_build_phase",{phase:Le});return}if(Te||Qt){Re("preview_locked_or_repair_settling");return}if(_e){Re("preview_waiting_restore_in_flight",{restoreSteps:q?.map(He=>({id:He.id,status:He.status,label:He.label}))});return}if(Ar.current===D)return;if($&&cs.current===D){Vt.current=null,Re("force_restart_already_attempted",{forceRestart:$});return}if(Q("auto_preview_eligible",{requestId:D,phase:ot?.phase||null,readyPreviewCount:J,previewStarting:z}),Ut.current="",j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),Qr.current===D){Vt.current=null;return}Ar.current=D,$&&(cs.current=D,Vt.current=null);const bt=()=>Ar.current===D&&(Vt.current?.requestId===D||Qr.current===D||$&&cs.current===D),Xe=He=>{if(!bt())return!1;if(Ve.get().aborted)return Re("preview_aborted_during_auto_start",{stage:He}),!1;if(Ve.get().previewLocked||zr.current)return Re("preview_locked_during_auto_start",{stage:He}),!1;const At=j.builderLifecyclePhase.get();return MD(At)?!0:(Re("preview_blocked_during_auto_start",{stage:He,phase:At}),!1)},vt=async()=>{let At=!1;await Promise.race([j.waitForPendingActions(),new Promise(Wt=>{window.setTimeout(()=>{At=!0,Wt()},1e4)})]),At&&Q("auto_preview_pending_actions_wait_timed_out",{requestId:D,timeoutMs:1e4})};(async()=>{try{if(await vt(),!Xe("pending_actions_flushed")||(await new Promise(Rt=>window.setTimeout(Rt,150)),!Xe("post_settle_delay")))return;const He=j.previews.get().some(Rt=>Rt.ready);Q("auto_preview_triggered",{requestId:D,source:He?"existing_ready_preview":"ensure_preview_running",readyPreviewCount:j.previews.get().filter(Rt=>Rt.ready).length});let At=!0;if(!He){const Rt=p1();Q("auto_preview_start_attempts_requested",{requestId:D,maxAttempts:2,source:"clean_build_start_dev_server",constrainedConnection:tv().constrained,waitForActiveStartMs:Rt.previewActiveStartTimeoutMs,waitForPreviewMs:Rt.previewReadyTimeoutMs}),At=await j.ensurePreviewRunningFromWorkspace({allowInitialStart:!0,reason:"clean-build-dev-server",maxAttempts:2,retryDelayMs:1500,waitForActiveStartMs:Rt.previewActiveStartTimeoutMs,waitForPreviewMs:Rt.previewReadyTimeoutMs,forceRestart:$,skipSetupCommand:!0,skipSetupCommandWhenDependenciesMissing:W})}if(!Xe("start_attempts_finished"))return;const Wt=j.previews.get().some(Rt=>Rt.ready);if(!At||!Wt){if(At&&j.previewStarting.get()){Q("auto_preview_deferred_until_ready",{requestId:D,source:"stream_finished",previewStartSucceeded:At,hasReadyPreview:Wt,previewStarting:!0,message:"Preview server start is still in progress; keeping auto-open pending until server-ready."});return}Vt.current=null,Q("auto_preview_deferred_until_ready",{requestId:D,source:"stream_finished",previewStartSucceeded:At,hasReadyPreview:Wt}),Re("no_ready_preview_after_start_attempts",{source:"stream_finished",previewStartSucceeded:At,hasReadyPreview:Wt});return}Vt.current=null,Qr.current=D,Ut.current="";const Wr=Ks.current;if(Wr?.requestId===D){Ks.current=null;const Rt=Jse({needsStripe:Wr.needsStripe,needsForms:Wr.needsForms});Rt&&Se.info(Rt,{autoClose:7e3})}if(gn("PREVIEW_RUNNING",{errorMessage:null}),j.setBuilderLifecyclePhase("PREVIEW_RUNNING"),Q("preview_started",{requestId:D,source:He?"existing_ready_preview":"post_build_auto_preview"}),j.currentView.set("preview"),await new Promise(Rt=>window.setTimeout(Rt,300)),!bt())return;j.requestPreviewRefresh(),j.refreshAllPreviews(),Q("auto_preview_open_and_refresh",{requestId:D,source:"stream_finished",readyPreviewCount:j.previews.get().filter(Rt=>Rt.ready).length})}catch(He){Vt.current=null,Re("auto_preview_exception",{errorMessage:He instanceof Error?He.message:String(He)}),mr.warn("Failed to auto-open preview after streaming finished",He)}finally{Ar.current===D&&(Ar.current=null)}})()},[B,lt,T,mt,yt,Pt,Ne,Q,z,Te,Jr,q,gn,Qt,Cs,ot?.phase]),x.useEffect(()=>{const P=Tl(Me,yt);P!==Gr.current&&(Ve.get().aborted||(Gr.current=P,vse({messages:Me,initialMessages:n,isLoading:yt,parseMessages:Jm,storeMessageHistory:ei})))},[n,yt,Me,Jm,ei]),x.useEffect(()=>{if(yt)return;const P=br.current;if(!P||Me.length===0)return;const D=`${P.requestId}:${Tl(Me,!1)}`;if(D===Tr.current){br.current=null;return}Tr.current=D,br.current=null;const $=lt==="build"&&(Pt||mt);Q("completion_persistence_dispatch",{requestId:P.requestId,messageCount:Me.length,flushRemote:!$}),ei(Me,{persistSnapshot:!0,flushRemote:!$,deferRemoteSync:$}).catch(W=>{console.error("[chat.client] Completion persistence failed",W),Se.error(W instanceof Error?W.message:"Failed to persist chat history")})},[lt,mt,yt,Pt,Q,Me,ei]),x.useEffect(()=>{const D=`${Fe?e||t||"default":t||"default"}::${Tl(n,!1)}`;D!==ln.current&&(G.current=!0,Dn.current+=1,Au(),qe.current=null,or.current=null,br.current=null,Vt.current=null,Ar.current=null,Qr.current=null,cs.current=null,Ut.current="",Mt.current=null,Pr.current+=1,Or.current=!1,zr.current=!1,Tn.current=null,je.current=null,St.current="idle",Ot.current=0,Sr.current=!1,fr.current=0,Ei.current.clear(),Nt(!1),R(!1),U(!1),oe(0),Ft($=>
2139{if(!$)return!1;const W=Ve.get();return W.started||W.previewLocked||j.showWorkbench.get()||!!Mt.current||T||B||yt?$:!1}),xt(void 0),ku(void 0),M($=>$==="repair"?"update":$),Ve.setKey("aborted",!1),Ve.get().previewLocked&&Ve.setKey("previewLocked",!1),j.clearAlert(),ln.current=D,Pu(),Gr.current="",Ta($=>{const W=Tl($,!1),J=Tl(n,!1);return W===J?$:n}))},[B,Fe,t,T,n,yt,Pu,Ta,Au,e]),x.useEffect(()=>{yt&&T&&R(!1)},[T,yt]),x.useEffect(()=>{B&&(Or.current||zr.current||N==="repair"||(M0||O0)&&(U(!1),oe(0)))},[N,B,M0,O0]),x.useEffect(()=>{Ve.get().previewLocked&&(Mt.current||or.current||Or.current||zr.current||!yt&&!B&&!T&&!Cs&&dt("idle_without_pending_validation"))},[B,T,yt,dt,Cs]),x.useEffect(()=>{if(!Dt)return;const P=PO();if(!P){an&&vs(!1),_g();return}if(Dx()||Mx(),!Dx())return;an&&vs(!1);const D=yg();if(P.route!==D){Q("auth_resume_route_redirect",{from:D,to:P.route}),window.location.replace(P.route);return}if(Ft(!0),m(!0),Ve.setKey("backgroundHomeActive",!1),Ve.setKey("backgroundHomeReturnPath",""),Ve.setKey("showChat",!0),Ve.setKey("started",!0),j.showWorkbench.set(!0),j.currentView.get()==="preview"&&j.previews.get().length===0&&j.currentView.set("code"),yt||T||B||!nn.current)return;const $=`${P.route}::${P.timestamp}`;if(js.current===$)return;js.current=$;const W=TO();if(!W){_g();return}_g(),$e(),Q("auth_resume_prompt_dispatch",{route:W.route,promptPreview:Un(W.prompt)}),nn.current(void 0,W.prompt).then(()=>{pn.current=0}).catch(J=>{const re=pn.current+1;if(pn.current=re,js.current=null,mr.error("Failed to resume pending prompt after authentication",J),Ie(W.prompt),Mx(),j.abortActiveGenerationProgress(),R(!1),U(!1),oe(0),Q("auth_resume_prompt_dispatch_failed",{retryCount:re,maxRetries:n1,error:J instanceof Error?J.message:String(J)}),re<=n1){te.current!==null&&window.clearTimeout(te.current),te.current=window.setTimeout(()=>{te.current=null,Fn(de=>de+1)},lne);return}xt({type:"error",title:"Unable to resume your prompt",description:"You are signed in, but the saved prompt could not be started. Please send it again.",provider:ht.name,errorType:"network"})})},[Dt,ys,B,$e,T,yt,Q,Ie,ht.name,an]),x.useCallback(P=>{const D=(P||"Unknown project error").trim().slice(0,12e3);return`${Yo} 2140${Xo} 2141Fix the generated project so it compiles, starts, and preview loads. Use the diagnostic details below as evidence, then inspect the current workspace and choose the least risky repair strategy. Rewrite every generated app file needed in this same response. 2142Do not target only the first mentioned file/error if another generated file is the root cause. 2143\`\`\`text 2144${D} 2145\`\`\``},[]);const F0=x.useCallback((P,D)=>{const $=(D||P||"Continue the original user request and update the workspace files.").trim().slice(0,12e3),W=(P||"Model returned plain text changes without file actions.").trim().slice(0,6e3);return`${Yo} 2146${Xo} 2147The last response described concrete code changes in plain text, but it did not emit any actual <boltAction type="file"> updates, so the workspace did not change. 2148Re-issue the ORIGINAL USER REQUEST as real Bolt file actions now. Stream complete corrected file contents for every generated app file needed for the requested experience. Do not just describe the code. 2149\`\`\`text 2150${$} 2151\`\`\` 2152Recent non-applied attempt for reference: 2153\`\`\`text 2154${W} 2155\`\`\``},[]),BL=x.useCallback((P,D)=>{const $=(P||"Continue the latest user request and update the workspace files.").trim().slice(0,12e3);return`${Yo} 2156${Xo} 2157The last model reply for the ${D==="build"?"initial build request":"latest follow-up request"} completed without emitting any assistant content or any real <boltAction type="file"> updates, so the workspace did not change. 2158Resume the SAME user request now using real Bolt file actions: 2159- modify the existing project files in place 2160- create every required page/component/module/route in this SAME response 2161- if navigation or buttons should route to a new page, wire those updates too 2162- stream complete <boltAction type="file"> contents for every changed or created file 2163- do not use find/replace patch blocks 2164- do not return an empty response, plain-text summary, or shell-only output 2165\`\`\`text 2166${$} 2167\`\`\``},[]),FL=x.useCallback(P=>{const D=(P.originalRequest||"Repair the current generated project so it builds cleanly and preview can load.").trim().slice(0,6e3),$=(P.previousRepairPrompt||"Retry the previous automatic repair with real file changes.").trim().slice(0,14e3),W=String(P.previousRepairSource||"auto_repair").trim();return`${Yo} 2168${Xo} 2169The previous automatic repair request (${W}) returned no assistant content and made no file changes. 2170Retry the SAME repair now and do not return an empty response. 2171Use normal <boltAction type="file"> updates and rewrite the full affected file(s) when necessary. 2172Do not use find/replace patch blocks. 2173 2174Original user goal: 2175\`\`\`text 2176${D} 2177\`\`\` 2178 2179Previous failed automatic repair request: 2180\`\`\`text 2181${$} 2182\`\`\` 2183 2184Requirements: 2185- emit actual full-file changes in this response 2186- prioritize the files already named in the failed repair request 2187- if a file is badly broken, rewrite the full file instead of returning a no-op or empty patch 2188- do not stop at commentary or summary text 2189- finish only when the current project should build and preview cleanly`},[]),W0=x.useCallback((P,D)=>{const $=(D||P||"Continue the original user request and update the workspace files.").trim().slice(0,12e3),W=(P||"Model emitted shell actions without file updates.").trim().slice(0,6e3);return`${Yo} 2190${Xo} 2191The last response emitted shell actions (for example dependency installation) but it did not emit any real <boltAction type="file"> updates, so the workspace is still on the starter template. 2192Continue the SAME original request now using real file actions: 2193- keep any dependency or package changes that were already applied if they are still needed 2194- update the live app entry file if it still contains the starter placeholder 2195- create every newly referenced page/component/module in this SAME response so the app compiles immediately 2196- stream complete <boltAction type="file"> contents for every changed or created file 2197- do not stop after shell actions; emit the actual implementation files now 2198- if no further dependencies are needed, do not emit another shell action 2199\`\`\`text 2200${$} 2201\`\`\` 2202Recent shell-only attempt for reference: 2203\`\`\`text 2204${W} 2205\`\`\``},[]),H0=x.useCallback((P,D,$=[])=>{const W=(P||"Continue the original user request and replace the starter placeholder entry.").trim().slice(0,12e3),J=$.length>0?`Recent file actions touched: ${$.slice(0,8).join(", ")}.`:"Recent file actions did not replace the placeholder entry.";return`${Yo} 2206${Xo}
2207The starter placeholder is still mounted in \`${D}\` after the latest response, so the requested app is not actually rendered yet. 2208${J} 2209Continue the same request and replace the placeholder entry with the real implementation now: 2210- update the live app entry flow so the requested UI is visible on first load 2211- do not only rewrite \`${D}\`; create or rewrite every generated app module, style file, and config file needed for the requested app 2212- do not spend this repair editing only protected template infrastructure or form integration helper files 2213- if you update \`${D}\` to import pages/components/hooks, create every newly referenced local module in the SAME response so the app compiles immediately after this reply 2214- if you create supporting pages/components/hooks, also wire them into \`${D}\` and the route tree in the same response 2215- stream complete <boltAction type="file"> contents for every changed or created file 2216Do not leave \`${D}\` importing files that do not exist after this reply. 2217\`\`\`text 2218${W} 2219\`\`\``},[]),U0=x.useCallback((P,D,$)=>{const W=(P||"Continue the original user request and replace the starter placeholder entry.").trim().slice(0,12e3),J=$.length>0?$.join(", "):"none";return`${Yo} 2220${Xo} 2221The last response only attempted file edits in protected template infrastructure (${J}). Those writes were ignored, so the requested app was not created and the starter placeholder is still mounted in \`${D}\`. 2222Resume the ORIGINAL USER REQUEST below and implement it by editing app-owned files now: 2223- replace the placeholder in \`${D}\` so the requested UI is visible on first load 2224- create or update the actual app files needed for the requested experience (pages, components, routes, hooks, styles, and app-owned schema/modules as needed) 2225- stream complete <boltAction type="file"> contents for every changed or created file 2226- do not spend this repair editing only protected infrastructure such as \`src/lib/appSchema.ts\`, \`src/lib/appData.ts\`, or other protected runtime files 2227- if imports need app-specific schema/data helpers, create app-owned files and point consumers there instead of rewriting protected template files 2228- if you update \`${D}\` or any route/layout file to import local modules, also create every imported local module in the SAME response so preview can compile immediately after this reply 2229- do not stop after a single protected-file attempt or a single entry-file rewrite; finish the first compile-ready app slice in one pass 2230\`\`\`text 2231${W} 2232\`\`\``},[]),io=x.useCallback(()=>{Pr.current+=1,Or.current=!1,zr.current=!1,kr.current=null,St.current="idle",Ot.current=0,Sr.current=!1,Nt(!1),M(P=>P==="repair"?"update":P)},[]),z0=x.useCallback(P=>{const D=P.validationIssues.map($=>$.code);return Me.length>0&&ei(Me,{persistSnapshot:!0,flushRemote:lt==="build"&&(Pt||mt)}).catch($=>{console.error("[chat.client] Completion persistence failed after successful build",$)}),io(),or.current=null,Vt.current={requestId:P.requestId,dependenciesAlreadyInstalled:!0},R(!1),U(!1),oe(0),gn("READY_FOR_PREVIEW",{errorMessage:null}),j.setBuilderLifecyclePhase("READY_FOR_PREVIEW"),j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),j.clearRestoreProgressForPreviewHandoff(P.source),Q("generation_validation_complete",{requestId:P.requestId,source:P.source,messageCount:Me.length,validationIssueCount:P.validationIssues.length,validationCodes:D,finalVerificationBuild:!1}),P.validationIssues.length>0?Q("preview_unlocked_validation_warnings",{requestId:P.requestId,repairIteration:P.repairIteration,validationIssueCount:P.validationIssues.length,validationCodes:D,message:"Build passed, so preview is unlocking immediately while validation warnings remain available for follow-up fixes."}):Q(hs.PREVIEW_UNLOCKED_CLEAN_BUILD,{requestId:P.requestId,repairIteration:P.repairIteration,totalRepairCycles:P.repairIteration+1}),dt(P.source),!0},[lt,io,mt,Pt,Q,Me,ei,dt,gn]),Vo=x.useCallback(P=>{io(),Sr.current=P.source==="assistant_empty_response",or.current=null,Vt.current=null,R(!1),U(!1),oe(0);const D=P.buildIssueCount===0&&P.validationIssueCount===0&&P.importIssueCount===0,$=P.allowPreviewWithCurrentWorkspace===!0,W=[P.summary,"",`Source: ${P.source}`,`Repair iteration: ${P.repairIteration}`,`Build issues: ${P.buildIssueCount}
2232`,`Validation issues: ${P.validationIssueCount}`,`Import issues: ${P.importIssueCount}`].join(` 2233`);return P.source==="assistant_empty_response"&&D?(Vt.current={requestId:P.requestId},gn("READY_FOR_PREVIEW",{errorMessage:null}),j.setBuilderLifecyclePhase("READY_FOR_PREVIEW"),j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),j.clearRestoreProgressForPreviewHandoff("auto-repair-empty-response-clean-preview"),j.actionAlert.set(void 0),Ve.setKey("previewLocked",!1),Q("auto_repair_empty_response_clean_preview_queued",{requestId:P.requestId,source:P.source,repairIteration:P.repairIteration,message:"Automatic repair returned no content, but there are no remaining diagnostics, so preview is queued instead of failing the builder."}),!0):($?(Vt.current={requestId:P.requestId},gn("READY_FOR_PREVIEW",{errorMessage:null}),j.setBuilderLifecyclePhase("READY_FOR_PREVIEW"),j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),j.clearRestoreProgressForPreviewHandoff("auto-repair-stopped-preview-queued")):(gn("FAILED",{errorMessage:P.summary}),j.setBuilderLifecyclePhase("FAILED")),j.actionAlert.set({type:"error",title:"Automatic Repair Stopped",description:P.summary,content:W}),Ve.setKey("previewLocked",!1),$&&Q("auto_repair_stopped_preview_queued",{requestId:P.requestId,source:P.source,repairIteration:P.repairIteration,buildIssueCount:P.buildIssueCount,validationIssueCount:P.validationIssueCount,importIssueCount:P.importIssueCount,reason:P.previewFallbackReason||"current_workspace_runnable",message:"Automatic repair stopped, but the generated app build passed, so the current workspace preview is queued with remaining diagnostics visible."}),Q("auto_repair_stopped_visible_failure",{requestId:P.requestId,source:P.source,repairIteration:P.repairIteration,buildIssueCount:P.buildIssueCount,validationIssueCount:P.validationIssueCount,importIssueCount:P.importIssueCount,previewQueued:$,message:P.summary}),!0)},[io,Q,gn]),Zm=x.useCallback(P=>{const D=fse(P.timedOutCommands),$=P.timedOutCommands.some(re=>re.stage==="install"),J=Object.entries(j.files.get()).some(([re,de])=>{const _e=fn(re);return!!de&&de.type==="file"&&!de.isBinary&&!_e.startsWith("node_modules/")&&!_e.startsWith(".git/")&&/\.(?:html?|[jt]sx?|vue|astro|svelte|mdx?|css)$/i.test(_e)})&&!$&&P.syntaxPreflightPassed===!0;return io(),or.current=null,Vt.current=J?{requestId:P.requestId,dependenciesAlreadyInstalled:!0}:null,R(!1),U(!1),oe(0),J?(gn("READY_FOR_PREVIEW",{errorMessage:null}),j.setBuilderLifecyclePhase("READY_FOR_PREVIEW"),j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),j.clearRestoreProgressForPreviewHandoff("workspace-validation-timeout-preview-fallback"),j.actionAlert.set(void 0),dt("workspace_validation_timeout_preview_fallback"),Se.warning("Full validation exceeded its time budget. Your files passed syntax checks, so preview is starting. Large requests can be continued with smaller follow-up prompts if needed."),Q("workspace_command_timeout_preview_fallback_queued",{requestId:P.requestId,repairIteration:P.repairIteration,timedOutCommands:Pl(P.timedOutCommands),message:"Generated files passed the syntax preflight, so preview is being unlocked while the slower validation command is allowed to time out."}),!0):(gn("FAILED",{errorMessage:D}),j.setBuilderLifecyclePhase("FAILED"),j.actionAlert.set({type:"error",title:$?"Dependency Installation Timed Out":"Workspace Validation Timed Out",description:D,content:[D,"",`Repair iteration: ${P.repairIteration}`,`Timed out commands: ${P.timedOutCommands.length}`,`Syntax preflight passed: ${P.syntaxPreflightPassed===!0}`,JSON.stringify(Pl(P.timedOutCommands),null,2)].join(` 2234`)}),dt("workspace_validation_timeout_without_verified_syntax"),Q("workspace_command_timeout_not_sent_to_qwen",{requestId:P.requestId,repairIteration:P.repairIteration,timedOutCommands:Pl(P.timedOutCommands),message:D}),!1)}
2234,[io,Q,dt,gn]),dn=x.useCallback(P=>{ei(Me,{persistSnapshot:!0,flushRemote:!1,deferRemoteSync:!0}).catch(D=>{mr.warn("Failed to persist workspace snapshot after local repair",D),Q("local_repair_snapshot_persistence_failed",{reason:P,error:D instanceof Error?D.message:String(D)})})},[Q,Me,ei]),WL=x.useCallback(async()=>{const P=++Pr.current;zr.current=!0,Nt(!0);try{await j.waitForPendingActions(),await new Promise(D=>window.setTimeout(D,hne)),j.requestPreviewRefresh(),j.refreshAllPreviews()}finally{if(Pr.current!==P)return;Or.current=!1,zr.current=!1,Nt(!1),M(D=>D==="repair"?"update":D),R(!1),U(!1),oe(0)}},[]),HL=x.useCallback(async(P,D)=>{const $=RL(P);if(Q("targeted_repairs_extraction",{requestId:D,contentLength:P.length,contentPreview:P.slice(0,400),repairBlockCount:$.length,repairBlockFilePaths:$.map(W=>W.filePath||"(missing)")}),$.length===0)return!1;try{await j.waitForPendingActions();let W=j.files.get();const J=[],re=[];for(const de of $){const _e=hn(W,de.filePath);if(!_e){re.push({filePath:de.filePath||"(missing file path)",reason:"file-not-found"});continue}const Re=Kt(W,_e),Le=Ase(Re,de);if(!Le.applied){re.push({filePath:_e,reason:Le.reason});continue}if(Le.content===Re){re.push({filePath:_e,reason:"no-op"});continue}await j.writeFile(_e,Le.content);const at=W[_e];W={...W,[_e]:at&&at.type==="file"?{...at,content:Le.content}:{type:"file",content:Le.content,isBinary:!1}},J.push({filePath:_e,matchMode:Le.matchMode})}return Q("targeted_repairs_processed",{requestId:D,blockCount:$.length,appliedRepairCount:J.length,skippedRepairCount:re.length,appliedRepairs:J,skippedRepairs:re}),J.length===0?!1:(Ot.current=0,dn("targeted-repairs"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0)}catch(W){return mr.error("Failed to process targeted repairs",W),Q("targeted_repairs_processing_failed",{requestId:D,error:W instanceof Error?W.message:String(W)}),!1}},[Q,dn]),eg=x.useCallback(async P=>{const D=Date.now()+i1;for(await j.waitForPendingActions();Date.now()<D;){const $=j.hasPendingFileActions(),W=j.hasRecentFileActionActivity(Lf);if(!$&&!W)return;await new Promise(J=>window.setTimeout(J,pne)),await j.waitForPendingActions()}Q("workspace_settle_timeout",{reason:P,previewStarting:j.previewStarting.get(),hasPendingFileActions:j.hasPendingFileActions(),hasRecentFileActionActivity:j.hasRecentFileActionActivity(Lf)})},[Q]),Tu=x.useCallback(async(P,D,$,W)=>{const J=W?.displayCommand||[D,...$].join(" "),re=W?.timeoutMs??(()=>{const Wt=p1();return P==="install"?Wt.installTimeoutMs:P==="syntax"?Math.max(6e4,Math.min(Wt.typecheckTimeoutMs,12e4)):P==="typecheck"?Wt.typecheckTimeoutMs:Wt.buildTimeoutMs})();Q("workspace_command_started",{stage:P,command:J,timeoutMs:re});const _e=await(await ev).spawn(D,$);let Re="",Le=!1,at=null,bt=null;const Xe=Date.now(),vt=Wt=>{try{j.boltTerminal.terminal?.write(Wt)}catch{}};vt(`\r 2235> ${J}\r 2236`),(P==="install"||P==="build"||P==="typecheck")&&(bt=setInterval(()=>{const Wt=Math.max(1,Math.floor((Date.now()-Xe)/6e4));vt(P==="install"?`\r 2237[builder] Dependency installation is still running (${Wt}m elapsed). Your files are saved.\r 2238`:`\r 2239[builder] ${P==="build"?"Build validation":"Type checking"} is still running (${Wt}m elapsed). Your files are saved; slow browser sessions can take longer.\r 2240`)},6e4));const vr=_e.output.pipeTo(new WritableStream({write(Wt){const Wr=String(Wt||"");Re+=Wr,vt(Wr)}})).catch(()=>{}),He=_e.exit,At=re>0?await Promise.race([He,new Promise(Wt=>{at=setTimeout(()=>{Le=!0;try{_e.kill()}catch{}Wt(124)},re)})]):await He;if(at&&clearTimeout(at),bt&&clearInterval(bt),await Promise.race([vr,new Promise(Wt=>{window.setTimeout(Wt,2e3)})]),Le){const Wt=` 2241[builder] ${J} timed out after ${re}ms and was terminated. 2242`;Re=`${Re}${Wt}`.trim(),vt(Wt.replaceAll(` 2243`,`\r 2244`))}else vt(`\r 2245[builder] Command finished with exit code ${At}.\r 2246`);return{stage:P,command:J,exitCode:At,output:Re,timedOut:Le,timeoutMs:re}},[Q]),V0=x.useCallback(async P=>{const D=j.files.get(),$=Kt(D,"package.json");if(!$.trim())return null;const W=Kt(D,ise),J=W.trim().length>0&&ND($,W),re=tv(),de=J?["ci","--prefer-offline","--no-audit","--no-fund","--progress=false"]:["install","--prefer-offline","--no-audit","--no-fund","--progress=false"];de.push(...ZD(re));const _e=`npm ${de.join(" ")}`,Re=Tt($),Le=await ev;let at=!0;try{await Le.fs.readdir(`${Le.workdir}/node_modules`)}catch{at=!1}if(Xs.current===Re)return Q("dependency_install_skipped_session_cache",{requestId:P,hasNodeModules:at,message:"This exact package manifest already completed installation in the current workspace session, so validation is reusing it."}),null;if(at)try{const Xe=JSON.parse($),vt=[...new Set([...Object.keys(Xe.dependencies||{}),...Object.keys(Xe.devDependencies||{})])].filter(He=>He.trim().length>0),vr=[];for(const He of vt){const At=He.startsWith("@")?He.split("/").filter(
2246Boolean):[He];if(At.length!==0)try{await Le.fs.readdir(`${Le.workdir}/node_modules/${At.join("/")}`)}catch{vr.push(He)}}if(vr.length===0)return Xs.current=Re,Q("dependency_install_skipped_satisfied_node_modules",{requestId:P,packageCount:vt.length,message:"Existing node_modules already contains every declared dependency, so validation is not blocking preview on npm install."}),null;Q("dependency_install_required_missing_node_modules_packages",{requestId:P,missingPackageCount:vr.length,missingPackageNames:vr.slice(0,20)})}catch(Xe){Q("dependency_install_satisfaction_check_failed",{requestId:P,error:Xe instanceof Error?Xe.message:String(Xe)})}Q("dependency_install_started",{requestId:P,command:_e,hasPackageLock:!!W.trim(),packageLockCompatible:J,constrainedNetwork:re.constrained});const bt=await Tu("install","npm",de);return Q("dependency_install_completed",{requestId:P,exitCode:bt.exitCode}),bt.exitCode===0&&(Xs.current=Re),bt},[Q,Tu]),tg=x.useCallback(async P=>{await j.waitForPendingActions();const D=j.files.get(),$=sse(D);if(!$||$.rewrites.length===0)return!1;const W=[...new Set($.detectedImports.map(re=>re.importSource))],J=[...new Set($.detectedImports.map(re=>re.filePath))];Q("lucide_import_detected",{requestId:P,fileCount:J.length,importSourceCount:W.length,importSources:W,iconCount:$.iconNames.length});for(const re of $.rewrites)re.create?await j.createFile(re.filePath,re.content,{selectFile:!1}):await j.writeFile(re.filePath,re.content);return Q("lucide_import_rewritten",{requestId:P,fileCount:$.rewrites.length,iconCount:$.iconNames.length,filePaths:$.rewrites.map(re=>re.filePath)}),!0},[Q]),Eh=x.useCallback(async(P,D)=>{if(P.code!=="auth-runtime-disabled")return!1;if(Xt.current===D)return!0;Xt.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=[hn($,P.filePath)||P.filePath,hn($,"app.config.json"),hn($,"public/app.config.json")].filter((re,de,_e)=>!!re&&_e.indexOf(re)===de),J=[];for(const re of W){const de=Kt($,re),_e=Tse(de);!_e||_e.content===de||J.push({filePath:re,content:_e.content})}if(J.length===0)return!1;for(const re of J)await j.writeFile(re.filePath,re.content);return Q("local_auth_runtime_disabled_repair_applied",{filePaths:J.map(re=>re.filePath),consumerFileCount:P.consumerFilePaths.length,consumerFilePaths:P.consumerFilePaths.slice(0,8),hasLoginEntryPoint:P.hasLoginEntryPoint,hasSignupEntryPoint:P.hasSignupEntryPoint}),dn("local-auth-runtime-disabled-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local auth runtime disabled repair",$),!1}finally{Xt.current===D&&(Xt.current=null)}},[Q,dn]),G0=x.useCallback(async(P,D)=>{if(P.length===0)return!1;if(jr.current===D)return!0;jr.current=D;try{await j.waitForPendingActions();let $=j.files.get();const W=new Map;for(const J of P){const re=J.resolvedPath?hn($,J.resolvedPath)||J.resolvedPath:null;if(J.code==="missing-export"&&re&&fn(re)===tp&&J.missingExportNames.length>0){const bt=W.get(re)?.content??Kt($,re),Xe=nse(bt,J.missingExportNames);if(Xe&&Xe.content!==bt){W.set(re,{filePath:re,content:Xe.content,importSource:J.importSource,repairKind:"generated-icon-export",addedIconNames:Xe.addedIconNames});const vt=$[re];$={...$,[re]:vt&&vt.type==="file"?{...vt,content:Xe.content}:{type:"file",content:Xe.content,isBinary:!1}}}continue}const de=hn($,J.sourceFile)||J.sourceFile,_e=W.get(de)?.content??Kt($,de),Re=re?W.get(re)?.content??Kt($,re):"",Le=Hne(_e,J,Re);if(!Le||Le.content===_e)continue;W.set(de,{filePath:de,content:Le.content,importSource:J.importSource,repairKind:Le.kind});const at=$[de];$={...$,[de]:at&&at.type==="file"?{...at,content:Le.content}:{type:"file",content:Le.content,isBinary:!1}}}if(W.size===0)return!1;for(const J of W.values())await j.writeFile(J.filePath,J.content);return Q("local_import_integrity_repair_applied",{issueCount:P.length,repairCount:W.size,repairs:Array.from(W.values()).map(({content:J,...re})=>re)}),dn("local-import-integrity-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local import integrity repair",$),!1}finally{jr.current===D&&(jr.current=null)}},[Q,dn]),q0=x.useCallback(async(P,D,$)=>{let W=null;try{await j.waitForPendingActions();const J=j.files.get(),re=hn(J,Fh)||Fh,de=Kt(J,re);if(!de.trim())return!1;const _e=eE(de);if(_e===de)return!1;const Re=(de.match(/const writeTextResponse = \(/g)||[]).length,Le=`vite-local-db-writeTextResponse-dedupe::${re}::${Re}`;return ls.current===Le||(W=Le,ls.current=Le,Q("local_vite_local_db_runtime_repair_applied",{requestId:P,repairIteration:D,source:$,filePath:re,originalHelperCount:Re,repairedHelperCount:(_e.match(/const writeTextResponse = \(/g)||[]).length}),await j.writeFile(re,_e),dn("local-vite-local-db-runtime-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews()),!0}catch(J){return mr.error("Failed local vite.local-db runtime repair",J),!1}finally{W&&ls.current===W&&(ls.current=null)}},[Q,dn]),K0=x.useCallback(async(P,D,$)=>{try{await j.waitForPendingActions();const W=j.files.get(),J=cie(W);return!J||Kt(W,J.filePath).trim()===J.content.trim()?!1:(Q("tailwind_theme_tokens_repaired",{requestId:P,repairIteration:D,source:$,filePath:J.filePath,tokenNames:J.tokenNames}),await j.writeFile(J.filePath,J.content),dn("local-tailwind-theme-token-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0)}catch(W){return mr.error("Failed local tailwind theme token repair",W),!1}},[Q,dn]),Y0=x.useCallback(async(P,D,$)=>{try{await j.waitForPendingActions();const W=j.files.get(),J=aie(W);return!J||Kt(W,J.filePath).trim()===J.content.trim()?!1:(Q("missing_dom_targets_repaired",{requestId:P,repairIteration:D,source:$,filePath:J.filePath,targets:J.targets}),await j.writeFile(J.filePath,J.content),dn("local-missing-dom-target-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0)}catch(W){return mr.error("Failed local missing DOM target repair",W),!1}},[Q,dn]),Ru=x.useCallback(async P=>{const D=ot?.repairIteration??0,$=[];gn("STREAM_COMPLETE",{errorMessage:null}),Q("stream_completed",{requestId:P,repairIteration:D});const J=await(async()=>{const Oe=i1,Ze=100,Et=Date.now();for(;Date.now()-Et<Oe;){await j.waitForPendingActions();
2246const zt=j.hasPendingFileActions(),Rr=j.hasRecentFileActionActivity(Lf);if(!zt&&!Rr)return!0;await new Promise(vn=>setTimeout(vn,Ze))}return!1})();J||Q(hs.PREVIEW_BLOCKED_PENDING_FILE_WRITES,{requestId:P,message:"Timed out waiting for file actions to complete"}),Q(hs.ALL_FILE_ACTIONS_APPLIED,{requestId:P,waitedForFileActions:J}),await tg(P);const re=await j.interruptBoltTerminal(D>0?"stream-complete-repair-verification":"stream-complete-initial-verification");Q("validation_shell_interrupted",{requestId:P,repairIteration:D,interrupted:re});let de=j.files.get();await q0(P,D,"prebuild_runtime_cleanup")&&(de=j.files.get()),await K0(P,D,"prebuild_tailwind_theme_cleanup")&&(de=j.files.get()),await Y0(P,D,"prebuild_dom_target_cleanup")&&(de=j.files.get());const at=await j.cleanupViteSourceEntryPublicMirrors();at.length>0&&(de=j.files.get(),Q("vite_public_entry_mirrors_removed",{requestId:P,repairIteration:D,filePaths:at}),dn("vite-public-entry-mirrors-removed"));const bt=Kt(de,"package.json"),Xe=/["']typescript["']\s*:/.test(bt),vt=!!Kt(de,"tsconfig.json").trim()||!!Kt(de,"tsconfig.app.json").trim(),vr=Object.keys(de).some(Oe=>{const Ze=fn(Oe)||String(Oe||"").replace(/\\/g,"/");return!/\.(?:ts|tsx)$/i.test(Ze)||/\.d\.ts$/i.test(Ze)?!1:Ze.startsWith("src/")||Ze.startsWith("app/")||Ze==="main.ts"||Ze==="main.tsx"}),He=Xe&&(vt||vr),At=Oe=>{const Ze=Oe.exitCode===0?"":kL(Oe.output);Q("workspace_command_completed",{requestId:P,repairIteration:D,stage:Oe.stage,command:Oe.command,exitCode:Oe.exitCode,outputPreview:Ze||void 0})},Wt=(Oe,Ze,Et,zt)=>{Ze.length>0&&Q("build_issue_details",{requestId:P,repairIteration:D,phase:Oe,issueCount:Ze.length,issues:g1(Ze)}),Et.length>0&&Q("validation_issue_details",{requestId:P,repairIteration:D,phase:Oe,issueCount:Et.length,issues:Xb(Et)}),zt.length>0&&Q("import_issue_details",{requestId:P,repairIteration:D,phase:Oe,issueCount:zt.length,issues:Jb(zt)})},Wr=(Oe,Ze,Et)=>{Q(hs.DEPENDENCY_GRAPH_SCAN_STARTED,{requestId:P,repairIteration:D,phase:Ze,limit:Et});const zt=zy(Oe,{includeWarnings:!1,limit:Et});return Q(hs.DEPENDENCY_GRAPH_SCAN_COMPLETED,{requestId:P,repairIteration:D,phase:Ze,scannedFileCount:zt.scannedFileCount,localImportCount:zt.localImportCount,importIssueCount:zt.issues.length,missingDependencyCount:zt.missingDependencyCount}),zt.issues.length>0&&Q(hs.MISSING_IMPORT_GRAPH_DETECTED,{requestId:P,repairIteration:D,phase:Ze,importIssueCount:zt.issues.length,missingDependencyCount:zt.missingDependencyCount,sampleImporters:zt.missingDependencies.slice(0,5).map(Rr=>Rr.importerFile)}),zt},Rt=async(Oe,Ze,Et,zt,Rr,vn)=>{const Kr=Oe,Yr=Ze,An=Et,lg=Kr.length+Yr.length+An.length,gi=Kr[0]?.message||An[0]?.message||(Yr[0]?nh(Yr[0]):"Post-stream build validation failed.");gn("BUILD_FAILED_AGGREGATED",{errorMessage:gi});const Nu=zt==="import_integrity"&&Kr.length===0&&Yr.length===0&&An.length>0,Lu=Ot.current>0&&(Kr.length>0||Yr.length>0||An.length>0),ja=vn?.allowPreviewWithCurrentWorkspace===!0;
2246if(Lu&&Vo({requestId:P,source:zt,repairIteration:D,summary:Nu?"Automatic repair stopped making code changes, but the preview server is already running. You can inspect the app now while the remaining import issue is still listed in the diagnostics.":"Automatic repair stopped making code changes, so preview has been unlocked with the current workspace state while the remaining build diagnostics stay visible.",buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length,allowPreviewWithCurrentWorkspace:ja,previewFallbackReason:vn?.reason}))return!0;if(D>=ep)return ja&&Vo({requestId:P,source:zt,repairIteration:D,summary:"Automatic repair hit its retry limit with typecheck-only diagnostics remaining, but the app build passed. Preview is opening with the current workspace state while the diagnostics stay visible.",buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length,allowPreviewWithCurrentWorkspace:ja,previewFallbackReason:vn?.reason})||Nu&&Vo({requestId:P,source:zt,repairIteration:D,summary:"Preview has been unlocked with remaining import warnings because automatic repair hit its retry limit.",buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length})?!0:(hi("failed",gi),or.current=null,Q(hs.PREVIEW_BLOCKED_FAILED_VERIFICATION,{requestId:P,reason:`${zt}_limit_reached`,repairIteration:D+1,maxIterations:ep,buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length,allowPreviewWithCurrentWorkspace:ja,previewFallbackReason:vn?.reason}),!1);let Du="";An.length>0&&(Du=` 2247 2248### Import Integrity Issues 2249${OZ(An,Rr)}`,Q(hs.REPAIR_PAYLOAD_INCLUDES_MISSING_DEPENDENCIES,{requestId:P,repairIteration:D+1,source:zt,importIssueCount:An.length,missingDependencyCount:Rr?.missingDependencyCount??0}));const Mu=$.filter($a=>!$l($a)),Ou=$.filter($l);Ou.length>0&&Q("workspace_command_timeouts_omitted_from_qwen_repair_payload",{requestId:P,repairIteration:D+1,source:zt,timedOutCommands:Pl(Ou),message:"Workspace command timeouts are builder validation issues and are not included in Qwen repair prompts."});let So=pse({originalRequest:kl(Me),buildIssues:Kr,validationIssues:Yr,importIssues:An,importGraphReport:Rr,commandResults:Mu,repairIteration:D+1})+Du;const qo=hse(Kr,Yr,An),yc=Sn.current,Oh=yc!==null&&yc===qo;if(Oh&&D>=2)return Vo({requestId:P,source:zt,repairIteration:D,summary:ja?"Automatic repair stopped because the same diagnostics remained after multiple Qwen repair passes, but the app build passed. Preview is opening with the current workspace state while the diagnostics stay visible.":"Automatic repair stopped because the same diagnostics remained after multiple Qwen repair passes. Preview is unlocked with the current workspace state to avoid rewriting the same files again.",buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length,allowPreviewWithCurrentWorkspace:ja,previewFallbackReason:vn?.reason})?!0:(hi("failed",gi),or.current=null,Q("auto_repair_repeated_signature_stopped",{requestId:P,repairIteration:D,source:zt,signature:qo.slice(0,200),buildIssueCount:Oe.length,validationIssueCount:Ze.length,importIssueCount:Et.length}),!1);if(Oh){const $a=[...new Set([...Kr.map(ks=>ks.filePath).filter(Boolean),...Yr.map(ks=>ks.filePath).filter(Boolean),...An.map(ks=>ks.sourceFile).filter(Boolean)])],tx=[...Kr.map(ks=>({code:ks.code||"build-issue",message:ks.message,filePath:ks.filePath||void 0})),...Yr.map(ks=>({code:ks.code,message:nh(ks),filePath:ks.filePath})),...An.map(ks=>({code:ks.code,message:ks.message,filePath:ks.sourceFile}))];So=mse({basePrompt:So,previousSignature:yc,currentSignature:qo,affectedFiles:$a,remainingIssues:tx}),Q(hs.REPAIR_SIGNATURE_REPEATED,{requestId:P,repairIteration:D+1,signature:qo.slice(0,200),affectedFileCount:$a.length,remainingIssueCount:tx.length,message:"Same issue signature detected after previous repair attempt - sending stronger repair prompt"})}const ri=Rr?.signature||null;An.length>0&&!!ri&&kr.current===ri&&Rr&&(So=gse({basePrompt:So,importGraphReport:Rr}),Q(hs.REPAIR_SIGNATURE_REPEATED_MISSING_DEPENDENCIES,{requestId:P,repairIteration:D+1,source:zt,importIssueCount:An.length,missingDependencyCount:Rr.missingDependencyCount,importGraphSignature:ri.slice(0,200)})),Sn.current=qo,kr.current=ri,gn("REPAIRING",{errorMessage:gi,incrementRepairIteration:!0}),Q(hs.BUILD_REPAIR_CYCLE_STARTED,{requestId:P,repairIteration:D+1,maxRepairIterations:ep,source:zt,buildIssueCount:Oe.length,validationIssueC
2249ount:Ze.length,importIssueCount:Et.length,totalIssueCount:lg}),Q("qwen_repair_request_sent",{requestId:P,repairIteration:D+1,source:zt,signature:qo.slice(0,240),messagePreview:m1(Kr,Yr,An),buildIssueCount:Kr.length,validationIssueCount:Yr.length,importIssueCount:An.length,buildIssues:g1(Kr),validationIssues:Xb(Yr),importIssues:Jb(An),omittedWorkspaceTimeoutCount:Ou.length,provider:ao,model:Jo});const ug=ws.current?.({prompt:So,signature:qo,source:zt,messagePreview:m1(Kr,Yr,An)})??!1;return or.current=null,ug?(Q("preview_blocked_active_repair",{requestId:P,reason:`${zt}_repair_requested`,message:"Preview remains locked until clean build convergence"}),!0):(hi("failed",gi),!1)};let kt=Ic(de,Zo).filter(Oe=>Y(Oe));const qr=kt.find(Oe=>Yu.has(Oe.code));if(qr){const Oe=Sd(qr);Oe&&await Ph(qr,Oe)&&(de=j.files.get(),kt=Ic(de,Zo).filter(Et=>Y(Et)),Q("prebuild_validation_recomputed_after_local_only_repair",{requestId:P,repairIteration:D,repairedValidationCode:qr.code,remainingValidationIssueCount:kt.length,validationCodes:kt.map(Et=>Et.code)}))}let Ri=kt.filter(Oe=>!Yu.has(Oe.code));const $s=Ri.find(Oe=>Oe.code==="auth-runtime-disabled");if($s){const Oe=Sd($s);Oe&&await Eh($s,Oe)&&(de=j.files.get(),Ri=Ic(de,Zo).filter(Et=>Y(Et)&&!Yu.has(Et.code)),Q("prebuild_validation_recomputed_after_local_repair",{requestId:P,repairIteration:D,remainingValidationIssueCount:Ri.length,validationCodes:Ri.map(Et=>Et.code)}))}const Ma=Wr(de,"prebuild",20);let Jn=Ma.issues;if(Jn.length>0){const Oe=Wne(Jn);Oe&&await G0(Jn,Oe)&&(de=j.files.get(),Jn=Wr(de,"prebuild",20).issues,Q("prebuild_import_integrity_recomputed_after_local_repair",{requestId:P,repairIteration:D,remainingImportIssueCount:Jn.length,issueCodes:Jn.map(zt=>zt.code)}))}if(Jn.length>0)return Q("prebuild_import_integrity_issues",{requestId:P,repairIteration:D,importIssueCount:Jn.length,issueCodes:Jn.map(Oe=>Oe.code)}),Wt("prebuild",[],[],Jn),await Rt([],[],Jn,"import_integrity",Ma);const Go=Ri.filter(Oe=>T1(Oe));Go.length>0&&D===0&&(Q("prebuild_validation_deferred_until_build",{requestId:P,repairIteration:D,validationIssueCount:Go.length,validationCodes:Go.map(Oe=>Oe.code)}),Wt("prebuild",[],Go,[])),bt.trim()&&gn("INSTALLING_DEPENDENCIES",{errorMessage:null});const on=await V0(P);if(on&&($.push(on),At(on),$l(on)))return Q("dependency_install_timeout_reported",{requestId:P,repairIteration:D,timedOutCommands:Pl([on]),message:"Dependency installation timed out after generated files were saved; preview remains unavailable until required packages finish installing."}),Zm({requestId:P,repairIteration:D,timedOutCommands:[on]});const vl=D>0?"BUILD_VERIFICATION":"BUILDING";gn(vl,{errorMessage:null}),Q(hs.BUILD_REPAIR_CYCLE_STARTED,{requestId:P,repairIteration:D,phase:vl,source:D>0?"repair_verification":"initial_build"});let ti=ZA(j.files.get());const yl=Dre(bt)&&ti.length>0;let Ii=!1,As=null;if(yl){const Oe=performance.now();try{const Ze=await Ore(j.files.get(),ti),Et=[];for(const Rr of Ze)try{Rr.targetAlreadyExists||await j.writeFile(Rr.targetFilePath,Rr.content),await j.deleteFile(Rr.sourceFilePath),Et.push(Rr)}catch(vn){Q("workspace_jsx_extension_repair_failed",{requestId:P,repairIteration:D,sourceFilePath:Rr.sourceFilePath,targetFilePath:Rr.targetFilePath,error:vn instanceof Error?vn.message:String(vn)})}Et.length>0&&(ti=ZA(j.files.get()),Q("workspace_jsx_extension_repair_applied",{requestId:P,repairIteration:D,repairs:Et.map(Rr=>({sourceFilePath:Rr.sourceFilePath,targetFilePath:Rr.targetFilePath,reusedExistingTarget:Rr.targetAlreadyExists})),message:"JSX source files were moved to JSX-capable extensions before build validation."}));const zt=await Mre(j.files.get(),ti);As={stage:"syntax",command:`in-page syntax preflight (${ti.length} files)`,exitCode:zt.length>0?1:0,output:$re(zt)},Ii=zt.length===0,$.push(As),At(As),Q("workspace_syntax_preflight_completed",{requestId:P,repairIteration:D,sourceFileCount:ti.length,issueCount:zt.length,exitCode:As.exitCode,elapsedMs:Math.round(performance.now()-Oe),execution:"in_page_parser"})}catch(Ze){Q("workspace_syntax_preflight_unavailable",{requestId:P,repairIteration:D,sourceFileCount:ti.length,elapsedMs:Math.round(performance.now()-Oe),error:Ze instanceof Error?Ze.message:String(Ze),message:"The in-page syntax parser was unavailable, so normal build validation will continue."})}}else Q("workspace_syntax_preflight_skipped",{requestId:P,repairIteration:D,sourceFileCount:ti.length,reason:ti.length===0?"no_supported_source_files":"vite_or_esbuild_not_declared"});let bn;if(As&&As.exitCode!==0)bn=As,Q("workspace_full_validation_skipped_after_syntax_failure",{requestId:P,repairIteration:D,exitCode:As.exitCode,message:"The fast syntax preflight found a blocking source error, so typecheck and build were skipped and the diagnostic will be sent directly to repair."});else if(bn=await Tu("build","npm",["run","build"]),$.push(bn),At(bn),bn.exitCode===0&&(Ii=!0),bn.exitCode===0&&He){const Oe=await Tu("typecheck","npx",["tsc","--noEmit","--pretty","false","--skipLibCheck"]);$.push(Oe),At(Oe)}else He?Q("typecheck_skipped_after_inconclusive_build",{requestId:P,repairIteration:D,buildExitCode:bn.exitCode,buildTimedOut:$l(bn),message:"Typecheck was skipped because build did not finish successfully; its diagnostics would be redundant and would delay preview recovery on a
2249slow connection."}):Q("typecheck_skipped",{requestId:P,repairIteration:D,packageDeclaresTypeScript:Xe,hasTypeScriptConfig:vt,hasGeneratedTypeScriptSource:vr,reason:Xe?"no_app_typescript_config_or_source":"typescript_not_declared_in_package_json"});const Ui=$.filter($l);Ui.length>0&&Q("workspace_command_timeouts_detected",{requestId:P,repairIteration:D,timedOutCommands:Pl(Ui),message:"Workspace command timeouts will not be treated as generated-app diagnostics or sent to Qwen."});const zn=use($),fi=Ic(j.files.get(),Zo).filter(Oe=>Y(Oe)&&!Yu.has(Oe.code)),yr=j.files.get(),vc=Wr(yr,"postbuild",20),pi=vc.issues;Q(hs.BUILD_REPAIR_CYCLE_COMPLETED,{requestId:P,repairIteration:D,buildExitCode:bn.exitCode,buildStage:bn.stage,commandCount:$.length,buildIssueCount:zn.length,validationIssueCount:fi.length,importIssueCount:pi.length,timedOutCommandCount:Ui.length,totalIssueCount:zn.length+fi.length+pi.length}),Q("aggregated_error_count",{requestId:P,repairIteration:D,buildIssueCount:zn.length,validationIssueCount:fi.length,importIssueCount:pi.length,timedOutCommandCount:Ui.length}),Wt("postbuild",zn,fi,pi);const Dh=zn.length>0,og=fi.length>0,mi=pi.length>0,ag=fi.map(Oe=>Oe.code),Es=fi.filter(Oe=>T1(Oe)),Oa=Ui.filter(Oe=>Oe.stage==="install"||Oe.stage==="build"),Mh=Dh||Es.length>0||mi,et=p$({timedOutStages:Oa.map(Oe=>Oe.stage),syntaxPreflightPassed:Ii,buildIssueCount:zn.length,validationIssueCount:Es.length,importIssueCount:pi.length}),ut=bn.exitCode===0&&dse(zn)&&Es.length===0&&pi.length===0&&Oa.length===0;return ut&&Q("preview_fallback_available_typecheck_only",{requestId:P,repairIteration:D,buildIssueCount:zn.length,buildExitCode:bn.exitCode,message:"The app build passed and only typecheck diagnostics remain; preview can open if automatic repair stalls."}),Oa.length>0&&(et||!Mh)?(Q("workspace_command_timeout_blocked_qwen_repair",{requestId:P,repairIteration:D,timedOutCommands:Pl(Oa),message:et?"Full validation timed out after syntax passed. Static validation findings are not being used to turn this timeout into a code failure; preview fallback is starting.":"Build/install timeout did not include repairable app diagnostics, so validation is using the timeout fallback without Qwen repair."}),Zm({requestId:P,repairIteration:D,timedOutCommands:Oa,syntaxPreflightPassed:Ii})):!Dh&&!mi&&Es.length===0?(og&&Q("postbuild_validation_warnings_non_blocking",{requestId:P,repairIteration:D,validationIssueCount:fi.length,validationCodes:ag,message:"Build passed and no import issues remain; non-build-blocking validation warnings will not trigger Qwen repair or keep preview locked."}),z0({requestId:P,repairIteration:D,source:og?"post_stream_build_validation_warnings":"post_stream_build_validation_complete",validationIssues:fi})):(Q(hs.PREVIEW_BLOCKED_UNCLEAN_BUILD,{requestId:P,repairIteration:D,buildIssueCount:zn.length,validationIssueCount:Es.length,importIssueCount:pi.length,validationCodes:Es.map(Oe=>Oe.code),message:"Preview blocked: build/validation/import issues detected"}),Q(hs.PREVIEW_UNLOCK_BLOCKED_UNCLEAN_BUILD,{requestId:P,repairIteration:D,buildIssueCount:zn.length,validationIssueCount:Es.length,importIssueCount:pi.length,validationCodes:Es.map(Oe=>Oe.code),totalIssueCount:zn.length+Es.length+pi.length,message:"Preview unlock blocked: build is not clean - zero issues required for preview"}),await Rt(zn,Es,pi,"post_stream_build_validation",vc,{allowPreviewWithCurrentWorkspace:ut,reason:"build_passed_typecheck_only_diagnostics"}))},[Eh,G0,tg,Y0,K0,q0,lt,V0,mt,Pt,Q,hi,Me,ei,dt,Tu,z0,gn,Y,Vo,Zm,ot?.repairIteration]),Hi=x.useCallback(P=>{const D=P.prompt.trim(),$={...P,prompt:D};if(!D)return St.current="unavailable",!1;const W=Date.now(),J=Ei.current;for(const[Re,Le]of J)W-Le.lastAttemptAt>sne&&J.delete(Re);const re=J.get(P.signature),de=Math.max(1,Math.floor(P.maxAttempts??nne));if(!!re&&re.count>=de&&W-re.lastAttemptAt<Jy){qe.current=null,St.current="suppressed_signature";const Re=`signature:${P.signature}`,Le="Automatic repair stopped because the same diagnostic signature was requested repeatedly without converging.";return Tn.current!==Re&&(Tn.current=Re,Q("auto_repair_signature_suppressed",{source:P.source,count:re.count,maxAttempts:de,cooldownMs:Jy,signature:P.signature.slice(0,240),message:(P.messagePreview||"").slice(0,240)})),lt==="build"&&(Pt||mt)&&Vo({requestId:Mt.current?.id??0,source:"post_stream_build_validation",repairIteration:ot?.repairIteration??fr.current,summary:`${Le} ${P.messagePreview||"The remaining error is shown in diagnostics."}
2249`,buildIssueCount:0,validationIssueCount:0,importIssueCount:0}),!1}if(fr.current>=rne){qe.current=null,St.current="suppressed_depth";const Re="Automatic repair stopped because the workspace hit the repair depth limit.";return Tn.current!==P.signature&&(Tn.current=P.signature,Q("auto_repair_limit_reached",{source:P.source,depth:fr.current,signature:P.signature.slice(0,240),message:(P.messagePreview||"").slice(0,240)})),lt==="build"&&(Pt||mt)&&Vo({requestId:Mt.current?.id??0,source:"post_stream_build_validation",repairIteration:ot?.repairIteration??fr.current,summary:`${Re} ${P.messagePreview||"The remaining error is shown in diagnostics."}`,buildIssueCount:0,validationIssueCount:0,importIssueCount:0}),!1}if(B||yt||T){if((Or.current||zr.current)&&P.source==="action_alert:runtime")return!0;const Re=qe.current?.signature===P.signature;return qe.current?.source==="action_alert:runtime"&&P.source==="action_alert:runtime"||(qe.current=$,St.current="queued",Re||Q("auto_repair_queued",{source:P.source,message:(P.messagePreview||"").slice(0,160),signature:P.signature.slice(0,240),provider:ao,model:Jo})),!0}if(!nn.current)return St.current="unavailable",!1;if(qe.current=null,Bt.current=$,Tn.current=null,J.set(P.signature,{count:(re?.count??0)+1,lastAttemptAt:W}),J.size>ine){let Re=null,Le=Number.POSITIVE_INFINITY;for(const[at,bt]of J)bt.lastAttemptAt<Le&&(Le=bt.lastAttemptAt,Re=at);Re&&J.delete(Re)}return fr.current+=1,Pr.current+=1,Or.current=!0,zr.current=!1,Nt(!1),Q("auto_repair_triggered",{source:P.source,message:(P.messagePreview||"").slice(0,160),signature:P.signature.slice(0,240),depth:fr.current,provider:ao,model:Jo}),M("repair"),U(!0),oe(0),R(!0),St.current="sent",Ve.setKey("previewLocked",!0),j.setPreviewStarting(!1),j.setPreviewVisible(!1),j.currentView.get()==="preview"&&j.currentView.set("code"),so(D,"repair",{resumeExisting:!0}),nn.current(void 0,D,{skipPromptQualification:!0}).catch(Re=>{mr.error("Failed to send auto-repair prompt to LLM",Re),St.current="unavailable",io(),R(!1),U(!1)}),!0},[B,so,lt,io,T,mt,yt,Pt,Q,Vo,ot?.repairIteration]);x.useEffect(()=>{ws.current=Hi},[Hi]),x.useEffect(()=>{const P=Ys.current;Ys.current=se.connected,!(P===null||P===!0||!se.connected)&&h&&Q("stripe_connected_checkout_binding_ready",{mode:se.mode,webhookConfigured:se.webhookConfigured})},[h,Q,se]),x.useEffect(()=>{if(B||yt||T||!nn.current)return;const P=qe.current;P&&(Q("auto_repair_queue_flushed",{source:P.source,message:(P.messagePreview||"").slice(0,160),signature:P.signature.slice(0,240),provider:ao,model:Jo}),Hi(P))},[B,T,yt,Q,Hi]);const Na=x.useCallback(()=>{Ln.current!==null&&(window.clearTimeout(Ln.current),Ln.current=null)},[]),X0=x.useCallback(()=>{Na(),Lr.current.clear(),Nn.current=!1},[Na]),kh=x.useCallback(async P=>{Na();const D=[...Lr.current.values()].sort((kt,qr)=>kt.capturedAt-qr.capturedAt),$=j.files.get(),W=Ic($,Zo).filter(kt=>Y(kt)&&!Yu.has(kt.code)),J=zy($,{includeWarnings:!1,limit:Zo*2}),re=J.issues,de=Dne($,D);if(D.length===0&&W.length===0&&re.length===0)return Nn.current=!1,!1;const _e=Mne(D,W,re),Re=j.restoreProgress.get(),Le=!!Re?.some(kt=>kt.status==="failed"),at=!!Re?.some(kt=>kt.status==="running"||kt.status==="pending"&&!Le),bt=j.previews.get().some(kt=>kt.ready),Xe=j.hasPendingFileActions(),vt=j.hasRecentFileActionActivity(Lf),vr=!!or.current||Xe||vt,He=N==="repair"&&(Or.current||zr.current||B||yt||T||Qt),At=D.length>0&&W.length===0&&re.length===0&&D.every(kt=>yL(kt)),Wt=re.length===0&&(D.some(kt=>jne(kt))||Re?.some(kt=>kt.status==="failed"&&(kt.id==="install-dependencies"||/dependenc/i.test(kt.label||""))));if(At)return Lr.current.clear(),Nn.current=!1,Q("auto_repair_batch_skipped_preview_infrastructure",{reason:P,signature:_e.slice(0,240),runtimeAlertCount:D.length,runtimeAlerts:Kb(D),phase:j.builderLifecyclePhase.get(),hasReadyPreview:bt,previewCount:j.previews.get().length,message:"Preview startup/readiness infrastructure alerts are logged but not sent to Qwen because code repair cannot fix preview transport or interrupted start state."}),bt&&(j.showWorkbench.set(!0),j.currentView.set("preview"),j.requestPreviewRefresh(),j.refreshAllPreviews(),dt("preview_infrastru
2249cture_alert_ready_preview")),!1;if(Wt)return Lr.current.clear(),Nn.current=!1,j.actionAlert.set(void 0),dt("dependency_infrastructure_alert"),Q("auto_repair_batch_skipped_dependency_infrastructure",{reason:P,signature:_e.slice(0,240),runtimeAlertCount:D.length,validationIssueCount:W.length,importIssueCount:re.length,validationCodes:W.map(kt=>kt.code),runtimeAlerts:Kb(D),restoreSteps:Re?.map(kt=>({id:kt.id,status:kt.status,label:kt.label}))||[],phase:j.builderLifecyclePhase.get(),message:"Dependency setup or preview tooling is unavailable, so automatic code repair is suppressed until the generated app can start."}),!1;if(Ne&&at&&!bt||vr||B||yt||T||He)return Nn.current=!0,Ln.current=window.setTimeout(()=>{Ln.current=null,kh(`${P}:retry`)},Gb),Q("auto_repair_batch_deferred",{reason:P,runtimeAlertCount:D.length,validationIssueCount:W.length,importIssueCount:re.length,historyRestoring:Ne,restoreBlocking:at,hasReadyPreview:bt,workspaceStillSettling:vr,hasPendingFileActions:Xe,hasRecentFileActionActivity:vt,awaitingResponse:B,isLoading:yt,fakeLoading:T,repairInFlight:He}),!1;const Wr=Bne({originalRequest:kl(Me),runtimeAlerts:D,validationIssues:W,importIssues:re,importGraphReport:J,runtimeSourceSnippets:de});return re.length>0&&Q(hs.REPAIR_PAYLOAD_INCLUDES_MISSING_DEPENDENCIES,{source:"auto_repair_batch",importIssueCount:re.length,missingDependencyCount:J.missingDependencyCount}),Q("auto_repair_batch_flushed",{reason:P,signature:_e.slice(0,240),runtimeAlertCount:D.length,validationIssueCount:W.length,importIssueCount:re.length,runtimeSourceSnippetCount:de.length,validationCodes:W.map(kt=>kt.code),runtimeAlerts:Kb(D),validationIssues:Xb(W),importIssues:Jb(re),provider:ao,model:Jo}),Hi({prompt:Wr,signature:_e,source:"auto_repair_batch",messagePreview:One(D,W,re),maxAttempts:D.length>0?1:void 0})?(D.length>0&&(Sr.current=!1),Lr.current.clear(),Nn.current=!1,!0):(Nn.current=!0,Ln.current=window.setTimeout(()=>{Ln.current=null,kh(`${P}:retry`)},Gb),!1)},[N,B,Na,T,Ne,yt,Q,Me,dt,Qt,Y,Hi]),pc=x.useCallback(P=>{Nn.current=!0,Na(),Ln.current=window.setTimeout(()=>{Ln.current=null,kh(P)},Gb)},[Na,kh]);x.useEffect(()=>{Nn.current&&(B||yt||T||pc("request-idle"))},[B,T,yt,pc]),x.useEffect(()=>()=>{Na()},[Na]);const J0=x.useCallback(async(P,D)=>{if(as.current===P)return!1;as.current=P;try{await j.waitForPendingActions();const $=j.files.get(),W=P1($),J=rie($,D||W.filePath)||sie($,D||W.filePath);return J?(or.current=null,Q("local_scaffold_entry_repair_applied",{requestId:P,filePath:J.filePath,componentCount:J.componentNames.length,components:J.componentNames.slice(0,12),repairKind:J.repairKind}),await j.writeFile(J.filePath,J.content),dn("local-scaffold-entry-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0):!1}catch($){return mr.error("Failed local scaffold entry repair",$),!1}finally{as.current===P&&(as.current=null)}},[tg,Q,dn]),Ph=x.useCallback(async(P,D)=>{if(P.code==="auth-runtime-disabled")return Eh(P,D);if(P.code==="auth-global-lockout"){if(ur.current===D)return!0;ur.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=[hn($,P.filePath)||P.filePath,hn($,"app.config.json"),hn($,"public/app.config.json")].filter((re,de,_e)=>!!re&&_e.indexOf(re)===de),J=[];for(const re of W){const de=Kt($,re),_e=Pse(de);!_e||_e.content===de||J.push({filePath:re,content:_e.content,disabledRequireLogin:_e.disabledRequireLogin,removedProtectedPaths:_e.removedProtectedPaths})}if(J.length===0)return!1;for(const re of J)await j.writeFile(re.filePath,re.content);return Q("local_auth_global_lockout_repair_applied",{filePaths:J.map(re=>re.filePath),disabledRequireLogin:J.some(re=>re.disabledRequireLogin),removedProtectedPaths:J.flatMap(re=>re.removedProtectedPaths)}),dn("local-auth-global-lockout-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local auth global lockout repair",$),!1}finally{ur.current===D&&(ur.current=null)}}if(P.code==="invalid-protected-app-schema-import"){if(_s.current===D)return!0;_s.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=ese($,P);if(!W)return!1;for(const J of W.writes)await j.writeFile(J.filePath,J.content);
2249return Q("local_invalid_protected_app_schema_import_repair_applied",{schemaPath:W.schemaPath,rewrittenFiles:W.rewrittenFiles,writeCount:W.writes.length,invalidIdentifiers:P.invalidIdentifiers}),dn("local-invalid-protected-app-schema-import-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local invalid protected appSchema import repair",$),!1}finally{_s.current===D&&(_s.current=null)}}if(P.code==="invalid-local-api-endpoint"){if(di.current===D)return!0;di.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=hn($,P.filePath)||P.filePath,J=Kt($,W),re=kse(J,P.endpointPath,P.suggestionPaths);return re?(Q("local_invalid_local_api_endpoint_repair_applied",{filePath:W,endpointPath:P.endpointPath,replacementPath:re.replacementPath,replacementCount:re.replacementCount}),await j.writeFile(W,re.content),dn("local-invalid-api-endpoint-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0):!1}catch($){return mr.error("Failed local invalid local API endpoint repair",$),!1}finally{di.current===D&&(di.current=null)}}if(P.code==="missing-local-db-api-plugin"){if(wr.current===D)return!0;wr.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=hn($,P.filePath)||P.filePath,J=hn($,"vite.local-db.ts")||"vite.local-db.ts",re=Kt($,W),de=Kt($,J),_e=l1.test(re)&&c1.test(re),Re=a1.test(de),Le=_e?re:_1(Me,W,Xe=>l1.test(Xe)&&c1.test(Xe)),at=Re?de:_1(Me,J,Xe=>a1.test(Xe));if(!Le||!at)return!1;const bt=[];if(re!==Le&&bt.push({filePath:W,content:Le}),de!==at&&bt.push({filePath:J,content:at}),bt.length===0)return!1;for(const Xe of bt)await j.writeFile(Xe.filePath,Xe.content);return Q("local_missing_local_db_api_plugin_repair_applied",{filePaths:bt.map(Xe=>Xe.filePath),recoveredFromHistory:!0}),dn("local-missing-local-db-plugin-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local missing createLocalDbApiPlugin repair",$),!1}finally{wr.current===D&&(wr.current=null)}}if(P.code==="missing-package-dependency"){if(Rn.current===D)return!0;Rn.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=hn($,P.packageJsonPath)||P.packageJsonPath,J=Kt($,W),re=vre(J,P.missingPackages),de=!!re&&P.packageNames.every(_e=>re.repairedPackageNames.includes(_e));return!re||!de?!1:(Q("local_missing_package_dependency_repair_applied",{filePath:W,packageNames:re.repairedPackageNames}),await j.writeFile(W,re.content),dn("local-missing-package-dependency-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0)}catch($){return mr.error("Failed local missing package dependency repair",$),!1}finally{Rn.current===D&&(Rn.current=null)}}if(P.code==="placeholder-navigation-link"){if(In.current===D)return!0;In.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=[...new Set(P.placeholderLinks.map(re=>re.filePath))],J=[];for(const re of W){const de=hn($,re)||re,_e=Kt($,de),Re=Ese(_e,P.knownRoutePaths);if(!Re||Re.unresolvedLabels.length>0)return!1;J.push({filePath:de,content:Re.content,repairedLabels:Re.repairedLabels})}if(J.length===0)return!1;for(const re of J)await j.writeFile(re.filePath,re.content);return Q("local_placeholder_navigation_repair_applied",{filePaths:J.map(re=>re.filePath),knownRoutePaths:P.knownRoutePaths,repairedLabels:J.flatMap(re=>re.repairedLabels)}),dn("local-placeholder-navigation-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local placeholder navigation repair",$),!1}finally{In.current===D&&(In.current=null)}}if(P.code==="protected-runtime-syntax-corruption"){if(jt.current===D)return!0;jt.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=hn($,P.filePath)||P.filePath,J=Kt($,W);if(!J.includes(P.brokenFragment))return!1;const re=J.split(P.brokenFragment).join(P.fixedFragment);return Q("local_protected_runtime_repair_applied",{filePath:W,issueCode:P.code}),await j.writeFile(W,re),dn("local-protected-runtime-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0}catch($){return mr.error("Failed local protected runtime repair",$),!1}finally{jt.current===D&&(jt.current=null)}}if(P.code!=="persisted-local-db-duplicate-rows")return!1;if($i.current===D)return!0;$i.current=D;try{await j.waitForPendingActions();const $=j.files.get(),W=hn($,P.filePath)||P.filePath,J=Kt($,W),re=ate(J);return re?(Q("local_persisted_local_db_dedupe_applied",{filePath:W,removedRowCount:re.removedRowCount,tables:re.updatedTables}),await j.writeFile(W,re.content),dn("local-persisted-local-db-dedupe-repair"),j.requestPreviewRefresh(),j.refreshAllPreviews(),!0):!1}catch($){return mr.error("Failed local persisted local-db dedupe repair",$),!1}finally{$i.current===D&&($i.current=null)}},[Eh,Q,dn]);x.useEffect(()=>{if(yt||B||T||Cs)return;const P=or.current;if(!P)return;const D=Tl(Me,!1),$=Tl(n,!1);if(D===$){or.current=null,Q("post_request_validation_skipped_history_replay",{requestId:P.requestId,messageCount:Me.length}),dt("post_request_validation_skipped_history_replay");return}const W=window.setTimeout(()=>{(async()=>{const J=or.current;if(!J||J.requestId!==P.requestId)return;await eg("post_request_validation");const re=or.current;if(!(!re||re.requestId!==P.requestId)&&Vr.current!==re.requestId){Vr.current=re.requestId,or.current=null;try{const de=P1(j.files.get());if(de.detected){const _e=await J0(re.requestId,de.filePath);if(!_e){const Re=[...Me].reverse().find(bt=>bt.role==="assistant"),Le=Re?Gi(Re):"",at=C1(Le);if(Q("local_scaffold_entry_repair_skipped",{requestId:re.requestId,filePath:de.filePath,patternId:de.patternId,fileActionCount:at.fileActionCount,actionLikeLineCount:at.actionLikeLineCount}),at.fileActionCount===0&&at.targetedRepairBlockCount===0&&at.shellActionCount>0){const bt=kl(Me),vt=`shell-only-no-file-actions::${Tt(bt||Le).slice(0,600)}`,vr=W0(Le,bt);Q("assistant_payload_shell_only_actions",{requestId:re.requestId,shellActionCount:at.shellActionCount,startActionCount:at.startActionCount}),Hi({prompt:vr,signature:vt,source:"assistant_payload:shell_only_no_file_actions",messagePreview:Le.slice(0,160)})}else if(at.targetedRepairBlockCount===0&&!at.hasBoltAction&&(at.actionLikeLineCount>0||at.codeLikeLineCount>=4||at.containsCodeFence&&at.codeLikeLineCount>=2)){const bt=kl(Me),vt=`missing-file-actions::${Tt(bt||Le).slice(0,600)}`,vr=F0(Le,bt);Hi({prompt:vr,signature:vt,source:"assistant_payload:missing_file_actions",messagePreview:Le.slice(0,160)})}else if(at.fileActionCount>0){const bt=de.filePath||"src/App.tsx",Xe=kl(Me),vt=Ere(Le),vr=Xe||Le;if(vt.protectedOnly){Q("assistant_payload_protected_only_file_actions",{requestId:re.requestId,filePaths:vt.filePaths,scaffoldFilePath:bt});const Wt=`protected-only-file-actions::${bt}::${Tt(`${vr}::${vt.filePaths.join("|")}`).slice(0,700)}`,Wr=U0(Xe,bt,vt.filePaths);Hi({prompt:Wr,signature:Wt,source:"assistant_payload:protected_only_file_actions",messagePreview:Le.slice(0,160)});return}const He=`placeholder-still-present::${bt}::${Tt(`${vr}::${vt.writablePaths.join("|")}`).slice(0,700)}`,At=H0(Xe,bt,vt.filePaths);Hi({prompt:At,signature:He,source:"assistant_payload:placeholder_still_present",messagePreview:Le.slice(0,160)})}}_e&&(await eg("post_request_validation:after_local_scaffold_repair"),await new Promise(Re=>window.setTimeout(Re,dne)),await Ru(re.requestId));return}await Ru(re.requestId)}finally{Vr.current===re.requestId&&(Vr.current=null)}}})().catch(J=>{if(mr.warn("Failed to persist settled generation workspace state",J),Vr.current===P.requestId&&(Vr.current=null),or.current=null,Object.entries(j.files.get()).some(([de,_e])=>{const Re=fn(de);return!!_e&&_e.type==="file"&&!_e.isBinary&&!Re.startsWith("node_modules/")&&!Re.startsWith(".git/")&&/\.(?:html?|[jt]sx?|vue|astro|svelte|mdx?|css)$/i.test(Re)})){Vt.current={requestId:P.requestId,forceRestart:!0},gn("READY_FOR_PREVIEW",{errorMessage:null}),j.setBuilderLifecyclePhase("READY_FOR_PREVIEW"),j.showWorkbench.set(!0),j.setPreviewDevice("responsive"),j.clearRestoreProgressForPreviewHandoff("post-request-validation-error-preview-fallback"),j.actionAlert.set(void 0),dt("post_request_validation_error_preview_fallback"),Q("post_request_validation_error_preview_fallback_queued",{requestId:P.requestId,errorMessage:J instanceof Error?J.message:String(J),message:"Post-stream validation failed after files were written, so preview is opening with the generated
2249workspace instead of leaving the build failed."});return}gn("FAILED",{errorMessage:J instanceof Error?J.message:"Post-stream validation failed."}),j.setBuilderLifecyclePhase("FAILED"),dt("post_request_validation_error")})},fne);return()=>{window.clearTimeout(W)}},[J0,B,T,n,yt,Q,Me,dt,Ru,Cs,F0,W0,H0,U0,lt,mt,Pt,Hi,eg]),x.useEffect(()=>{const P=ae;if(!P||P.revision<=Fi.current||yt||B||T||Cs||Te||Ne||Qt||N==="repair"||z||![...Me].reverse().find(W=>W.role==="assistant")||Me.length===0)return;const $=window.setTimeout(()=>{(async()=>{const W=j.workspacePersistenceRequest.get();if(!W||W.revision!==P.revision||W.revision<=Fi.current)return;const J=lt==="build"&&(Pt||mt);Q("workspace_recovery_persistence_dispatch",{revision:W.revision,source:W.source,reason:W.reason,updatedFiles:W.updatedFiles,flushRemote:J,messageCount:Me.length}),await j.waitForPendingActions(),await new Promise(re=>window.setTimeout(re,gne)),await ei(Me,{persistSnapshot:!0,flushRemote:J}),Fi.current=W.revision,j.clearWorkspacePersistenceRequest(W.revision),Q("workspace_recovery_persistence_complete",{revision:W.revision,source:W.source,reason:W.reason,updatedFiles:W.updatedFiles,flushRemote:J,messageCount:Me.length})})().catch(W=>{mr.warn("Failed to persist preview auto-recovery workspace state",W)})},mne);return()=>{window.clearTimeout($)}},[N,B,lt,T,Ne,mt,yt,Pt,Q,Me,Te,z,ei,Qt,Cs,ae]),x.useEffect(()=>{if(!B)return;const P=Date.now();oe(0);const D=window.setInterval(()=>{oe(Math.floor((Date.now()-P)/1e3))},1e3);return()=>{window.clearInterval(D)}},[B]),x.useEffect(()=>{if(!pe||pe.source!=="preview"&&pe.source!=="terminal")return;const P=LD(bl),D=Tt([pe.source,pe.title,pe.description,pe.content].join(` 2250`)).slice(0,900),$=j.restoreProgress.get(),W=!!$?.some(_e=>_e.status==="failed"),J=!!$?.some(_e=>_e.status==="running"||_e.status==="pending"&&!W),re=j.previews.get().some(_e=>_e.ready);if(Ne)if(!J||re)Ve.setKey("historyRestoring",!1);else{const _e=Date.now();_e-De.current>=5e3&&(De.current=_e,Q("auto_repair_suppressed_history_restore",{alertSource:pe.source,title:pe.title})),j.clearAlert();return}if(!P){const _e=Date.now();_e-De.current>=5e3&&(De.current=_e,Q("preview_issue_suppressed",{alertSource:pe.source,title:pe.title,phase:bl})),j.clearAlert();return}const de=$ne(pe);if(!pe.autoAskGeniePrompt&&!de){Q("preview_issue_not_auto_repaired",{alertSource:pe.source,title:pe.title,phase:bl,reason:"no_auto_repair_prompt",summary:String(pe.description||pe.title||"").slice(0,200)}),j.clearAlert();return}if(!pe.autoAskGeniePrompt&&de&&Q("preview_issue_auto_repair_prompt_synthesized",{alertSource:pe.source,title:pe.title,phase:bl,summary:String(pe.description||pe.title||"").slice(0,200)}),ki.current===D){j.clearAlert();return}if(ki.current=D,Q("preview_issue_reported",{alertSource:pe.source,title:pe.title,phase:bl,summary:String(pe.description||pe.title||"").slice(0,200)}),lt==="build"&&(Pt||mt)){const _e=Sr.current?"empty-response-runtime-alert":"runtime-alert";Lr.current.set(D,{key:D,source:pe.source,title:String(pe.title||"Preview Build Failed"),description:String(pe.description||""),content:String(pe.content||pe.description||pe.title||""),capturedAt:Date.now()}),pc(`${_e}:${pe.source}`),Q("runtime_alert_batched_for_auto_repair",{alertSource:pe.source,title:pe.title,phase:bl,reason:_e})}j.clearAlert()},[pe,lt,bl,Ne,mt,Pt,Q,pc]),x.useEffect(()=>{if(!!!q?.some(J=>J.status==="failed")){je.current=null;return}if(pe||Ne||N==="repair"||B||yt||T||Qt)return;const D=dre(j.files.get());if(!D)return;const $=Sd(D);if(!$)return;const W=`restore-failure::${$}`;je.current!==W&&(je.current=W,Q("restore_failure_validation_issue",{code:D.code,filePath:D.filePath,relatedFiles:D.relatedFilePaths}),(async()=>{if(!await Ph(D,$)){if(!Y(D)){je.current=null,Q("restore_failure_validation_issue_deferred",{code:D.code,filePath:D.filePath,relatedFiles:D.relatedFilePaths});return}pc(`restore-failure-validation:${D.code}`)}})().catch(J=>{mr.warn("Failed to trigger restore failure validation repair",J),je.current===W&&(je.current=null)}))},[pe,N,Ph,B,T,Ne,yt,Q,q,Qt,pc,Y]),x.useEffect(()=>{const P=Ge.current;Ge.current=Ne,!(!P||Ne)&&(pe||N==="repair"||B||yt||T||Qt||mr.info("History restore completed - skipping validation auto-repair to preserve previous state"))},[pe,N,Ph,B,T,Ne,yt,Q,Qt,Hi]);const UL=()=>{const P=d.current;P&&(P.scrollTop=P.scrollHeight)},mc=P=>Ve.get().aborted||Dn.current!==P,rg=()=>{Q("request_aborted_by_user"),Dn.current+=1,Au(),hi("canceled","Build canceled by user."),qe.current=null,or.current=null,Vt.current=null,Ar.current=null,Ut.current="",X0(),io(),ku([]),R(!1),U(!1),oe(0),Ft(!1),Pu(),Gr.current="",Ve.get().previewLocked&&Ve.setKey("previewLocked",!1),Ve.setKey("aborted",!0),j.abortActiveGenerationProgress(),Mt.current=null,Wa.logProvider("Chat response aborted",{component:"Chat",action:"abort",model:ct,provider:ht.name})},zL=x.useCallback(P=>{const D=or.current?.requestId??Mt.current?.id??xr.current,$=Mt.current?.id??null,W=lt==="build"&&(Pt||mt)&&D>0;return qe.current=null,Vt.current=null,Ar.current=null,Ut.current="",Ks.current=null,R(!1),U(!1),oe(0),Ft(!1),ku([]),xt({type:"warning",title:P.title||"Generation paused",description:P.message,content:P.content,provider:ht.name,errorType:void 0}),Q("output_data_inspection_recovery_started",{requestId:D,canValidateWorksp
2250ace:W,provider:P.provider||ht.name,message:P.message}),W?(or.current=null,Vr.current===D||(Vr.current=D,(async()=>{try{await j.waitForPendingActions(),await Ru(D)}catch(J){mr.error("Failed to validate workspace after output inspection interruption",J);const re=J instanceof Error?J.message:"Validation failed after the model provider stopped the draft.";hi("failed",re),j.setBuilderLifecyclePhase("FAILED"),Ve.setKey("previewLocked",!1),xt({type:"error",title:"Validation failed",description:re,provider:ht.name,errorType:"unknown"}),Q("output_data_inspection_recovery_failed",{requestId:D,message:re})}finally{Vr.current===D&&(Vr.current=null),$!==null&&Mt.current?.id===$&&(Mt.current=null)}})()),!0):(Mt.current=null,!0)},[lt,mt,Pt,Q,hi,ht.name,Ru]),VL=x.useCallback((P,D="chat")=>{mr.error(`${D} request failed`,P),Au(),R(!1),U(!1),oe(0),Ft(!1),j.abortActiveGenerationProgress();let $={message:"An unexpected error occurred",isRetryable:!0,statusCode:500,provider:ht.name,type:"unknown",retryDelay:0};if(P.message){const _e=rw(P.message);if(_e)$={...$,..._e};else try{const Re=JSON.parse(P.message);Re.error||Re.message?$={...$,...Re}:$.message=P.message}catch{$.message=P.message}}let W="unknown",J=$.title||"Request Failed";const re=$.type==="safety_block",de=$.type===pv;re?(J=$.title||"Request Blocked",W=void 0):de?(J=$.title||"Generation paused",W=void 0):$.statusCode===401||String($.message||"").toLowerCase().includes("api key")?(W="authentication",J="Authentication Error"):$.statusCode===429||String($.message||"").toLowerCase().includes("rate limit")?(W="rate_limit",J="Rate Limit Exceeded"):String($.message||"").toLowerCase().includes("quota")?(W="quota",J="Quota Exceeded"):$.statusCode>=500&&(W="network",J="Server Error"),Wa.logError(`${D} request failed`,P,{component:"Chat",action:"request",error:$.message,context:D,retryable:$.isRetryable,errorType:W,provider:ht.name}),Q("request_failed",{context:D,message:$.message,statusCode:$.statusCode,retryable:$.isRetryable}),or.current=null,Vt.current=null,Ar.current=null,Ut.current="",Mt.current=null,xt({type:re||de?"warning":"error",title:J,description:$.message,content:$.content,provider:ht.name,errorType:W}),ku([])},[Q,ht.name,Au]),GL=x.useCallback(()=>{xt(void 0)},[]),ng=x.useCallback(()=>{so("continue generation",N==="repair"?"repair":N==="update"?"update":"build",{resumeExisting:!0}),sn("continue generation",!0),Q("continue_generation_triggered"),Q("stream_started",{source:"continue_generation"}),Dn.current+=1,G.current=!1,Ve.setKey("aborted",!1),j.resumeIncomingProgress(),xt(void 0),R(!0),U(!0),oe(0),Eu()},[N,so,Q,Eu,sn]);x.useEffect(()=>{if(!Pt&&!mt||!Cs||yt||T||B)return;const P=Me.filter(J=>J.role==="assistant"),$=P[P.length-1]?.id;if(!$||os.current===$)return;const W=window.setTimeout(()=>{os.current=$,ng()},3e3);return()=>{window.clearTimeout(W)}
2250},[B,ng,T,mt,yt,Pt,Me,Cs]),x.useEffect(()=>{const P=d.current;if(P){if(P.style.height=`${Ah}px`,P.style.minHeight=`${Ah}px`,P.style.maxHeight=`${Ah}px`,ka.length===0){P.style.overflowY="hidden",P.scrollTop=0;return}P.style.overflowY="auto"}},[Ah,Dt?.email,t,rr,Ne,ka,an,d]);const Th=x.useCallback(async()=>{if(!h){Ve.setKey("started",!0),j.showWorkbench.set(!0),m(!0);try{const P=document.querySelector("#intro"),D=document.querySelector("#examples"),$=[];if(D&&$.push(ci(D,{opacity:0,display:"none"},{duration:.1})),P&&$.push(ci(P,{opacity:0,flex:1},{duration:.2,ease:Ds})),$.length===0)return;Promise.all($).catch(W=>{console.warn("Intro transition animation failed:",W)})}catch(P){console.warn("Intro transition animation failed:",P)}}},[ci,h]),sg=x.useCallback(P=>{if(!Pt&&!mt&&!Dr)return;const D=h||Ve.get().started;Ve.setKey("backgroundHomeActive",!1),Ve.setKey("backgroundHomeReturnPath",""),Ve.setKey("showChat",!0),Ve.setKey("started",!0),j.showWorkbench.set(!0),m(!0),Dr?j.currentView.set("preview"):j.currentView.get()==="preview"&&j.previews.get().length===0&&j.currentView.set("code"),!D&&(Q("run_animation_triggered",{chatStarted:h,stage:P}),Th())},[h,mt,Dr,Pt,Q,Th]),gc=(P,D=[])=>[{type:"text",text:P}],Q0=P=>{const D={};return Object.keys(P).forEach($=>{const W=P[$];W?.S!==void 0?D[$]=W.S:W?.N!==void 0?D[$]=W.N:D[$]=W}),D},Rh=x.useCallback(async P=>{const D=TM(F,{enabled:!0,setupRequired:P.setupRequired??Z?.setupRequired??!1,connectionType:P.connectionType||Z?.connectionType||"connect",mode:se.mode,webhookConfigured:se.webhookConfigured});D!==F&&(await j.writeFile(fg,D),j.requestWorkspacePersistence("stripe integration updated",1,"admin-settings"))},[F,Z?.connectionType,Z?.setupRequired,se.mode,se.webhookConfigured]),qL=x.useCallback(P=>{Rh({setupRequired:!1,connectionType:P}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ty,{detail:{integrationId:"stripe",intent:P}}))},[Rh]),KL=x.useCallback(()=>{Rh({setupRequired:!1})},[Rh]),Iu=x.useCallback(async(P,D="cloudmysite forms integration updated")=>{const $=RM(F,{provider:xl,plan:"free",source:_l,...P});$!==F&&(await j.writeFile(fg,$),j.requestWorkspacePersistence(D,1,"admin-settings"))},[F]),La=x.useCallback(async P=>{if(!Pi)return;const D=IM(P),$=Kt(L,px),W=DM(),J=Kt(L,mx),re=Kt(L,Fh),de=NM(re),_e=Kt(L,gx),Re=LM(_e);let Le=0;$!==D&&(await j.writeFile(px,D),Le+=1),J!==W&&(await j.writeFile(mx,W),Le+=1),de&&re!==de&&(await j.writeFile(Fh,de),Le+=1),Re&&_e!==Re&&(await j.writeFile(gx,Re),Le+=1),Le>0&&j.requestWorkspacePersistence("cloudmysite form workspace helpers updated",Le)},[Pi,L]),ig=x.useCallback(async P=>{if(!Dt?.email)return null;const D=P?.intent||bx(P?.prompt)||xo||vx(K)||yx(),$=_x({routeScope:ds,routeChatId:t,prompt:P?.prompt,publishedDomain:l?.publishedDomain}),W=`${$.siteId}::${$.domain}::${D.intentType}`;if(!P?.force&&xs.current.has(W))return null;if(!P?.force&&pg(K,D))return await La(K),K||null;xs.current.add(W);try{await Iu({enabled:!0,status:"provisioning",provider:xl,intentType:D.intentType,formName:D.formName,plan:"free",notificationEmail:Dt.email,email:Dt.email,siteId:$.siteId,domain:$.domain,source:_l,lastError:void 0}),await La({...K,enabled:!0,status:"provisioning",provider:xl,intentType:D.intentType,formName:D.formName,plan:"free",notificationEmail:Dt.email,email:Dt.email,siteId:$.siteId,domain:$.domain,source:_l,lastError:void 0});const J=await jf();if(!J)throw new Error("Unable to provision CloudMySite Forms because the authenticated session token is missing.");const re=await fetch(MM,{method:"POST",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({siteId:$.siteId,domain:$.domain,formName:D.formName,intentType:D.intentType})}),de=await re.json().catch(()=>({}));if(!re.ok)throw new Error(de.error||"Unable to provision CloudMySite Forms.");const _e={enabled:!0,status:"connected",provider:xl,intentType:D.intentType,formName:de.form_name||D.formName,plan:(de.plan==="free","free"),formId:de.form_id,endpoint:de.endpoint,uploadEndpoint:de.upload_endpoint,existing:de.existing===!0,notificationEmail:de.notification_email||de.email||Dt.email,email:de.notification_email||de.email||Dt.email,siteId:de.site_id||$.siteId,domain:de.domain||$.domain,source:_l};return await Iu(_e),await La(_e),j.requestPreviewRefresh(),j.refreshAllPreviews(),_e}catch(J){const re=J instanceof Error?J.message:"Unable to provision CloudMySite Forms.",de={enabled:!0,status:"error",provider:xl,intentType:D.intentType,formName:D.formName,plan:"free",notificationEmail
2250:Dt.email,email:Dt.email,siteId:$.siteId,domain:$.domain,source:_l,lastError:re};return await Iu(de),await La(de),de}finally{xs.current.delete(W)}},[Dt?.email,K,ds,t,L,l?.publishedDomain,Iu,La,xo]);x.useEffect(()=>{!Pi||!(K?.enabled===!0||no)||La(K)},[Pi,K,La,no]),x.useEffect(()=>{if(lt!=="build"||!Dt?.email||!(no||K?.enabled===!0))return;const D=vx(K)||xo||yx();if((I==="connected"||I==="provisioning")&&pg(K,D))return;const $=`${t||ds}::${no?"component":"admin"}::${D.intentType}`;Nr.current!==$&&(Nr.current=$,setTimeout(()=>{ig({intent:D}).catch(W=>{console.warn("[Chat] Auto form provisioning failed (non-blocking):",W?.message||W)})},2e3))},[Dt?.email,lt,K,ds,I,t,ig,xo,no]);const Da=x.useCallback(()=>{Wn(null),is(!1),Jt(null)},[]);x.useEffect(()=>{lt==="build"&&(Pt||mt)||Da()},[lt,Da,mt,Pt]);const Ih=x.useCallback(async P=>{let D;const $={...P,appId:P.appId||e||t||$r||void 0,chatId:P.chatId||t||e||$r||void 0};try{D=await Fl("/api/prompt-qualification",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}catch(J){if(!Ti(J))throw J;sv(yg()),vs(!0),D=await new Promise((re,de)=>{let _e=0;const Re=120,Le=()=>{Fl("/api/prompt-qualification",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}).then(at=>{vs(!1),re(at)}).catch(at=>{if(!Ti(at)){de(at);return}if(_e+=1,_e>=Re){de(at);return}setTimeout(Le,1e3)})};setTimeout(Le,1e3)})}const W=await D.json().catch(()=>null);if(!D.ok){const J=W&&typeof W=="object"&&"error"in W&&W.error?W.error:"Prompt qualification failed.";throw W&&typeof W=="object"&&"code"in W&&W.code==="token_limit_reached"&&nr(),new Error(J)}return W&&typeof W=="object"&&"usageSummary"in W&&W.usageSummary&&Rx(W.usageSummary),W},[$r,t,nr,e]),Nh=x.useCallback(async P=>{const D=zre({result:P.result,projectKind:P.projectKind,rawPrompt:P.originalPrompt,defaultsApproved:P.usedDefaults});Da(),await nn.current?.({},D,{skipPromptQualification:!0,qualifiedPromptContent:D,userVisiblePromptContent:Vre({originalPrompt:P.originalPrompt,result:P.result,projectKind:P.projectKind,answerText:P.answerText,usedDefaults:P.usedDefaults}),originalUserPrompt:P.originalPrompt})},[Da]),YL=x.useCallback(async()=>{if(!(!Ir||Hn)){is(!0),Jt(null);try{const P=await Ih({mode:"finalize",prompt:Ir.originalPrompt,originalPrompt:Ir.originalPrompt,projectKind:Ir.projectKind,useSmartDefaults:!0,priorQualification:Ir.result});if(P.status==="needs_clarification"){Wn({...Ir,result:P});return}await Nh({originalPrompt:Ir.originalPrompt,result:P,projectKind:Ir.projectKind,usedDefaults:!0})}catch(P){Jt(P instanceof Error?P.message:"Unable to use smart defaults right now.")}finally{is(!1)}}},[Nh,Ir,Hn,Ih]),Z0=async(P,D,$)=>{const W=$?.qualifiedPromptContent??D??ka,J=W.trim(),re=Dr&&!W.includes(s2)?i2(J):W,de=$?.uploadedFiles??b,_e=$?.imageDataList??p,Re=$?.assetReferences??v,Le=de.length>0||_e.length>0||Re.length>0,at=de.length>vi||_e.length>vi||Re.length>vi;if(Ct){Se.info(Ct);return}if(!(Dr?J:re.trim())&&!Le)return;if(at){Se.error(`You can attach up to ${vi} assets to a prompt right now.`);return}const bt=$?.userVisiblePromptContent??(Dr?J:re.trim()),Xe=bt||"Use the attached workspace asset metadata as context for this request.",vt=bt||void 0,vr=$?.originalUserPrompt&&$.originalUserPrompt.trim().length>0?$.originalUserPrompt.trim():Dr&&J||void 0,He=re.trim()||Xe,At=kc(Xe),Wt=Fe&&rr==="/",Rt=!(Wt?!1:Me.length>0||n.length>0||!!t)&&!At,kt=At?"repair":Rt?"build":"update",qr=Hre({isNewsletterChat:Dr,chatMode:lt,requestMode:kt,isRepairPrompt:At,skipPromptQualification:$?.skipPromptQualification}),Ri=At&&kl(Me)||Xe,$s=oM(He),Ma=$s.blocked&&$s.category==="invalid_input"&&qr;if($s.blocked&&!Ma){or.current=null,R(!1),U(!1),oe(0),xt({type:"warning",title:$s.title,description:$s.description,content:$s.content,provider:ht.name}),Q("prompt_safety_blocked",{category:$s.category,promptPreview:Un(Xe)});return}OD();const Jn=$M(Ri),Go=BM(Ri),on=bx(Ri),vl=FM(Ri,on),ti=on!==null&&(lt==="build"||!vl),yl=on!==null&<!=="build"&&vl,Ii=_x({routeScope:ds,routeChatId:t,prompt:Xe,publishedDomain:l?.publishedDomain}),As=yl?{...K||{},enabled:!0,status:on&&pg(K,on)?"connected":"provisioning",provider:xl,intentType:on?.intentType,formName:on?.formName||xx,plan:"free",notificationEmail
2250:Dt?.email,email:Dt?.email,siteId:K?.siteId||Ii.siteId,domain:K?.domain||Ii.domain,source:_l}:void 0;if(lt==="build"&&yl&&(await Iu({enabled:!0,status:As?.status||"provisioning",provider:xl,intentType:on?.intentType,formName:on?.formName||xx,plan:"free",notificationEmail:Dt?.email,email:Dt?.email,siteId:Ii.siteId,domain:Ii.domain,source:_l,lastError:void 0}),Pi&&await La(As),setTimeout(()=>{ig({prompt:Xe,intent:on}).catch(et=>{console.warn("[Chat] Form provisioning failed (non-blocking, will retry later):",et?.message||et)})},3e3)),j.setReloadedMessagesConfig([],{skipActionReplay:!1}),j.clearAlert(),At||(qe.current=null,Bt.current=null,X0(),io(),Ei.current.clear(),qs.current.clear(),xt(void 0),fr.current=0,Tn.current=null),yt){if(typeof D=="string"&&D.trim().length>0){Q("request_ignored_while_loading",{reason:"in_flight_request",source:"auto_or_alert"});return}rg();return}Ve.setKey("aborted",!1);const bn=Dn.current+1;Dn.current=bn,G.current=!1,j.resumeIncomingProgress(),Wt&&(Wa.logDebug("home_new_app_reset_started",{priorPath:Ve.get().backgroundHomeReturnPath||"/"}),Ve.setKey("backgroundHomeActive",!1),Ve.setKey("backgroundHomeReturnPath",""),Ve.setKey("started",!1),Ve.setKey("previewLocked",!1),Ta([]),await j.resetForHomeNewApp(),Wa.logDebug("home_new_app_state_cleared")),M(kt);const Ui=mt?"site":"app";if(qr){const et=C$(Xe);if(!et.ok&&et.resolution!=="qualify"){const ut=et.reason||"Please describe what you want to build.";or.current=null,Da(),Ve.setKey("previewLocked",!1),j.abortActiveGenerationProgress(),R(!1),U(!1),oe(0),Ft(!1),xt({type:"warning",title:ut===Ha?"Describe the app you want to create":"Prompt blocked",description:ut,content:ut,provider:ht.name}),Se.error(ut),Q("build_prompt_unusable",{promptPreview:Un(Xe),reason:ut});return}}if(wt.current=Xe,At||(Gt.current=Xe),$e(),Pt||mt){const{email:et}=await Be();if(!et){ze(Xe);return}Rt&&sg("authenticated_initial_prompt_preflight")}else Dr&&Rt&&sg("newsletter_initial_prompt_preflight");if(lt==="build"&&(Pt||mt)){const et=await Br(Ue);if(!et.allowed){const ut=et.message||Tx(et.summary)||"Your monthly AI token allowance has been reached. Upgrade your plan to create more apps.";Da(),Ve.setKey("previewLocked",!1),j.abortActiveGenerationProgress(),R(!1),U(!1),oe(0),Ft(!1),xt({type:"warning",title:et.code==="token_limit_reached"||Px(et.summary)?"AI tokens reached":"AI token check failed",description:ut,content:ut,provider:ht.name}),Se.error(ut),nr(),Q("runtime_capacity_blocked_before_prompt_qualification",{productType:Ue,planName:et.summary?.planName,monthlyTokenLimit:et.summary?.monthlyTokenLimit,monthlyTokensUsed:et.summary?.monthlyTokensUsed,monthlyTokensRemaining:et.summary?.monthlyTokensRemaining});return}}if(qr&&(Pt||mt)){const{email:et}=await Qe();if(!et){ze(re);return}sg("prompt_qualification")}if(qr){is(!0),Jt(null);try{if(Ir){const ut=await Ih({mode:"finalize",prompt:Ir.originalPrompt,originalPrompt:Ir.originalPrompt,answers:Xe,projectKind:Ir.projectKind,priorQualification:Ir.result});if(Q("prompt_classification_completed",{classification:ut.classification,classificationSource:ut.classificationSource||"unknown",phase:"finalize",reason:ut.reason}),ut.classification==="INVALID_GIBBERISH"){Jt(Ha),Se.error(Ha);return}if(ut.classification==="NEEDS_CLARIFICATION"){Wn({...Ir,result:ut}),Pa("");return}await Nh({originalPrompt:Ir.originalPrompt,result:ut,projectKind:Ir.projectKind,answerText:Xe});return}const et=await Ih({mode:"qualify",prompt:Xe,projectKind:Ui});if(Q("prompt_classification_completed",{classification:et.classification,classificationSource:et.classificationSource||"unknown",phase:"qualify",reason:et.reason}),et.classification==="INVALID_GIBBERISH"){Da(),xt({type:"warning",title:"Describe the app you want to create",description:Ha,content:Ha,provider:ht.name}),Se.error(Ha);return}if(et.classification==="READY"){await Nh({originalPrompt:Xe,result:et,projectKind:Ui});return}Wn({originalPrompt:Xe,projectKind:Ui,result:et}),Pa("");return}catch(et){const ut=et instanceof Error?et.message:"Unable to qualify this prompt right now. Please try again.";Jt(ut),Se.error(ut);return}finally{is(!1)}}const zn=Pt||mt,fi=Rt&&zn;
2250if(zn&&(Ve.setKey("previewLocked",!0),j.currentView.set("code"),j.setPreviewDevice("responsive"),Rt&&!At&&j.resetProgressForNewRequest()),fi&&(j.showWorkbench.set(!0),Q("run_animation_triggered",{chatStarted:h,stage:"pre_subscription_validation"}),Th()),Pt&&Rt){const{email:et}=await Qe();if(!et){ze(re);return}try{const Oe=await v1(IA({email:et,product_type:"genie ai"}),b1,"Genie AI plan lookup"),Ze=typeof Oe=="string"?JSON.parse(Oe):Oe,Et=Array.isArray(Ze)?Ze:Array.isArray(Ze?.items)?Ze.items:Array.isArray(Ze?.Items)?Ze.Items:Ze?.items&&typeof Ze.items=="object"?Object.values(Ze.items):Ze?.data&&typeof Ze.data=="object"?Array.isArray(Ze.data)?Ze.data:Object.values(Ze.data):[],Rr=(Array.isArray(Et)?Et:[]).filter(Yr=>!!Yr&&typeof Yr=="object").map(Q0);let vn=null;Rr.length>0&&(vn=Rr.find(Yr=>!Yr.repo_name)||null);const Kr=vn?.id;(typeof Kr=="string"||typeof Kr=="number")&&Xn(String(Kr))}catch(ut){console.warn("[chat] D1 Genie AI subscription preflight failed; continuing build request.",ut)}}if(mc(bn))return;if(mt&&Rt){const{email:et}=await Qe();if(!et){ze(re);return}try{const Oe=await v1(IA({email:et,product_type:"genie-builder"}),b1,"Genie Builder plan lookup"),Ze=typeof Oe=="string"?JSON.parse(Oe):Oe,Et=Array.isArray(Ze)?Ze:Array.isArray(Ze?.items)?Ze.items:Array.isArray(Ze?.Items)?Ze.Items:Ze?.items&&typeof Ze.items=="object"?Object.values(Ze.items):Ze?.data&&typeof Ze.data=="object"?Array.isArray(Ze.data)?Ze.data:Object.values(Ze.data):[],Rr=(Array.isArray(Et)?Et:[]).filter(Yr=>!!Yr&&typeof Yr=="object").map(Q0);let vn=null;Rr.length>0&&(vn=Rr.find(Yr=>!Yr.repo_name)||null);const Kr=vn?.id;(typeof Kr=="string"||typeof Kr=="number")&&ui(String(Kr))}catch(ut){console.warn("[chat] D1 Genie Builder subscription preflight failed; continuing build request.",ut)}}if(mc(bn))return;let yr=He;if(wn&&(console.log("Selected Element:",wn),yr=`${He} 2251 2252${Mse(wn)}`,Q("selected_element_context_appended",{tagName:wn.tagName,selector:wn.selector,elementPath:wn.elementPath,hasText:!!(wn.textContent||wn.displayText)})),lt==="build"&&Jn&&(yr=`${yr} 2253 2254${VM()}`,Q("stripe_integration_context_deferred_to_admin",{connected:se.connected,mode:se.mode,webhookConfigured:se.webhookConfigured})),lt==="build"&&yl&&(yr=`${yr} 2255 2256${WM(As,{useBuiltInComponent:Pi})}`,Q("cloudmysite_forms_context_appended",{connected:HM(As),status:fx(As),useBuiltInComponent:Pi})),lt==="build"&&ti&&on&&(yr=`${yr} 2257 2258${UM(on)}`,Q("cloudmysite_forms_context_deferred_to_admin",{intentType:on.intentType})),lt==="build"&&Go&&(yr=`${yr} 2259 2260${zM()}`,Q("newsletter_context_deferred_to_admin",{promptPreview:Un(Ri)})),lt==="build"&&!At){const et=$se(yr,kt);yr=`${yr} 2261 2262${Bse(et)}`,Q(hs.SELF_CONTAINED_GENERATION_MODE_SELECTED,{requestMode:kt,isInitialPrompt:Rt,mode:et})}const vc=!Rt,pi=lt==="build"&&vc&&!At?Rse(yr,L):null;pi&&(yr=`${yr} 2263 2264${pi}`,Q("auth_routing_context_appended",{promptPreview:Un(Xe)}));const Dh=yr.trim();if(!/^\*auto-repair/i.test(Dh)&<==="build"&&Rt){const et=vZ(re);et&&(yr=et,Q("game_prompt_auto_normalized",{originalLength:re.length,normalizedLength:et.length}))}let mi=[];try{mi=await ne({uploadedFiles:de,imageDataList:_e,assetReferences:Re})}catch(et){const ut=et instanceof Error?et.message:"Unable to prepare the attached media.";Q("composer_asset_reference_prepare_failed",{message:ut,uploadedFileCount:de.length,imageDataCount:_e.length}),Se.error(ut),R(!1),U(!1),oe(0),Ft(!1);return}if(mi.length>0&&!yr.includes(AO)){const et=EO(mi,{newsletter:Dr});yr=`${yr.trim()} 2265 2266${et}`,Q("composer_asset_manifest_appended",{assetReferenceCount:mi.length,mediaKinds:mi.map(ut=>ut.mediaKind||ut.assetType||Lx(ut.mimeType)),hasPublicUrls:mi.map(ut=>!!ut.publicUrl)})}vc||j.setGeneratedProjectKind(sw(yr,"app"));const ag=sn(yr,vc),Es=et=>me(et,mi);if(lt==="build"){const et=Jn&&!se.connected||ti;Ks.current=et?{requestId:ag,needsStripe:Jn&&!se.connected,needsForms:ti}:null}else Ks.current=null;if(lt==="build"&&(Pt||mt)){so(yr,kt,{resumeExisting:Cs||kt==="repair"}),Q("stream_started",{requestMode:kt,resumeExisting:Cs||kt==="repair"});const et={id:`workspace-seed-${Date.now().toString(36)}`,role:"user",content:`[Model: ${ct}] 2267 2268[Provider: ${ht.name}] 2269 2270${yr}`,parts:gc(`[Model: ${ct}] 2271 2272[Provider: ${ht.name}] 2273 2274${yr}`,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr};await u?.({seedMessages:[et],description:r||void 0,metadata:{...l||{},historyStatusOverride:kt==="build"?"processing":l?.historyStatusOverride==="published"||l?.historyStatusOverride==="running"?l.historyStatusOverride:"draft"},timestamp:new Date().toISOString()})}else if(Dr&&Rt){const et=Ad(J||Xe,$r),ut={id:`newsletter-seed-${Date.now().toString(36)}`,role:"user",content:`[Model: ${ct}] 2275 2276[Provider: ${ht.name}] 2277 2278${yr}`,parts:gc(`[Model: ${ct}] 2279 2280[Provider: ${ht.name}] 2281 2282${yr}`,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr};await u?.({seedMessages:[ut],description:et.workspaceTitle,metadata:{...l||{},primaryArtifactId:et.primaryArtifactId,workspaceTitle:et.workspaceTitle,historyStatusOverride:"processing"},timestamp:new Date().toISOString()})}if(zn&<==="build"?or.current={requestId:Mt.current?.id??xr.current}:or.current=null,U(!0),oe(0),R(!0),Wa.logProvider("Chat request queued",{component:"Chat",action:"request_start",model:ct,provider:ht.name,chatStarted:Rt?!1:h,flowType:Dr?"newsletter":mt?"builder":"app"}),fi||(Q("run_animation_triggered",{chatStarted:h}),Th()),Rt&&!Dr){if(Ft(!0),pt){Q("starter_template_selection_start");const{template:Et,title:zt}=await JQ({message:yr||Xe,isEleventy:mt,fallbackTemplateName:mt?uo:np});if(mc(bn)){Ft(!1);return}if(Q("starter_template_selection_complete",{template:Et,title:zt||""}),Et!=="blank"){Q("starter_template_import_start",{template:Et});const Rr=yr||Xe,vn=await TA(Et,zt,{prompt:Rr}).catch(An=>(An.message.includes("rate limit")?Se.warning(`Rate limit exceeded. Skipping starter template 2283 Continuing with blank template`):Se.warning(`Failed to import starter template 2284 Continuing with blank template`),Q("starter_template_import_failed",{template:Et,error:An?.message||"Unknown error"}),null)),Kr=mt||Et==="Vanilla Vite"||Et==="Phaser Vite"?uo:np,Yr=vn||(Et!==Kr?await TA(Kr,zt,{prompt:Rr}).catch(()=>null):null);if(mc(bn)){Ft(!1);return}if(!vn&&Yr&&Q("starter_template_import_fallback_used",{attemptedTemplate:Et,fallbackTemplate:Kr}),Yr){const{assistantMessage:An,userMessage:lg,metadata:gi,protectedFiles:Nu,runtimeFiles:Lu,starterFiles:ja}=Yr;Q("starter_template_import_complete",{template:vn?Et:Kr,imported:!0,repo:gi?.repo||"",source:gi?.source||"",fetcher:gi?.fetcher||"",localPath:gi?.localPath||"",fileCount:gi?.fileCount||0,deployWorkflow:!!gi?.deployWorkflow,protectedFiles:Array.isArray(Nu)?Nu.length:0});const Du=`[Model: ${ct}] 2285 2286[Provider: ${ht.name}] 2287 2288${yr}`,Mu=Date.now(),Ou=`1-${Mu}`,So=`2-${Mu}`,qo=`3-${Mu}`;j.ignoreProgressForMessage(So);const yc=[{id:Ou,role:"user",content:Du,parts:gc(Du,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr},{id:So,role:"assistant",content:An},{id:qo,role:"user",content:`[Model: ${ct}] 2289 2290[Provider: ${ht.name}] 2291 2292${lg}`,annotations:["hidden"]}];j.setReloadedMessagesConfig([So],{skipActionReplay:!0}),Ta(yc),Jm(yc,!1);const Oh=j.queueStarterTemplateRuntimeFiles(ja||Lu||[]);Q("starter_template_actions_queued",{template:vn?Et:Kr,fileCount:gi?.fileCount||0,runtimeFileCount:Lu?.length||0}),Oh.then(ug=>{Q(ug?"starter_template_actions_applied":"starter_template_actions_cancelled",{template:vn?Et:Kr,fileCount:gi?.fileCount||0,runtimeFileCount:Lu?.length||0})}),j.requestPreviewNavigation("/",So,"assistant-page-update");const ri=await Ee({uploadedFiles:de,imageDataList:_e,assetReferences:mi}),cg=ri.attachments?{experimental_attachments:ri.attachments}:void 0;if(mc(bn)){Ft(!1);return}rt("chat_reload_attachments_prepared",{uploadedFileCount:ri.uploadedFileCount,imageDataCount:ri.imageDataCount,assetReferenceCount:ri.assetReferenceCount,attachmentCount:ri.attachmentCount,attachmentContentTypes:ri.attachmentContentTypes}),Q("chat_reload_dispatched",{hasTemplateSeed:!0,hasAttachments:!!cg?.experimental_attachments,imageDataCount:ri.imageDataCount,assetReferenceCount:ri.assetReferenceCount,attachmentCount:ri.attachmentCount}),Eu(cg),Pa(""),wc.remove(ju),ml(),Xm(),d.current?.blur();return}Q("starter_template_import_complete",{template:Et,imported:!1})}}
2292else Q("starter_template_selection_skipped",{reason:"auto_select_disabled",conversationId:t??"",initialMessageCount:n.length,currentMessageCount:Me.length});const et=`[Model: ${ct}] 2293 2294[Provider: ${ht.name}] 2295 2296${yr}`,ut=await Ee({uploadedFiles:de,imageDataList:_e,assetReferences:mi}),Oe=ut.attachments;if(mc(bn)){Ft(!1);return}const Ze=`${new Date().getTime()}`;Ta([{id:Ze,role:"user",content:et,parts:gc(et,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr}]),j.requestPreviewNavigation("/",Ze,"assistant-page-update"),rt("chat_reload_attachments_prepared",{uploadedFileCount:ut.uploadedFileCount,imageDataCount:ut.imageDataCount,assetReferenceCount:ut.assetReferenceCount,attachmentCount:ut.attachmentCount,attachmentContentTypes:ut.attachmentContentTypes}),Q("chat_reload_dispatched",{hasTemplateSeed:!1,hasAttachments:!!Oe,imageDataCount:ut.imageDataCount,assetReferenceCount:ut.assetReferenceCount,attachmentCount:ut.attachmentCount}),Eu(Oe?{experimental_attachments:Oe}:void 0),Pa(""),wc.remove(ju),ml(),Xm(),d.current?.blur();return}!At&<==="build"&&Q("starter_template_selection_skipped",{reason:"not_initial_prompt",conversationId:t??"",initialMessageCount:n.length,currentMessageCount:Me.length,chatStarted:h}),DL!=null&&Ta(Me.slice(0,-1));const Oa=Dr?void 0:j.getModifiedFiles(),Mh=_e.length>0;if(Ve.setKey("aborted",!1),Oa!==void 0){const et=Mh?"":DD(Oa,`${Date.now()}`),ut=`[Model: ${ct}] 2297 2298[Provider: ${ht.name}] 2299 2300${et}${yr}`,Oe=await Ee({uploadedFiles:de,imageDataList:_e,assetReferences:mi}),Ze=Oe.attachments?{experimental_attachments:Oe.attachments}:void 0;Ym({id:Zb(),role:"user",content:ut,parts:gc(ut,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr},Ze),rt("chat_append_attachments_prepared",{uploadedFileCount:Oe.uploadedFileCount,imageDataCount:Oe.imageDataCount,assetReferenceCount:Oe.assetReferenceCount,attachmentCount:Oe.attachmentCount,attachmentContentTypes:Oe.attachmentContentTypes}),Q("chat_append_dispatched",{includesModifiedFiles:!0,includesModifiedFileArtifact:!Mh,hasAttachments:!!Ze?.experimental_attachments,imageDataCount:Oe.imageDataCount,assetReferenceCount:Oe.assetReferenceCount,attachmentCount:Oe.attachmentCount}),j.resetAllFileModifications()}else{const et=`[Model: ${ct}] 2301 2302[Provider: ${ht.name}] 2303 2304${yr}`,ut=await Ee({uploadedFiles:de,imageDataList:_e,assetReferences:mi}),Oe=ut.attachments?{experimental_attachments:ut.attachments}:void 0;Ym({id:Zb(),role:"user",content:et,parts:gc(et,_e),annotations:Es(),userVisibleContent:vt,originalUserPrompt:vr},Oe),rt("chat_append_attachments_prepared",{uploadedFileCount:ut.uploadedFileCount,imageDataCount:ut.imageDataCount,assetReferenceCount:ut.assetReferenceCount,attachmentCount:ut.attachmentCount,attachmentContentTypes:ut.attachmentContentTypes}),Q("chat_append_dispatched",{includesModifiedFiles:!1,hasAttachments:!!Oe?.experimental_attachments,imageDataCount:ut.imageDataCount,assetReferenceCount:ut.assetReferenceCount,attachmentCount:ut.attachmentCount})}Pa(""),wc.remove(ju),ml(),Xm(),d.current?.blur()};nn.current=Z0;const bc=x.useCallback((P,D)=>{const $=P.trim();if($){if(yt||T||B||!nn.current){ce.current={prompt:$,overrides:D?.overrides},!D?.queued&&D?.toastWhenQueued!==!1&&Se.info("Queued security fix request. It will be sent when the current request finishes.");return}lt!=="build"&&bs("build"),nn.current(void 0,$,D?.overrides).catch(W=>{mr.error("Failed to dispatch external prompt",W),ce.current={prompt:$,overrides:D?.overrides}})}},[B,lt,T,yt]);x.useEffect(()=>{const P=D=>{const W=D.detail?.prompt;W&&bc(W)};return window.addEventListener(Py,P),()=>{window.removeEventListener(Py,P)}},[bc]);const Lh=x.useCallback(P=>{if(!P?.prompt||Je.current===P.id)return;Je.current=P.id;const D=Array.isArray(P.imageDataList)?P.imageDataList.filter(W=>W.startsWith("data:image/")).slice(0,1):[],$=Array.isArray(P.assetReferences)?P.assetReferences.filter(CO).slice(0,ld):[];bc(P.prompt,{overrides:D.length>0||$.length>0?{imageDataList:D,assetReferences:$}:void 0,toastWhenQueued:!1})},[bc]);x.useEffect(()=>{Lh(OO())},[Lh]),x.useEffect(()=>{const P=D=>{Lh(D.detail)};return window.addEventListener(Ox,P),()=>{window.removeEventListener(Ox,P)}},[Lh]),x.useEffect(()=>{if(yt||T||B)return;const P=ce.current;P&&(ce.current=null,bc(P.prompt,{queued:!0,overrides:P.overrides}))},[B,bc,T,yt]);const XL=P=>{Km(P)},JL=x.useCallback(sh(P=>{const D=P.target.value.trim();wc.set(ju,D,{expires:30})},1e3),[]);x.useEffect(()=>{const P=wc.get("apiKeys");P&&$n(JSON.parse(P))},[]);const QL=Or.current||Qt||N==="repair"&&B?void 0:pe,ZL=Fe&&rr==="/"?!0:h?be:!0,ex=P=>P.replace(/<!-- system:[a-z-]+ -->[\s\S]*?<!-- \/system:[a-z-]+ -->/g,"").trim(),eD=x.useMemo(()=>xd(Me.map((P,D)=>{if(P.role==="user"){const $=ex(P.content),W=typeof P.userVisibleContent=="string"?P.userVisibleContent:lm(P.content);return{...P,...W?{userVisibleContent:W}:{},content:$,parts:P.parts?.map(J=>J.type==="text"?{...J,text:W||ex(J.text)}:J)}}return{...P,content:D0[D]||""}})),[Me,D0]),tD=x.useCallback(P=>{RA.get()!==P&&RA.set(P)},[]),rD=x.useCallback(P=>{const D=String(P||"").trim();if(!D)return;const $=ka.trim()?`${ka.trim()} 2305${D}`:D;Km({target:{value:$}}),requestAnimationFrame(()=>{d.current?.focus(),d.current?.setSelectionRange($.length,$.length)})},[Km,ka,d]);return an&&!Dt?f.jsx(MO,{children:f.jsx(f.Fragment,{})}):Dr&&rr.startsWith("/newsletter/c/")&&(!Ca?.workspace_id||!Ca.publication_id)?f.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#f4f8ff] px-4 py-10",children:f.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-slate-200 bg-white p-6 text-center shadow-sm",children:[f.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-[#fff4e5] text-[#b45309]",children:f.jsx("span",{className:"i-ph:warning-circle-duotone text-2xl","aria-hidden":"true"})}),f.jsx("h1",{className:"mt-4 text-2xl font-semibold text-slate-950",children:"Newsletter context required"}),f.jsx("p",{className:"mt-3 text-sm leading-6 text-slate-600",children:"This newsletter draft is missing workspace context. Open AI Studio from CloudMySite Newsletter or select a workspace."})]})}
2305):f.jsx(yQ,{ref:Os,textareaRef:d,input:ka,showChat:ZL,chatStarted:h,isStreaming:yt||T||B||un?.status==="running",onStreamingChange:tD,awaitingResponse:B,awaitingResponseSeconds:X,awaitingResponseLabel:Dr?"Generating newsletter campaign":N==="repair"?"Genie is fixing the current project issue and updating your preview.":N==="update"?"Updating your app":"Working on app",isFollowUpRequest:N==="update",showResumeGeneration:Cs,onResumeGeneration:ng,enhancingPrompt:OL,promptEnhanced:jL,sendMessage:Z0,activePlanId:mt?null:Ai??null,dreamWeaverToken:mt?Ur??null:null,handleInputChange:P=>{XL(P),JL(P)},handleStop:rg,description:r,importChat:a,exportChat:o,messages:eD,enhancePrompt:()=>{$L(ka,P=>{Pa(P),UL()},ct,ht,Yn)},uploadedFiles:b,imageDataList:p,handleImageFilesSelected:Gm,handleExistingAssetSelected:qm,removeImageAttachment:Cu,clearImageAttachments:ml,assetWorkspaceId:$r,assetLibraryWorkspaceId:Su,readOnlyReason:Ct,actionAlert:QL,clearAlert:()=>j.clearAlert(),deployAlert:Ye,clearDeployAlert:()=>j.clearDeployAlert(),llmErrorAlert:nt,clearLlmErrorAlert:GL,promptQualification:Ir?.result??null,promptQualificationBusy:Hn,promptQualificationError:rn,onUsePromptQualificationDefaults:YL,clearPromptQualification:Da,applyPromptQualificationSuggestion:rD,stripeSetupRequired:fe,openStripeSetup:qL,dismissStripeSetup:KL,data:Zs,chatMode:lt,setChatMode:bs,append:Ym,designScheme:Ae,setDesignScheme:we,selectedElement:wn,setSelectedElement:Bn,addToolResult:ML,metadata:l,updateChatMestaData:c,buildJob:un,onCancelBuild:rg})}),Boe=Object.freeze(Object.defineProperty({__proto__:null,Chat:bse,ChatImpl:LL},Symbol.toStringTag,{value:"Module"}));export{bu as $,qi as A,fo as B,ym as C,pH as D,st as E,QH as F,ul as G,Am as H,_n as I,vu as J,Bc as K,cy as L,PT as M,hT as N,Cr as O,xH as P,Ts as Q,Ip as R,mo as S,rs as T,Us as U,uh as V,bo as W,dr as X,ji as Y,OF as Z,_a as _,Eoe as a,Oc as a0,Sv as a1,KF as a2,Ua as a3,Nk as a4,Cv as a5,Lk as a6,ma as a7,Zi as a8,la as a9,yoe as aA,V5 as aB,z5 as aC,ck as aD,nu as aE,iw as aF,Ay as aG,kb as aH,IC as aI,_I as aJ,kn as aK,Pb as aL,Kf as aM,HG as aN,CI as aO,AI as aP,SI as aQ,EI as aR,nq as aS,IA as aT,XG as aU,JG as aV,WG as aW,Ml as aX,bse as aY,Boe as aZ,Hl as aa,aa as ab,ch as ac,mp as ad,kd as ae,Ak as af,voe as ag,K5 as ah,Xl as ai,nk as aj,moe as ak,gp as al,fm as am,Rk as an,r3 as ao,t3 as ap,Mi as aq,H5 as ar,Ik as as,G5 as at,mk as au,sc as av,GF as aw,r5 as ax,jF as ay,M5 as az,Ci as b,hr as c,UH as d,koe as e,ZH as f,Roe as g,E3 as h,Oq as i,$oe as j,Loe as k,Doe as l,Ms as m,ke as n,_6 as o,Soe as p,Noe as q,Ioe as r,LH as s,he as t,k6 as u,Toe as v,Poe as w,BH as x,$H as y,woe as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.